<?php

namespace App\Repositories;

use App\Contracts\AcademicCalendarRepositoryInterface;
use App\Models\AcademicEvent;
use App\Models\AcademicYear;
use App\Models\SchoolHoliday;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

class AcademicCalendarRepository implements AcademicCalendarRepositoryInterface
{
    public function getAllAcademicYears(): Collection
    {
        return AcademicYear::withCount(['holidays', 'events'])->orderBy('start_date', 'desc')->get();
    }

    public function getActiveAcademicYear(): ?AcademicYear
    {
        return AcademicYear::where('is_active', true)->first();
    }

    public function createAcademicYear(array $data): AcademicYear
    {
        if (!empty($data['is_active'])) {
            AcademicYear::query()->update(['is_active' => false]);
        }

        return AcademicYear::create($data);
    }

    public function getAllHolidays(): Collection
    {
        return SchoolHoliday::with('academicYear')->orderBy('date', 'desc')->get();
    }

    public function isHolidayOrWeekend(string $date): bool
    {
        $carbon = Carbon::parse($date);
        
        // Pengecekan Hari Minggu (Day 0 / Sunday)
        if ($carbon->isSunday()) {
            return true;
        }

        // Pengecekan tabel Hari Libur Sekolah & Nasional
        return SchoolHoliday::whereDate('date', $carbon->toDateString())->exists();
    }

    public function createHoliday(array $data): SchoolHoliday
    {
        return SchoolHoliday::create($data);
    }

    public function getAllEvents(): Collection
    {
        return AcademicEvent::with('academicYear')->orderBy('start_date', 'desc')->get();
    }

    public function createEvent(array $data): AcademicEvent
    {
        return AcademicEvent::create($data);
    }

    public function deleteEvent(int $id): bool
    {
        $event = AcademicEvent::findOrFail($id);

        return (bool) $event->delete();
    }
}
