<?php

namespace App\Services\Attendance;

use DateTimeImmutable;
use DateTimeZone;

class AttendanceAutoPublishService
{
    public function timezone(?string $tzFromCfg = null): DateTimeZone
    {
        $tz = $tzFromCfg ?: (class_exists(\Config\School::class)
            ? (config('School')->attendance['timezone'] ?? null)
            : null);

        return new DateTimeZone($tz ?: date_default_timezone_get());
    }

    public function secondSundayAfterEndOfDay(string $ymd, ?string $tz = null): string
    {
        $zone = $this->timezone($tz);
        $day = new DateTimeImmutable($ymd . ' 00:00:00', $zone);

        $weekday = (int) $day->format('w');
        $daysToNextSunday = (7 - $weekday) % 7;
        if ($daysToNextSunday === 0) {
            $daysToNextSunday = 7;
        }

        $firstSunday = $day->modify("+{$daysToNextSunday} days");
        $secondSunday = $firstSunday->modify('+7 days');

        return $secondSunday->setTime(23, 59, 59)->format('Y-m-d H:i:s');
    }

    public function secondSundayBackwardDate(DateTimeImmutable $now, ?string $tz = null): string
    {
        $zone = $this->timezone($tz);
        $inZone = $now->setTimezone($zone);
        $weekday = (int) $inZone->format('w');
        $thisSunday = $inZone->setTime(0, 0, 0)->modify("-{$weekday} days");
        $twoBack = $thisSunday->modify('-14 days');

        return $twoBack->format('Y-m-d');
    }
}
