<?php

namespace Modules\Leave\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\LeaveBalanceModel;
use App\Models\LeaveTypeModel;
use Modules\Leave\Services\LeaveBalanceService;

class LeaveBalanceController extends BaseController
{
    protected LeaveBalanceModel $balances;
    protected LeaveTypeModel $types;
    protected EmployeeModel $employees;
    protected LeaveBalanceService $service;

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

    public function index()
    {
        $year       = (int) ($this->request->getGet('year') ?: date('Y'));
        $employeeId = $this->request->getGet('employee_id') ?: null;
        $search     = trim((string) $this->request->getGet('q'));

        $employees = $this->employees->scopeForList($search ?: null, 'active')->orderBy('full_name', 'ASC')->findAll();
        $types     = $this->types->getActive();

        $balances = [];
        if ($employeeId) {
            $this->service->ensureBalancesForEmployee((int) $employeeId, $year);
            $rows = $this->balances->scopeForList($year, (int) $employeeId)->findAll();
            foreach ($rows as $row) {
                $balances[$row['leave_type_id']] = $row;
            }
        }

        return view('Modules\Leave\Views\balances\index', array_merge($this->baseViewData(), [
            'title'      => 'Leave Balances',
            'employees'  => $employees,
            'types'      => $types,
            'balances'   => $balances,
            'filters'    => compact('year', 'employeeId', 'search'),
        ]));
    }

    public function initialize()
    {
        $year  = (int) ($this->request->getPost('year') ?: date('Y'));
        $count = $this->service->ensureAllEmployeeBalances($year);

        return redirect()->to('/leave/balances?year=' . $year)->with('success', "Leave balances initialized for {$count} employee(s).");
    }

    public function update(int $id)
    {
        $entitled = (float) $this->request->getPost('entitled');
        $result   = $this->service->updateEntitlement($id, $entitled, (int) $this->session->get('user_id'));

        if (! $result['success']) {
            return redirect()->back()->with('errors', $result['errors']);
        }

        return redirect()->back()->with('success', 'Leave balance updated.');
    }
}
