<?php

namespace App\Services\Attendance;

use Carbon\Carbon;

class SemesterRangeService
{
    public function normalizeSemester(?string $semester): string
    {
        $value = strtolower(trim((string)$semester));

        return match ($value) {
            'fall', 'autumn' => 'Fall',
            'spring' => 'Spring',
            default => '',
        };
    }

    public function getSchoolYearRange(string $schoolYear): array
    {
        [$startYear, $endYear] = $this->parseSchoolYear($schoolYear);

        return [
            Carbon::create($startYear, 9, 1)->toDateString(),
            Carbon::create($endYear, 5, 31)->toDateString(),
        ];
    }

    public function getSemesterRange(string $schoolYear, string $semester): ?array
    {
        [$startYear, $endYear] = $this->parseSchoolYear($schoolYear);
        $semester = $this->normalizeSemester($semester);

        return match ($semester) {
            'Fall' => [
                Carbon::create($startYear, 9, 21)->toDateString(),
                Carbon::create($endYear, 1, 18)->toDateString(),
            ],
            'Spring' => [
                Carbon::create($endYear, 1, 25)->toDateString(),
                Carbon::create($endYear, 5, 31)->toDateString(),
            ],
            default => null,
        };
    }

    public function buildSundayList(string $startDate, string $endDate): array
    {
        $start = Carbon::parse($startDate)->startOfDay();
        $end = Carbon::parse($endDate)->startOfDay();

        if ($start->dayOfWeek !== Carbon::SUNDAY) {
            $start = $start->next(Carbon::SUNDAY);
        }

        $dates = [];
        $cursor = $start->copy();

        while ($cursor->lte($end)) {
            $dates[] = $cursor->toDateString();
            $cursor->addWeek();
        }

        return $dates;
    }

    protected function parseSchoolYear(string $schoolYear): array
    {
        if (preg_match('/^\s*(\d{4})\s*-\s*(\d{4})\s*$/', $schoolYear, $m)) {
            return [(int)$m[1], (int)$m[2]];
        }

        $year = (int) date('Y');
        return [$year, $year + 1];
    }
}