<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Services;

use App\Core\App;
use App\Core\EventBus;

final class DocumentaryCreditService
{
    private const VALID_TRANSITIONS = [
        'draft' => ['submitted'],
        'submitted' => ['opened', 'cancelled'],
        'opened' => ['partially_utilized', 'fully_utilized', 'expired', 'cancelled'],
        'partially_utilized' => ['fully_utilized', 'expired'],
        'fully_utilized' => ['closed'],
        'expired' => ['closed'],
    ];

    public static function create(array $data): int
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        return $db->insert('documentary_credits', [
            'credit_number' => $data['credit_number'],
            'type' => $data['type'] ?? 'import',
            'beneficiary_name' => $data['beneficiary_name'],
            'issuing_bank' => $data['issuing_bank'],
            'advising_bank' => $data['advising_bank'] ?? null,
            'amount' => $data['amount'],
            'currency_code' => $data['currency_code'] ?? 'EGP',
            'opening_date' => $data['opening_date'] ?? date('Y-m-d'),
            'expiry_date' => $data['expiry_date'],
            'shipment_date' => $data['shipment_date'] ?? null,
            'purchase_order_id' => $data['purchase_order_id'] ?? null,
            'bank_account_id' => $data['bank_account_id'] ?? null,
            'margin_amount' => $data['margin_amount'] ?? '0.00',
            'commission_rate' => $data['commission_rate'] ?? '0.00',
            'status' => 'draft',
            'notes' => $data['notes'] ?? null,
            'created_by' => $employee ? (int) $employee->id : null,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public static function transition(int $creditId, string $newStatus): array
    {
        $db = App::getInstance()->db();

        $credit = $db->selectOne("SELECT * FROM documentary_credits WHERE id = ?", [$creditId]);
        if (!$credit) {
            return ['success' => false, 'error' => 'الاعتماد المستندي غير موجود'];
        }

        $current = $credit['status'];
        $allowed = self::VALID_TRANSITIONS[$current] ?? [];

        if (!in_array($newStatus, $allowed, true)) {
            return ['success' => false, 'error' => "لا يمكن الانتقال من {$current} إلى {$newStatus}"];
        }

        $db->update('documentary_credits', [
            'status' => $newStatus,
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$creditId]);

        EventBus::dispatch('accounting.lc.status_changed', [
            'credit_id' => $creditId,
            'from_status' => $current,
            'to_status' => $newStatus,
            'amount' => (string) $credit['amount'],
        ]);

        return ['success' => true];
    }

    public static function addDocument(int $creditId, array $data): int
    {
        $db = App::getInstance()->db();

        return $db->insert('lc_documents', [
            'credit_id' => $creditId,
            'document_type' => $data['document_type'],
            'document_number' => $data['document_number'] ?? null,
            'description' => $data['description'] ?? null,
            'received_date' => $data['received_date'] ?? date('Y-m-d'),
            'status' => $data['status'] ?? 'received',
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }
}
