<?php

namespace App\Services\Grading;

use App\Models\CalendarEvent;
use DateTime;

class HomeworkTrackingCalendarService
{
    public function buildDateRange(string $schoolYear, string $semester): array
    {
        $startYear = null;
        if (preg_match('/\b(20\d{2})\b/', $schoolYear, $m)) {
            $startYear = (int) $m[1];
        }
        if ($startYear === null) {
            $today = new DateTime('today');
            return [$today, $today];
        }

        $nextYear = $startYear + 1;
        $sem = strtolower(trim($semester));

        try {
            if ($sem === 'spring') {
                $start = new DateTime("{$nextYear}-01-25");
                $end = new DateTime("{$nextYear}-05-31");
            } else {
                $start = new DateTime("{$startYear}-09-21");
                $end = new DateTime("{$nextYear}-01-18");
            }
        } catch (\Throwable $e) {
            $today = new DateTime('today');
            return [$today, $today];
        }

        return [$start, $end];
    }

    public function buildSundays(DateTime $start, DateTime $end): array
    {
        if ((int) $start->format('w') !== 0) {
            $start = (clone $start)->modify('next sunday');
        }

        $sundays = [];
        $d = clone $start;
        while ($d <= $end) {
            $sundays[] = $d->format('Y-m-d');
            $d->modify('+7 days');
        }

        return $sundays;
    }

    public function eventDays(string $schoolYear): array
    {
        $events = CalendarEvent::getEventsBySchoolYear($schoolYear) ?? [];
        $eventDays = [];
        foreach ($events as $event) {
            $ymd = substr((string) ($event['date'] ?? ''), 0, 10);
            $no = (int) ($event['no_school'] ?? 0);
            if ($ymd && $no === 1) {
                $eventDays[$ymd] = true;
            }
        }

        return $eventDays;
    }

    public function dateToIndex(array $sundays, array $eventDays): array
    {
        $dateToIndex = [];
        $idx = 0;
        foreach ($sundays as $ymd) {
            if (!isset($eventDays[$ymd])) {
                $idx++;
                $dateToIndex[$ymd] = $idx;
            } else {
                $dateToIndex[$ymd] = null;
            }
        }

        return $dateToIndex;
    }
}
