<?php
declare(strict_types=1);

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

MenuRegistry::register('sports_activity', [
    'label_ar'   => 'الأنشطة الرياضية',
    'label_en'   => 'Sports & Academy',
    'icon'       => 'activity',
    'route'      => '/sa',
    'permission' => 'sa.dashboard',
    'parent'     => null,
    'order'      => 395,
    'children'   => [
        ['label_ar' => 'لوحة التحكم',       'label_en' => 'Dashboard',       'route' => '/sa',                'permission' => 'sa.dashboard',         'order' => 1],
        ['label_ar' => 'المراية',           'label_en' => 'Mirror',          'route' => '/sa/mirror',         'permission' => 'sa.mirror.view',       'order' => 2],
        ['label_ar' => 'شبكة حمام السباحة', 'label_en' => 'Pool Grid',       'route' => '/sa/pool-grid',      'permission' => 'sa.pool-grid.manage',  'order' => 3],
        ['label_ar' => 'الألعاب',           'label_en' => 'Disciplines',     'route' => '/sa/disciplines',    'permission' => 'sa.discipline.view',   'order' => 3],
        ['label_ar' => 'المرافق',           'label_en' => 'Facilities',      'route' => '/sa/facilities',     'permission' => 'sa.facility.view',     'order' => 4],
        ['label_ar' => 'المدربين',          'label_en' => 'Coaches',         'route' => '/sa/coaches',        'permission' => 'sa.coach.view',        'order' => 5],
        ['label_ar' => 'اللاعبين',          'label_en' => 'Players',         'route' => '/sa/players',        'permission' => 'sa.player.view',       'order' => 6],
        ['label_ar' => 'الأكاديميات',       'label_en' => 'Academies',       'route' => '/sa/academies',      'permission' => 'sa.academy.view',      'order' => 7],
        ['label_ar' => 'البرامج',           'label_en' => 'Programs',        'route' => '/sa/programs',       'permission' => 'sa.program.view',      'order' => 8],
        ['label_ar' => 'المجموعات',         'label_en' => 'Groups',          'route' => '/sa/groups',         'permission' => 'sa.group.view',        'order' => 9],
        ['label_ar' => 'الجدول',            'label_en' => 'Schedule',        'route' => '/sa/schedule',       'permission' => 'sa.schedule.view',     'order' => 10],
        ['label_ar' => 'الحجوزات',          'label_en' => 'Bookings',        'route' => '/sa/bookings',       'permission' => 'sa.booking.view',      'order' => 11],
        ['label_ar' => 'التسعير',           'label_en' => 'Pricing',         'route' => '/sa/pricing',        'permission' => 'sa.pricing.view',      'order' => 12],
        ['label_ar' => 'الاشتراكات',        'label_en' => 'Subscriptions',   'route' => '/sa/subscriptions',  'permission' => 'sa.subscription.view', 'order' => 13],
        ['label_ar' => 'الحضور',            'label_en' => 'Attendance',      'route' => '/sa/attendance',     'permission' => 'sa.attendance.view',   'order' => 14],
        ['label_ar' => 'قائمة الانتظار',    'label_en' => 'Waitlist',        'route' => '/sa/waitlist',       'permission' => 'sa.waitlist.view',     'order' => 15],
        ['label_ar' => 'اللوكرات',          'label_en' => 'Lockers',         'route' => '/sa/lockers',        'permission' => 'sa.locker.view',       'order' => 16],
        ['label_ar' => 'إيجارات اللوكرات',  'label_en' => 'Locker Rentals',  'route' => '/sa/locker-rentals', 'permission' => 'sa.locker_rental.view','order' => 17],
    ],
]);

