<?php

namespace Modules\Payroll\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\PayrollSettlementModel;
use Modules\Payroll\Services\PayrollSettlementService;

class PayrollSettlementController extends BaseController
{
    protected PayrollSettlementModel $settlements;
    protected EmployeeModel $employees;
    protected PayrollSettlementService $service;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->settlements = new PayrollSettlementModel();
        $this->employees   = new EmployeeModel();
        $this->service     = new PayrollSettlementService();
    }

    public function index()
    {
        $search = trim((string) $this->request->getGet('q'));
        $status = $this->request->getGet('status') ?: null;

        return view('Modules\Payroll\Views\settlements\index', array_merge($this->baseViewData(), [
            'title'       => 'Final Settlements',
            'settlements' => $this->settlements->getWithEmployees($search ?: null, $status),
            'filters'     => compact('search', 'status'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Payroll\Views\settlements\create', array_merge($this->baseViewData(), [
            'title'     => 'New Final Settlement',
            'employees' => $this->employees->scopeForList(null, 'active')->orderBy('full_name', 'ASC')->findAll(),
        ]));
    }

    public function preview()
    {
        $employeeId      = (int) $this->request->getPost('employee_id');
        $terminationDate = $this->request->getPost('termination_date') ?? date('Y-m-d');
        $lastWorkingDay  = $this->request->getPost('last_working_day') ?? $terminationDate;

        $result = $this->service->calculate($employeeId, $terminationDate, $lastWorkingDay);
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return view('Modules\Payroll\Views\settlements\create', array_merge($this->baseViewData(), [
            'title'     => 'New Final Settlement',
            'employees' => $this->employees->scopeForList(null, 'active')->orderBy('full_name', 'ASC')->findAll(),
            'preview'   => $result['data'],
            'input'     => compact('employeeId', 'terminationDate', 'lastWorkingDay'),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'employee_id'      => 'required|integer',
            'termination_date'=> 'required|valid_date[Y-m-d]',
            'last_working_day' => 'required|valid_date[Y-m-d]',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/payroll/settlements/' . $result['id'])->with('success', 'Final settlement created.');
    }

    public function show(int $id)
    {
        $settlement = $this->settlements->getWithEmployee($id);
        if (! $settlement) {
            return redirect()->to('/payroll/settlements')->with('error', 'Settlement not found.');
        }

        return view('Modules\Payroll\Views\settlements\show', array_merge($this->baseViewData(), [
            'title'      => 'Settlement #' . $id,
            'settlement' => $settlement,
        ]));
    }

    public function approve(int $id)
    {
        $result = $this->service->approve($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', implode(' ', $result['errors'] ?? []));
        }

        return redirect()->to('/payroll/settlements/' . $id)->with('success', 'Settlement approved.');
    }

    public function markPaid(int $id)
    {
        $result = $this->service->markPaid($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', implode(' ', $result['errors'] ?? []));
        }

        return redirect()->to('/payroll/settlements/' . $id)->with('success', 'Settlement marked as paid.');
    }
}
