<?php

namespace App\Services\Attendance;

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

class LateSlipLogQueryService
{
    public function paginate(array $filters, int $page = 1, int $perPage = 50): LengthAwarePaginator
    {
        $query = LateSlipLog::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'])) {
            $query->where('student_name', 'like', '%' . $filters['q'] . '%');
        }

        $dateFrom = $this->toDbDate($filters['date_from'] ?? null);
        if ($dateFrom) {
            $query->where('slip_date', '>=', $dateFrom);
        }

        $dateTo = $this->toDbDate($filters['date_to'] ?? null);
        if ($dateTo) {
            $query->where('slip_date', '<=', $dateTo);
        }

        $sortBy = (string) ($filters['sort_by'] ?? 'id');
        $sortDir = strtolower((string) ($filters['sort_dir'] ?? 'desc')) === 'asc' ? 'asc' : 'desc';
        $allowedSorts = ['id', 'slip_date', 'student_name', 'printed_at', 'updated_at'];

        if (in_array($sortBy, $allowedSorts, true)) {
            $query->orderBy($sortBy, $sortDir);
        } else {
            $query->orderBy('id', 'desc');
        }

        return $query->paginate($perPage, ['*'], 'page', $page);
    }

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

    private function toDbDate(?string $value): ?string
    {
        $value = trim((string) $value);
        if ($value === '') {
            return null;
        }
        $ts = strtotime($value);
        return $ts ? date('Y-m-d', $ts) : null;
    }
}
