<?php

namespace Modules\Payroll\Controllers;

use App\Controllers\BaseController;
use App\Models\CompanySettingsModel;
use App\Models\PayrollItemLineModel;
use App\Models\PayrollItemModel;
use App\Models\PayrollRunModel;

class PayslipController extends BaseController
{
    protected PayrollItemModel $items;
    protected PayrollItemLineModel $lines;
    protected PayrollRunModel $runs;
    protected CompanySettingsModel $company;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->items   = new PayrollItemModel();
        $this->lines   = new PayrollItemLineModel();
        $this->runs    = new PayrollRunModel();
        $this->company = new CompanySettingsModel();
    }

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

        $run = $this->runs->findByPeriod($year, $month);
        $items = $run ? $this->items->getForRun((int) $run['id']) : [];

        return view('Modules\Payroll\Views\payslips\index', array_merge($this->baseViewData(), [
            'title'   => 'Payslips',
            'run'     => $run,
            'items'   => $items,
            'filters' => compact('year', 'month'),
        ]));
    }

    public function show(int $id)
    {
        $item = $this->items->getWithRunAndEmployee($id);
        if (! $item) {
            return redirect()->to('/payroll/payslips')->with('error', 'Payslip not found.');
        }

        $lines = $this->lines->getForItem($id);
        $earnings   = array_filter($lines, static fn ($l) => $l['type'] === 'earning');
        $deductions = array_filter($lines, static fn ($l) => $l['type'] === 'deduction');

        return view('Modules\Payroll\Views\payslips\show', array_merge($this->baseViewData(), [
            'title'      => 'Payslip — ' . $item['full_name'],
            'item'       => $item,
            'earnings'   => $earnings,
            'deductions' => $deductions,
            'company'    => $this->company->getSettings(),
        ]));
    }
}
