<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\LateSlipLogModel;
use App\Models\ConfigurationModel;

class LateSlipLogsController extends BaseController
{
    private LateSlipLogModel $logModel;
    private ConfigurationModel $configModel;

    public function __construct()
    {
        $this->logModel = new LateSlipLogModel();
        $this->configModel = new ConfigurationModel();
    }

    public function index()
    {
        $req = $this->request;

        $defaultYear = $this->currentSchoolYearName((string) ($this->schoolYear ?? ''));
        $defaultSem  = (string) ($this->configModel->getConfig('semester')    ?? '');
        $schoolYear  = trim((string) ($req->getGet('school_year') ?? $defaultYear));
        $semester    = trim((string) ($req->getGet('semester')    ?? $defaultSem));
        $q           = trim((string) ($req->getGet('q') ?? ''));
        $dateFrom    = trim((string) ($req->getGet('date_from') ?? ''));
        $dateTo      = trim((string) ($req->getGet('date_to') ?? ''));

        // Normalize dates to Y-m-d for filtering
        $toDbDate = static function (?string $s): ?string {
            $s = trim((string) $s);
            if ($s === '') return null;
            $ts = strtotime($s);
            return $ts ? date('Y-m-d', $ts) : null;
        };
        $df = $toDbDate($dateFrom);
        $dt = $toDbDate($dateTo);

        $model = $this->logModel;
        if ($schoolYear !== '') $model = $model->where('school_year', $schoolYear);
        if ($semester   !== '') $model = $model->where('semester', $semester);
        if ($q !== '')          $model = $model->like('student_name', $q);
        if ($df)                $model = $model->where('slip_date >=', $df);
        if ($dt)                $model = $model->where('slip_date <=', $dt);

        // Limit to most recent 200 entries
        $logs = $model->orderBy('id', 'DESC')->findAll(200);

        return view('administrator/late_slip_logs', [
            'schoolYear' => $schoolYear,
            'semester'   => $semester,
            'filters'    => [
                'q'         => $q,
                'date_from' => $dateFrom,
                'date_to'   => $dateTo,
            ],
            'logs'       => $logs,
        ]);
    }
}
