<?php

namespace Modules\Leave\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\HolidayModel;
use App\Models\LeaveRequestModel;
use App\Models\LeaveTypeModel;

class LeaveCalendarController extends BaseController
{
    protected LeaveRequestModel $requests;
    protected HolidayModel $holidays;
    protected EmployeeModel $employees;
    protected LeaveTypeModel $types;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->requests  = new LeaveRequestModel();
        $this->holidays  = new HolidayModel();
        $this->employees = new EmployeeModel();
        $this->types     = new LeaveTypeModel();
    }

    public function index()
    {
        $month = (int) ($this->request->getGet('month') ?: date('n'));
        $year  = (int) ($this->request->getGet('year') ?: date('Y'));

        if ($month < 1) {
            $month = 12;
            $year--;
        } elseif ($month > 12) {
            $month = 1;
            $year++;
        }

        $startDate = sprintf('%04d-%02d-01', $year, $month);
        $endDate   = date('Y-m-t', strtotime($startDate));

        $leaves = $this->requests->getApprovedInRange($startDate, $endDate);
        $holidayList = $this->holidays->getInRange($startDate, $endDate);

        $employeeMap = [];
        foreach ($this->employees->findAll() as $e) {
            $employeeMap[$e['id']] = $e['full_name'];
        }

        $typeMap = [];
        foreach ($this->types->findAll() as $t) {
            $typeMap[$t['id']] = $t;
        }

        $eventsByDay = [];
        foreach ($leaves as $leave) {
            $dayStart = max(strtotime($leave['start_date']), strtotime($startDate));
            $dayEnd   = min(strtotime($leave['end_date']), strtotime($endDate));
            for ($d = $dayStart; $d <= $dayEnd; $d += 86400) {
                $key = date('Y-m-d', $d);
                $eventsByDay[$key][] = [
                    'type'     => 'leave',
                    'label'    => ($employeeMap[$leave['employee_id']] ?? 'Employee') . ' — ' . ($typeMap[$leave['leave_type_id']]['code'] ?? 'Leave'),
                    'employee' => $employeeMap[$leave['employee_id']] ?? '—',
                ];
            }
        }

        foreach ($holidayList as $h) {
            $eventsByDay[$h['date']][] = [
                'type'  => 'holiday',
                'label' => $h['name'],
            ];
        }

        $daysInMonth = (int) date('t', strtotime($startDate));
        $firstDow    = (int) date('N', strtotime($startDate));

        $prevMonth = $month === 1 ? 12 : $month - 1;
        $prevYear  = $month === 1 ? $year - 1 : $year;
        $nextMonth = $month === 12 ? 1 : $month + 1;
        $nextYear  = $month === 12 ? $year + 1 : $year;

        return view('Modules\Leave\Views\calendar\index', array_merge($this->baseViewData(), [
            'title'       => 'Leave Calendar',
            'month'       => $month,
            'year'        => $year,
            'daysInMonth' => $daysInMonth,
            'firstDow'    => $firstDow,
            'eventsByDay' => $eventsByDay,
            'prevUrl'     => base_url("leave/calendar?month={$prevMonth}&year={$prevYear}"),
            'nextUrl'     => base_url("leave/calendar?month={$nextMonth}&year={$nextYear}"),
        ]));
    }
}
