<?php

namespace App\Services\Settings\SchoolCalendar;

use App\Models\CalendarEvent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class SchoolCalendarQueryService
{
    public function listEvents(array $filters): Collection
    {
        $query = CalendarEvent::query();

        $schoolYear = trim((string) ($filters['school_year'] ?? ''));
        if ($schoolYear !== '') {
            $query->where('school_year', $schoolYear);
        }

        $semester = trim((string) ($filters['semester'] ?? ''));
        if ($semester !== '') {
            $query->where('semester', $semester);
        }

        $sortDir = strtolower((string) ($filters['sort_dir'] ?? 'asc')) === 'desc' ? 'desc' : 'asc';
        $query->orderBy('date', $sortDir)->orderBy('id', 'asc');

        return $query->get();
    }

    public function findEvent(int $id): ?CalendarEvent
    {
        return CalendarEvent::query()->find($id);
    }

    public function filterEventsForAudience(Collection $events, ?string $audience): Collection
    {
        $audience = $audience !== null ? strtolower(trim($audience)) : null;
        if (!in_array($audience, ['parent', 'teacher', 'admin'], true)) {
            return $events;
        }

        return $events->filter(function (CalendarEvent $event) use ($audience) {
            $p = (int) $event->notify_parent;
            $t = (int) $event->notify_teacher;
            $a = (int) $event->notify_admin;
            $ns = (int) $event->no_school;
            $hasAny = ($p + $t + $a) > 0;

            if ($ns === 1) {
                return true;
            }

            if (!$hasAny) {
                return true;
            }

            if ($audience === 'parent') {
                return $p === 1;
            }
            if ($audience === 'teacher') {
                return $t === 1;
            }
            if ($audience === 'admin') {
                return $a === 1;
            }

            return true;
        })->values();
    }
}
