<?php

namespace Modules\Scheduling\Controllers;

use App\Controllers\BaseController;
use App\Models\ContractEmployeeModel;

class SchedulingCalendarController extends BaseController
{
    protected ContractEmployeeModel $assignments;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->assignments = new ContractEmployeeModel();
    }

    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));

        $rows = $this->assignments->getInDateRange($startDate, $endDate);

        $eventsByDay = [];
        foreach ($rows as $row) {
            $rangeStart = max(strtotime($row['start_date'] ?? $startDate), strtotime($startDate));
            $rangeEnd   = min(
                strtotime($row['end_date'] ?? $endDate),
                strtotime($endDate)
            );

            if ($rangeStart === false || $rangeEnd === false || $rangeStart > $rangeEnd) {
                continue;
            }

            for ($d = $rangeStart; $d <= $rangeEnd; $d += 86400) {
                $key = date('Y-m-d', $d);
                $eventsByDay[$key][] = [
                    'employee' => $row['full_name'] ?? 'Employee',
                    'label'    => ($row['full_name'] ?? 'Employee') . ' — ' . ($row['contract_number'] ?? 'Contract'),
                    'company'  => $row['company_name'] ?? '',
                    'contract' => $row['contract_title'] ?? ($row['contract_number'] ?? ''),
                ];
            }
        }

        $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\Scheduling\Views\calendar\index', array_merge($this->baseViewData(), [
            'title'       => 'Scheduling Calendar',
            'month'       => $month,
            'year'        => $year,
            'daysInMonth' => $daysInMonth,
            'firstDow'    => $firstDow,
            'eventsByDay' => $eventsByDay,
            'prevUrl'     => base_url("scheduling/calendar?month={$prevMonth}&year={$prevYear}"),
            'nextUrl'     => base_url("scheduling/calendar?month={$nextMonth}&year={$nextYear}"),
        ]));
    }
}
