<?php

namespace App\Services\Events;

use App\Models\Event;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class EventListService
{
    public function list(array $filters): array
    {
        $perPage = (int) ($filters['per_page'] ?? 25);
        $page = (int) ($filters['page'] ?? 1);
        $sortBy = (string) ($filters['sort_by'] ?? 'created_at');
        $sortDir = strtolower((string) ($filters['sort_dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';
        $activeOnly = $filters['active'] ?? null;

        $allowedSorts = ['created_at', 'expiration_date', 'event_name'];
        if (!in_array($sortBy, $allowedSorts, true)) {
            $sortBy = 'created_at';
        }

        $query = Event::query();

        if (!empty($filters['school_year'])) {
            $query->where('school_year', (string) $filters['school_year']);
        }
        if (!empty($filters['semester'])) {
            $query->where('semester', (string) $filters['semester']);
        }
        if (!empty($filters['q'])) {
            $term = trim((string) $filters['q']);
            $query->where('event_name', 'like', "%{$term}%");
        }
        if ($activeOnly !== null) {
            $today = now()->toDateString();
            if (filter_var($activeOnly, FILTER_VALIDATE_BOOLEAN)) {
                $query->whereDate('expiration_date', '>=', $today);
            } else {
                $query->whereDate('expiration_date', '<', $today);
            }
        }

        $paginator = $query
            ->orderBy($sortBy, $sortDir)
            ->paginate($perPage, ['*'], 'page', $page);

        $activeCount = $this->activeCount($filters);

        return [
            'events' => $paginator,
            'pagination' => $this->paginationPayload($paginator),
            'active_count' => $activeCount,
        ];
    }

    public function find(int $eventId, ?string $schoolYear = null): ?Event
    {
        $query = Event::query()->whereKey($eventId);
        if ($schoolYear !== null && $schoolYear !== '') {
            $query->where('school_year', $schoolYear);
        }

        return $query->first();
    }

    private function activeCount(array $filters): int
    {
        $query = Event::query()->whereDate('expiration_date', '>=', now()->toDateString());
        if (!empty($filters['school_year'])) {
            $query->where('school_year', (string) $filters['school_year']);
        }
        if (!empty($filters['semester'])) {
            $query->where('semester', (string) $filters['semester']);
        }

        return (int) $query->count();
    }

    private function paginationPayload(LengthAwarePaginator $paginator): array
    {
        return [
            'current_page' => $paginator->currentPage(),
            'per_page' => $paginator->perPage(),
            'total' => $paginator->total(),
            'total_pages' => $paginator->lastPage(),
        ];
    }
}
