<?php
declare(strict_types=1);

namespace App\Modules\HR\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\HR\Models\HrEmployeeLoan;
use App\Modules\HR\Models\HrLoanInstallment;
use App\Modules\HR\Models\HrEmployeeProfile;
use App\Modules\HR\Services\LoanService;

class LoanController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'q'      => trim((string) $request->get('q', '')),
            'status' => trim((string) $request->get('status', '')),
            'type'   => trim((string) $request->get('type', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = HrEmployeeLoan::search($filters, 25, $page);

        return $this->view('HR.Views.loans.index', [
            'loans'      => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
        ]);
    }

    public function create(Request $request): Response
    {
        $employees = HrEmployeeProfile::getActiveIds();

        return $this->view('HR.Views.loans.form', [
            'loan'      => null,
            'employees' => $employees,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = [
            'employee_profile_id'    => (int) $request->post('employee_profile_id', 0),
            'loan_type'              => trim((string) $request->post('loan_type', 'salary_advance')),
            'loan_amount'            => trim((string) $request->post('loan_amount', '0.00')),
            'number_of_installments' => (int) $request->post('number_of_installments', 1),
            'request_date'           => trim((string) $request->post('request_date', date('Y-m-d'))),
            'start_deduction_date'   => trim((string) $request->post('start_deduction_date', '')),
            'reason'                 => trim((string) $request->post('reason', '')) ?: null,
            'notes'                  => trim((string) $request->post('notes', '')) ?: null,
            'external_entity_name'   => trim((string) $request->post('external_entity_name', '')) ?: null,
            'external_reference'     => trim((string) $request->post('external_reference', '')) ?: null,
            'monthly_salary_impact'  => trim((string) $request->post('monthly_salary_impact', '')) ?: null,
        ];

        $result = LoanService::create($data);

        if (!$result['success']) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => $result['error']]]);
            $session->flash('_old_input', $request->all());
            return $this->redirect('/hr/loans/create');
        }

        return $this->redirect('/hr/loans/' . $result['loan_id'])->withSuccess('تم إنشاء طلب السلفة بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $loan = $db->selectOne(
            "SELECT l.*, hp.first_name_ar, hp.last_name_ar, hp.employee_number
             FROM hr_employee_loans l
             JOIN hr_employee_profiles hp ON hp.id = l.employee_profile_id
             WHERE l.id = ? AND l.is_archived = 0",
            [(int) $id]
        );

        if (!$loan) {
            return $this->redirect('/hr/loans')->withError('السلفة غير موجودة');
        }

        $installments = HrLoanInstallment::getForLoan((int) $id);

        $approver = $loan['approved_by']
            ? $db->selectOne("SELECT name FROM employees WHERE id = ?", [(int) $loan['approved_by']])
            : null;

        return $this->view('HR.Views.loans.show', [
            'loan'         => $loan,
            'installments' => $installments,
            'approver'     => $approver,
        ]);
    }

    public function approve(Request $request, string $id): Response
    {
        $result = LoanService::approve((int) $id);

        if (!$result['success']) {
            return $this->redirect('/hr/loans/' . $id)->withError($result['error']);
        }

        return $this->redirect('/hr/loans/' . $id)->withSuccess('تم اعتماد السلفة بنجاح');
    }

    public function reject(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $employee = $this->currentEmployee();

        $loan = $db->selectOne("SELECT * FROM hr_employee_loans WHERE id = ? AND is_archived = 0", [(int) $id]);
        if (!$loan || $loan['status'] !== 'pending') {
            return $this->redirect('/hr/loans/' . $id)->withError('السلفة غير قابلة للرفض');
        }

        $rejectionReason = trim((string) $request->post('rejection_reason', ''));

        $db->update('hr_employee_loans', [
            'status'     => 'rejected',
            'notes'      => $rejectionReason ? ('رفض: ' . $rejectionReason) : $loan['notes'],
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => $employee ? (int) $employee->id : null,
        ], '`id` = ?', [(int) $id]);

        return $this->redirect('/hr/loans/' . $id)->withSuccess('تم رفض السلفة');
    }

    public function disburse(Request $request, string $id): Response
    {
        $result = LoanService::disburse((int) $id);

        if (!$result['success']) {
            return $this->redirect('/hr/loans/' . $id)->withError($result['error']);
        }

        return $this->redirect('/hr/loans/' . $id)->withSuccess('تم صرف السلفة بنجاح');
    }
}
