<?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 DocumentaryCreditController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('accounting.lc.view');
        $db = App::getInstance()->db();

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

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

        $credits = $db->select(
            "SELECT lc.*, ba.account_name_ar as bank_name, s.name_ar as supplier_name
             FROM documentary_credits lc
             LEFT JOIN bank_accounts ba ON ba.id = lc.issuing_bank_id
             LEFT JOIN suppliers s ON s.id = lc.beneficiary_supplier_id
             WHERE {$where}
             ORDER BY lc.created_at DESC",
            $params
        );

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

    public function create(Request $request): Response
    {
        $this->authorize('accounting.lc.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");
        $suppliers = $db->select("SELECT id, name_ar FROM suppliers WHERE is_archived = 0 ORDER BY name_ar");

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

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

        $lcNumber = 'LC-' . 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);

        $lcId = $db->insert('documentary_credits', [
            'lc_number' => $lcNumber,
            'issuing_bank_id' => (int) $request->post('issuing_bank_id'),
            'beneficiary_supplier_id' => $request->post('beneficiary_supplier_id') ?: null,
            'beneficiary_name' => $request->post('beneficiary_name'),
            'amount' => $amount,
            'currency_code' => $request->post('currency_code', 'EGP'),
            'margin_percentage' => $marginPct,
            'margin_amount' => $marginAmount,
            'opening_date' => $request->post('opening_date'),
            'expiry_date' => $request->post('expiry_date'),
            'shipment_date' => $request->post('shipment_date') ?: null,
            'status' => 'opened',
            'terms' => $request->post('terms'),
            'purchase_order_id' => $request->post('purchase_order_id') ?: null,
            'notes' => $request->post('notes'),
            'created_by' => $employee ? (int) $employee->id : null,
        ]);

        return $this->redirect('/accounting/documentary-credits/' . $lcId)->withSuccess('تم فتح الاعتماد المستندي بنجاح — رقم: ' . $lcNumber);
    }

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

        $credit = $db->selectOne(
            "SELECT lc.*, ba.account_name_ar as bank_name, s.name_ar as supplier_name
             FROM documentary_credits lc
             LEFT JOIN bank_accounts ba ON ba.id = lc.issuing_bank_id
             LEFT JOIN suppliers s ON s.id = lc.beneficiary_supplier_id
             WHERE lc.id = ?",
            [(int) $id]
        );

        if (!$credit) {
            return $this->redirect('/accounting/documentary-credits')->withError('الاعتماد غير موجود');
        }

        $documents = $db->select("SELECT * FROM lc_documents WHERE lc_id = ? ORDER BY created_at DESC", [(int) $id]);

        return $this->view('Accounting.Views.documentary_credits.show', [
            'credit' => $credit,
            'documents' => $documents,
        ]);
    }

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

        $newStatus = $request->post('status');
        $db->update('documentary_credits', ['status' => $newStatus], 'id = ?', [(int) $id]);

        return $this->redirect('/accounting/documentary-credits/' . $id)->withSuccess('تم تحديث حالة الاعتماد');
    }
}
