<?php

namespace Modules\Payroll\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\EmployeeSalaryStructureModel;
use Modules\Payroll\Services\SalaryStructureService;

class SalaryStructureController extends BaseController
{
    protected EmployeeSalaryStructureModel $structures;
    protected EmployeeModel $employees;
    protected SalaryStructureService $service;

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

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

        return view('Modules\Payroll\Views\salary_structures\index', array_merge($this->baseViewData(), [
            'title'      => 'Salary Structures',
            'structures' => $this->structures->getWithEmployees($search ?: null),
            'filters'    => compact('search'),
        ]));
    }

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

    public function store()
    {
        if (! $this->validate([
            'employee_id'   => 'required|integer',
            'effective_from'=> 'required|valid_date[Y-m-d]',
            'basic_salary'  => 'required|decimal',
        ])) {
            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/salary')->with('success', 'Salary structure assigned.');
    }

    public function editForm(int $id)
    {
        $structure = $this->structures->find($id);
        if (! $structure) {
            return redirect()->to('/payroll/salary')->with('error', 'Salary structure not found.');
        }

        $employee = $this->employees->find((int) $structure['employee_id']);

        return view('Modules\Payroll\Views\salary_structures\edit', array_merge($this->baseViewData(), [
            'title'     => 'Edit Salary Structure',
            'structure' => $structure,
            'employee'  => $employee,
        ]));
    }

    public function update(int $id)
    {
        if (! $this->validate([
            'effective_from'=> 'required|valid_date[Y-m-d]',
            'basic_salary'  => 'required|decimal',
        ])) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

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

        return redirect()->to('/payroll/salary')->with('success', 'Salary structure updated.');
    }
}
