<?php
declare(strict_types=1);

use App\Core\Registries\MenuRegistry;
use App\Core\Registries\PermissionRegistry;
use App\Core\EventBus;

MenuRegistry::register('treasury', [
    'label_ar'   => 'الخزنة الفرعية',
    'label_en'   => 'Sub-Treasury',
    'icon'       => 'safe',
    'route'      => '/treasury',
    'permission' => 'treasury.view_dashboard',
    'parent'     => null,
    'order'      => 255,
    'children'   => [
        ['label_ar' => 'لوحة التحكم',   'label_en' => 'Dashboard',    'route' => '/treasury',              'permission' => 'treasury.view_dashboard',      'order' => 1],
        ['label_ar' => 'طابور التحصيل',  'label_en' => 'Queue',        'route' => '/treasury/queue',        'permission' => 'treasury.collect_payment',     'order' => 2],
        ['label_ar' => 'الورديات',      'label_en' => 'Sessions',     'route' => '/treasury/sessions',     'permission' => 'treasury.view_sessions',       'order' => 3],
        ['label_ar' => 'التسويات',      'label_en' => 'Settlements',  'route' => '/treasury/settlements',  'permission' => 'treasury.view_settlements',    'order' => 4],
        ['label_ar' => 'سجل العهدة',    'label_en' => 'Custody Log',  'route' => '/treasury/custody',      'permission' => 'treasury.view_custody',        'order' => 5],
    ],
]);

PermissionRegistry::register('treasury', [
    'treasury.view_dashboard'      => ['ar' => 'لوحة تحكم الخزنة الفرعية',           'en' => 'Sub-Treasury Dashboard'],
    'treasury.collect_payment'     => ['ar' => 'تحصيل مدفوعات',                      'en' => 'Collect Payments'],
    'treasury.open_session'        => ['ar' => 'فتح وردية',                          'en' => 'Open Session'],
    'treasury.close_session'       => ['ar' => 'إغلاق وردية',                        'en' => 'Close Session'],
    'treasury.initiate_settlement' => ['ar' => 'إجراء تسوية للخزنة الرئيسية',        'en' => 'Initiate Settlement'],
    'treasury.view_custody'        => ['ar' => 'عرض رصيد العهدة',                    'en' => 'View Custody Balance'],
    'treasury.view_sessions'       => ['ar' => 'عرض الورديات',                       'en' => 'View Sessions'],
    'treasury.view_settlements'    => ['ar' => 'عرض التسويات',                       'en' => 'View Settlements'],
]);

// Listen for payment voids on sub-treasury payments to reverse custody
EventBus::listen('payment.voided', function (array $data) {
    try {
        $paymentId = (int) ($data['payment_id'] ?? 0);
        if ($paymentId <= 0) return;

        $db = \App\Core\App::getInstance()->db();
        $payment = $db->selectOne(
            "SELECT treasury_id, session_id, amount, payment_method FROM payments WHERE id = ?",
            [$paymentId]
        );

        if (!$payment || !$payment['treasury_id'] || $payment['payment_method'] !== 'cash') return;

        $session = $db->selectOne("SELECT cashier_id FROM treasury_sessions WHERE id = ?", [(int) $payment['session_id']]);
        if (!$session) return;

        \App\Modules\Treasury\Services\CustodyService::recordVoidReversal(
            (int) $payment['treasury_id'],
            (int) $session['cashier_id'],
            (string) $payment['amount'],
            $paymentId
        );
    } catch (\Throwable $e) {
        \App\Core\Logger::error("Treasury payment.voided listener failed: " . $e->getMessage());
    }
}, 40);
