<?php

namespace Modules\Leave\Controllers;

use App\Controllers\BaseController;
use App\Models\EmployeeModel;
use App\Models\LeaveRequestModel;
use App\Models\LeaveTypeModel;
use Modules\Auth\Models\UserModel;
use Modules\Leave\Services\LeaveRequestService;

class LeaveRequestController extends BaseController
{
    protected LeaveRequestModel $requests;
    protected LeaveTypeModel $types;
    protected EmployeeModel $employees;
    protected UserModel $users;
    protected LeaveRequestService $service;

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

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

        $requests = $this->requests
            ->scopeForList(
                $search ?: null,
                $status,
                $employeeId ? (int) $employeeId : null,
                $leaveTypeId ? (int) $leaveTypeId : null
            )
            ->orderBy('created_at', 'DESC')
            ->paginate(15);

        $employeeMap = [];
        $typeMap     = [];
        foreach ($this->employees->findAll() as $e) {
            $employeeMap[$e['id']] = $e['full_name'];
        }
        foreach ($this->types->findAll() as $t) {
            $typeMap[$t['id']] = $t['name'];
        }

        return view('Modules\Leave\Views\requests\index', array_merge($this->baseViewData(), [
            'title'       => 'Leave Requests',
            'requests'    => $requests,
            'pager'       => $this->requests->pager,
            'employees'   => $this->employees->where('status !=', 'terminated')->orderBy('full_name', 'ASC')->findAll(),
            'types'       => $this->types->getActive(),
            'employeeMap' => $employeeMap,
            'typeMap'     => $typeMap,
            'filters'     => compact('search', 'status', 'employeeId', 'leaveTypeId'),
        ]));
    }

    public function createForm()
    {
        return view('Modules\Leave\Views\requests\create', array_merge($this->baseViewData(), [
            'title'     => 'New Leave Request',
            'employees' => $this->employees->where('status !=', 'terminated')->orderBy('full_name', 'ASC')->findAll(),
            'types'     => $this->types->getActive(),
        ]));
    }

    public function store()
    {
        if (! $this->validate([
            'employee_id'   => 'required|integer',
            'leave_type_id' => 'required|integer',
            'start_date'    => 'required|valid_date[Y-m-d]',
            'end_date'      => '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('/leave/requests/' . $result['id'])->with('success', 'Leave request submitted.');
    }

    public function show(int $id)
    {
        $request = $this->requests->find($id);
        if (! $request) {
            return redirect()->to('/leave/requests')->with('error', 'Leave request not found.');
        }

        $employee = $this->employees->find($request['employee_id']);
        $type     = $this->types->find($request['leave_type_id']);
        $approver = $request['approved_by'] ? $this->users->find($request['approved_by']) : null;

        return view('Modules\Leave\Views\requests\show', array_merge($this->baseViewData(), [
            'title'    => 'Leave Request #' . $id,
            'request'  => $request,
            'employee' => $employee,
            'type'     => $type,
            'approver' => $approver,
        ]));
    }

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

        return redirect()->back()->with('success', 'Leave request approved.');
    }

    public function reject(int $id)
    {
        $result = $this->service->reject($id, trim((string) $this->request->getPost('rejection_reason')), (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Leave request rejected.');
    }

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

        return redirect()->back()->with('success', 'Leave request cancelled.');
    }

    public function destroy(int $id)
    {
        $result = $this->service->delete($id, (int) $this->session->get('user_id'));
        if (! $result['success']) {
            return redirect()->to('/leave/requests')->with('error', $result['error']);
        }

        return redirect()->to('/leave/requests')->with('success', 'Leave request deleted.');
    }
}
