<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Accounting\Services\BankLoanService;

class BankLoanController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('accounting.loans.view');
        $db = App::getInstance()->db();

        $status = $request->get('status', '');
        $where = '1=1';
        $params = [];

        if ($status) {
            $where .= ' AND l.status = ?';
            $params[] = $status;
        }

        $loans = $db->select(
            "SELECT l.*, ba.account_name_ar as bank_name
             FROM bank_loans l
             LEFT JOIN bank_accounts ba ON ba.id = l.bank_account_id
             WHERE {$where}
             ORDER BY l.created_at DESC",
            $params
        );

        return $this->view('Accounting.Views.loans.index', [
            'loans' => $loans,
            'status' => $status,
        ]);
    }

    public function create(Request $request): Response
    {
        $this->authorize('accounting.loans.manage');
        $db = App::getInstance()->db();

        $bankAccounts = $db->select("SELECT id, account_name_ar FROM bank_accounts WHERE is_active = 1 ORDER BY account_name_ar");

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

    public function store(Request $request): Response
    {
        $this->authorize('accounting.loans.manage');

        $data = [
            'bank_account_id' => (int) $request->post('bank_account_id'),
            'loan_type' => $request->post('loan_type', 'term'),
            'principal_amount' => $request->post('principal_amount'),
            'interest_rate' => $request->post('interest_rate'),
            'term_months' => (int) $request->post('term_months'),
            'start_date' => $request->post('start_date'),
            'collateral_description' => $request->post('collateral_description'),
            'notes' => $request->post('notes'),
        ];

        $result = BankLoanService::createLoan($data);

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

        return $this->redirect('/accounting/loans/' . $result['loan_id'])->withSuccess('تم إنشاء القرض بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('accounting.loans.view');
        $db = App::getInstance()->db();

        $loan = $db->selectOne(
            "SELECT l.*, ba.account_name_ar as bank_name
             FROM bank_loans l
             LEFT JOIN bank_accounts ba ON ba.id = l.bank_account_id
             WHERE l.id = ?",
            [(int) $id]
        );

        if (!$loan) {
            return $this->redirect('/accounting/loans')->withError('القرض غير موجود');
        }

        $schedule = BankLoanService::getSchedule((int) $id);

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

    public function recordPayment(Request $request, string $id): Response
    {
        $this->authorize('accounting.loans.manage');

        $installmentNumber = (int) $request->post('installment_number');
        $paidAmount = $request->post('paid_amount');
        $paidDate = $request->post('paid_date');

        $result = BankLoanService::recordPayment((int) $id, $installmentNumber, $paidAmount, $paidDate);

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

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