PermissionRegistry::register('sports_activity', [
    'sa.dashboard'             => ['ar' => 'لوحة تحكم الأنشطة الرياضية', 'en' => 'Sports Activity Dashboard'],
    'sa.discipline.view'       => ['ar' => 'عرض الألعاب الرياضية',       'en' => 'View Disciplines'],
    'sa.discipline.manage'     => ['ar' => 'إدارة الألعاب الرياضية',      'en' => 'Manage Disciplines'],
    'sa.facility.view'         => ['ar' => 'عرض المرافق',                'en' => 'View Facilities'],
    'sa.facility.manage'       => ['ar' => 'إدارة المرافق',               'en' => 'Manage Facilities'],
    'sa.coach.view'            => ['ar' => 'عرض المدربين',               'en' => 'View Coaches'],
    'sa.coach.manage'          => ['ar' => 'إدارة المدربين',              'en' => 'Manage Coaches'],
    'sa.player.view'           => ['ar' => 'عرض اللاعبين',               'en' => 'View Players'],
    'sa.player.manage'         => ['ar' => 'إدارة اللاعبين',              'en' => 'Manage Players'],
    'sa.medical.approve'       => ['ar' => 'اعتماد الشهادات الطبية',     'en' => 'Approve Medical Certificates'],
    'sa.academy.view'          => ['ar' => 'عرض الأكاديميات',            'en' => 'View Academies'],
    'sa.academy.manage'        => ['ar' => 'إدارة الأكاديميات',           'en' => 'Manage Academies'],
    'sa.contract.view'         => ['ar' => 'عرض العقود',                 'en' => 'View Contracts'],
    'sa.contract.manage'       => ['ar' => 'إدارة العقود',                'en' => 'Manage Contracts'],
    'sa.contract.approve'      => ['ar' => 'اعتماد العقود',              'en' => 'Approve Contracts'],
    'sa.program.view'          => ['ar' => 'عرض البرامج',                'en' => 'View Programs'],
    'sa.program.manage'        => ['ar' => 'إدارة البرامج',               'en' => 'Manage Programs'],
    'sa.group.view'            => ['ar' => 'عرض المجموعات',              'en' => 'View Groups'],
    'sa.group.manage'          => ['ar' => 'إدارة المجموعات',             'en' => 'Manage Groups'],
    'sa.group.enroll'          => ['ar' => 'تسجيل لاعب في مجموعة',      'en' => 'Enroll Player in Group'],
    'sa.schedule.view'         => ['ar' => 'عرض الجدول',                 'en' => 'View Schedule'],
    'sa.schedule.manage'       => ['ar' => 'إدارة الجدول',                'en' => 'Manage Schedule'],
    'sa.booking.view'          => ['ar' => 'عرض الحجوزات',               'en' => 'View Bookings'],
    'sa.booking.create'        => ['ar' => 'إنشاء حجز',                  'en' => 'Create Booking'],
    'sa.booking.manage'        => ['ar' => 'إدارة الحجوزات',              'en' => 'Manage Bookings'],
    'sa.pricing.view'          => ['ar' => 'عرض التسعير',                'en' => 'View Pricing'],
    'sa.pricing.manage'        => ['ar' => 'إدارة التسعير',               'en' => 'Manage Pricing'],
    'sa.subscription.view'     => ['ar' => 'عرض الاشتراكات',             'en' => 'View Subscriptions'],
    'sa.subscription.generate' => ['ar' => 'توليد الاشتراكات',           'en' => 'Generate Subscriptions'],
    'sa.subscription.collect'  => ['ar' => 'تحصيل الاشتراكات',           'en' => 'Collect Subscription Payments'],
    'sa.subscription.exempt'   => ['ar' => 'إعفاء من الاشتراك',          'en' => 'Exempt from Subscription'],
    'sa.attendance.view'       => ['ar' => 'عرض الحضور',                 'en' => 'View Attendance'],
    'sa.attendance.manage'     => ['ar' => 'تسجيل الحضور',               'en' => 'Record Attendance'],
    'sa.mirror.view'           => ['ar' => 'عرض المراية',                'en' => 'View Mirror Display'],
    'sa.waitlist.view'         => ['ar' => 'عرض قائمة الانتظار',         'en' => 'View Waitlist'],
    'sa.waitlist.manage'       => ['ar' => 'إدارة قائمة الانتظار',        'en' => 'Manage Waitlist'],
    'sa.pool-grid.manage'      => ['ar' => 'إدارة شبكة حمام السباحة',    'en' => 'Manage Pool Grid'],
    'sa.locker.view'           => ['ar' => 'عرض اللوكرات',               'en' => 'View Lockers'],
    'sa.locker.manage'         => ['ar' => 'إدارة اللوكرات',              'en' => 'Manage Lockers'],
    'sa.locker_rental.view'    => ['ar' => 'عرض إيجارات اللوكرات',       'en' => 'View Locker Rentals'],
    'sa.locker_rental.create'  => ['ar' => 'إنشاء إيجار لوكر',           'en' => 'Create Locker Rental'],
    'sa.locker_rental.manage'  => ['ar' => 'إدارة إيجارات اللوكرات',      'en' => 'Manage Locker Rentals'],
    'sa.locker_rental.evict'   => ['ar' => 'محضر فض لوكر',               'en' => 'Evict Locker Tenant'],
]);

// ─── Event Listeners ────────────────────────────────────────────────────────

EventBus::listen('payment_request.completed', function (array $data): void {
    $entityType = $data['related_entity_type'] ?? '';
    try {
        $db = App::getInstance()->db();
        if ($entityType === 'sa_subscriptions') {
            $db->update('sa_subscriptions', [
                'payment_status' => 'paid',
                'paid_at'        => date('Y-m-d H:i:s'),
                'paid_amount'    => $data['amount'] ?? 0,
                'payment_id'     => $data['payment_id'] ?? null,
                'receipt_id'     => $data['receipt_id'] ?? null,
                'receipt_number' => $data['receipt_number'] ?? null,
                'updated_at'     => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) ($data['related_entity_id'] ?? 0)]);
        } elseif ($entityType === 'sa_bookings') {
            $db->update('sa_bookings', [
                'payment_status' => 'paid',
                'payment_id'     => $data['payment_id'] ?? null,
                'receipt_id'     => $data['receipt_id'] ?? null,
                'receipt_number' => $data['receipt_number'] ?? null,
                'updated_at'     => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) ($data['related_entity_id'] ?? 0)]);
        }
    } catch (\Throwable $e) {
        Logger::error('SA payment_request.completed listener failed: ' . $e->getMessage());
    }
}, 60);

EventBus::listen('payment.voided', function (array $data): void {
    try {
        $db = App::getInstance()->db();
        $paymentId = (int) ($data['payment_id'] ?? 0);
        if ($paymentId < 1) return;

        $sub = $db->selectOne("SELECT id FROM sa_subscriptions WHERE payment_id = ?", [$paymentId]);
        if ($sub) {
            $db->update('sa_subscriptions', [
                'payment_status' => 'unpaid',
                'paid_at'        => null,
                'paid_amount'    => null,
                'payment_id'     => null,
                'receipt_id'     => null,
                'receipt_number' => null,
                'updated_at'     => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $sub['id']]);
        }

        $bk = $db->selectOne("SELECT id FROM sa_bookings WHERE payment_id = ?", [$paymentId]);
        if ($bk) {
            $db->update('sa_bookings', [
                'payment_status' => 'unpaid',
                'payment_id'     => null,
                'receipt_id'     => null,
                'receipt_number' => null,
                'updated_at'     => date('Y-m-d H:i:s'),
            ], 'id = ?', [(int) $bk['id']]);
        }
    } catch (\Throwable $e) {
        Logger::error('SA payment.voided listener failed: ' . $e->getMessage());
    }
}, 60);
