<?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;

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

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

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

        $guarantees = $db->select(
            "SELECT lg.*, ba.account_name_ar as bank_name
             FROM letters_of_guarantee lg
             LEFT JOIN bank_accounts ba ON ba.id = lg.bank_account_id
             WHERE {$where}
             ORDER BY lg.expiry_date ASC",
            $params
        );

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

    public function create(Request $request): Response
    {
        $this->authorize('accounting.guarantee.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.guarantees.form', [
            'guarantee' => null,
            'bankAccounts' => $bankAccounts,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('accounting.guarantee.manage');
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $guaranteeNumber = 'LG-' . date('Ymd') . '-' . str_pad((string) random_int(1, 9999), 4, '0', STR_PAD_LEFT);

        $amount = (string) $request->post('amount');
        $marginPct = (string) $request->post('margin_percentage', '0');
        $marginAmount = bcmul($amount, bcdiv($marginPct, '100', 4), 2);
        $commissionRate = (string) $request->post('commission_rate', '0');
        $commissionAmount = bcmul($amount, bcdiv($commissionRate, '100', 6), 2);

        $lgId = $db->insert('letters_of_guarantee', [
            'guarantee_number' => $guaranteeNumber,
            'bank_account_id' => (int) $request->post('bank_account_id'),
            'beneficiary_name' => $request->post('beneficiary_name'),
            'guarantee_type' => $request->post('guarantee_type'),
            'amount' => $amount,
            'currency_code' => $request->post('currency_code', 'EGP'),
            'margin_percentage' => $marginPct,
            'margin_amount' => $marginAmount,
            'commission_rate' => $commissionRate,
            'commission_amount' => $commissionAmount,
            'issue_date' => $request->post('issue_date'),
            'expiry_date' => $request->post('expiry_date'),
            'status' => 'issued',
            'related_contract' => $request->post('related_contract'),
            'notes' => $request->post('notes'),
            'created_by' => $employee ? (int) $employee->id : null,
        ]);

        return $this->redirect('/accounting/guarantees/' . $lgId)->withSuccess('تم إصدار خطاب الضمان بنجاح — رقم: ' . $guaranteeNumber);
    }

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

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

        if (!$guarantee) {
            return $this->redirect('/accounting/guarantees')->withError('خطاب الضمان غير موجود');
        }

        return $this->view('Accounting.Views.guarantees.show', ['guarantee' => $guarantee]);
    }

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

        $newStatus = $request->post('status');
        $updateData = ['status' => $newStatus];

        if ($newStatus === 'renewed') {
            $updateData['renewal_date'] = date('Y-m-d');
            $updateData['expiry_date'] = $request->post('new_expiry_date');
        }

        $db->update('letters_of_guarantee', $updateData, 'id = ?', [(int) $id]);

        return $this->redirect('/accounting/guarantees/' . $id)->withSuccess('تم تحديث حالة خطاب الضمان');
    }
}
