<?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'      => 200,
    'children'   => [
        ['label_ar' => 'لوحة التحكم',       'label_en' => 'Dashboard',       'route' => '/sa',                'permission' => 'sa.dashboard',         'order' => 1],
        ['label_ar' => 'مكتب الخدمة',      'label_en' => 'Service Desk',    'route' => '/sa/service-desk',   'permission' => 'sa.registration.manage','order' => 2],
        ['label_ar' => 'متصفح الأنشطة',    'label_en' => 'Activity Browser','route' => '/sa/activities',     'permission' => 'sa.discipline.view',   'order' => 2.5],
        ['label_ar' => 'البوابة',           'label_en' => 'Gate',            'route' => '/sa/gate',           'permission' => 'sa.gate.view',         'order' => 3],
        ['label_ar' => 'المراية',           'label_en' => 'Mirror',          'route' => '/sa/mirror',         'permission' => 'sa.mirror.view',       'order' => 4],
        ['label_ar' => 'الألعاب',           'label_en' => 'Disciplines',     'route' => '/sa/disciplines',    'permission' => 'sa.discipline.view',   'order' => 6],
        ['label_ar' => 'المرافق',           'label_en' => 'Facilities',      'route' => '/sa/facilities',     'permission' => 'sa.facility.view',     'order' => 7],
        ['label_ar' => 'المدربين',          'label_en' => 'Coaches',         'route' => '/sa/coaches',        'permission' => 'sa.coach.view',        'order' => 8],
        ['label_ar' => 'اللاعبين',          'label_en' => 'Players',         'route' => '/sa/players',        'permission' => 'sa.player.view',       'order' => 9],
        ['label_ar' => 'تعيين اللاعبين',    'label_en' => 'Assignments',     'route' => '/sa/assignments',    'permission' => 'sa.player.assign',     'order' => 9.5],
        ['label_ar' => 'الكروت',            'label_en' => 'Cards',           'route' => '/sa/cards',          'permission' => 'sa.card.view',         'order' => 10],
        ['label_ar' => 'الأكاديميات',       'label_en' => 'Academies',       'route' => '/sa/academies',      'permission' => 'sa.academy.view',      'order' => 11],
        ['label_ar' => 'البرامج',           'label_en' => 'Programs',        'route' => '/sa/programs',       'permission' => 'sa.program.view',      'order' => 12],
        ['label_ar' => 'المجموعات',         'label_en' => 'Groups',          'route' => '/sa/groups',         'permission' => 'sa.group.view',        'order' => 13],
        ['label_ar' => 'الجدول',            'label_en' => 'Schedule',        'route' => '/sa/schedule',       'permission' => 'sa.schedule.view',     'order' => 14],
        ['label_ar' => 'معالج الحجز',       'label_en' => 'Booking Wizard',  'route' => '/sa/booking-wizard', 'permission' => 'sa.booking_wizard.use','order' => 14.5],
        ['label_ar' => 'الحجوزات',          'label_en' => 'Bookings',        'route' => '/sa/bookings',       'permission' => 'sa.booking.view',      'order' => 15],
        ['label_ar' => 'التسعير',           'label_en' => 'Pricing',         'route' => '/sa/pricing',        'permission' => 'sa.pricing.view',      'order' => 16],
        ['label_ar' => 'أسعار الأكاديميات', 'label_en' => 'Academy Pricing', 'route' => '/sa/academy-pricing','permission' => 'sa.pricing.view',      'order' => 16.5],
        ['label_ar' => 'الاشتراكات',        'label_en' => 'Subscriptions',   'route' => '/sa/subscriptions',  'permission' => 'sa.subscription.view', 'order' => 17],
        ['label_ar' => 'الحضور',            'label_en' => 'Attendance',      'route' => '/sa/attendance',     'permission' => 'sa.attendance.view',   'order' => 18],
        ['label_ar' => 'قائمة الانتظار',    'label_en' => 'Waitlist',        'route' => '/sa/waitlist',       'permission' => 'sa.waitlist.view',     'order' => 19],
        ['label_ar' => 'اللوكرات',          'label_en' => 'Lockers',         'route' => '/sa/lockers',        'permission' => 'sa.locker.view',       'order' => 20],
        ['label_ar' => 'إيجارات اللوكرات',  'label_en' => 'Locker Rentals',  'route' => '/sa/locker-rentals', 'permission' => 'sa.locker_rental.view','order' => 21],
        ['label_ar' => 'تذاكر السباحة',    'label_en' => 'Pool Tickets',    'route' => '/sa/pool-tickets',   'permission' => 'sa.pool_ticket.view',  'order' => 22],
        ['label_ar' => 'الألعاب الترفيهية','label_en' => 'Recreational Games','route' => '/sa/games',         'permission' => 'sa.game.view',         'order' => 23],
        ['label_ar' => '── السباحة ──',    'label_en' => '── Swimming ──',  'route' => '#',                  'permission' => 'sa.swimming.dashboard','order' => 30],
        ['label_ar' => 'لوحة تحكم السباحة','label_en' => 'Swimming Dashboard','route' => '/sa/swimming',     'permission' => 'sa.swimming.dashboard','order' => 31],
        ['label_ar' => 'تسجيل لاعب سباحة', 'label_en' => 'Register Swimmer','route' => '/sa/swimming/register','permission' => 'sa.swimming.register','order' => 32],
        ['label_ar' => 'تعيين في مجموعة',  'label_en' => 'Assign to Group', 'route' => '/sa/swimming/assign','permission' => 'sa.swimming.assign',  'order' => 33],
    ],
]);

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.player.assign'         => ['ar' => 'تعيين اللاعبين في المجموعات', 'en' => 'Assign Players to Groups'],
    'sa.medical.approve'       => ['ar' => '(ملغي) اعتماد الشهادات الطبية — استخدم medical.board.approve', 'en' => '(Deprecated) Use medical.board.approve'],
    '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_wizard.use'    => ['ar' => 'استخدام معالج الحجز',          'en' => 'Use Booking Wizard'],
    '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.game.view'             => ['ar' => 'عرض الألعاب الترفيهية',      'en' => 'View Recreational Games'],
    'sa.game.manage'           => ['ar' => 'إدارة الألعاب الترفيهية',     'en' => 'Manage Recreational Games'],
    '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'],
    'sa.registration.view'     => ['ar' => 'عرض التسجيلات',              'en' => 'View Registrations'],
    'sa.registration.manage'   => ['ar' => 'إدارة التسجيل',               'en' => 'Manage Registrations'],
    'sa.card.view'             => ['ar' => 'عرض كروت النشاط',            'en' => 'View SA Cards'],
    'sa.card.manage'           => ['ar' => 'إدارة كروت النشاط',           'en' => 'Manage SA Cards'],
    'sa.card.print'            => ['ar' => 'طباعة كروت النشاط',          'en' => 'Print SA Cards'],
    'sa.gate.view'             => ['ar' => 'عرض البوابة',                'en' => 'View Gate Access'],
    'sa.gate.scan'             => ['ar' => 'مسح البوابة',                'en' => 'Scan Gate Access'],
    'sa.group.force_enroll'    => ['ar' => 'تسجيل تجاوز السعة',         'en' => 'Force Enroll (Override Capacity)'],
    'sa.pool_ticket.view'      => ['ar' => 'عرض تذاكر حمام السباحة',    'en' => 'View Pool Tickets'],
    'sa.pool_ticket.issue'     => ['ar' => 'إصدار تذكرة سباحة',         'en' => 'Issue Pool Ticket'],
    'sa.pool_ticket.manage'    => ['ar' => 'إدارة تذاكر السباحة',        'en' => 'Manage Pool Tickets'],
    'sa.swimming.dashboard'    => ['ar' => 'لوحة تحكم السباحة',          'en' => 'Swimming Dashboard'],
    'sa.swimming.register'     => ['ar' => 'تسجيل لاعب سباحة',          'en' => 'Register Swimming Player'],
    'sa.swimming.assign'       => ['ar' => 'تعيين لاعب في مجموعة سباحة','en' => 'Assign Swimming Player to Group'],
]);

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

EventBus::listen('payment_request.completed', [\App\Modules\SportsActivity\Services\SaEventListenerService::class, 'handlePaymentCompleted'], 60);

EventBus::listen('payment.voided', [\App\Modules\SportsActivity\Services\SaEventListenerService::class, 'handlePaymentVoided'], 60);

// ─── Notification Listeners ─────────────────────────────────────────────────

EventBus::listen('sa.card.expiry_reminder', function (array $data): void {
    $phone = $data['phone'] ?? '';
    if ($phone !== '') {
        \App\Modules\Notifications\Services\SmsNotificationService::send(
            $phone,
            'تنبيه: كارت النشاط الرياضي للاعب ' . ($data['player_name'] ?? '') .
            ' سينتهي بتاريخ ' . ($data['expiry_date'] ?? '') . '. يرجى التجديد.'
        );
    }
}, 80);

EventBus::listen('sa.subscription.overdue', function (array $data): void {
    $phone = $data['phone'] ?? '';
    if ($phone !== '') {
        \App\Modules\Notifications\Services\SmsNotificationService::send(
            $phone,
            'تنبيه: اشتراك النشاط الرياضي للاعب ' . ($data['player_name'] ?? '') .
            ' متأخر السداد. المبلغ المطلوب: ' . ($data['amount'] ?? '0') . ' جنيه.'
        );
    }
}, 80);

EventBus::listen('sa.player.transferred', function (array $data): void {
    $db = App::getInstance()->db();
    $player = $db->selectOne(
        "SELECT full_name_ar, phone, guardian_phone FROM sa_players WHERE id = ?",
        [(int) ($data['player_id'] ?? 0)]
    );
    if (!$player) return;
    $phone = $player['guardian_phone'] ?: $player['phone'] ?? '';
    if ($phone !== '') {
        $toGroup = $db->selectOne("SELECT name_ar FROM sa_groups WHERE id = ?", [(int) ($data['to_group_id'] ?? 0)]);
        \App\Modules\Notifications\Services\SmsNotificationService::send(
            $phone,
            'تم نقل اللاعب ' . $player['full_name_ar'] . ' إلى مجموعة ' . ($toGroup['name_ar'] ?? '') . ' بنجاح.'
        );
    }
}, 80);

EventBus::listen('sa.player.absence_threshold', function (array $data): void {
    $phone = $data['phone'] ?? '';
    if ($phone !== '') {
        \App\Modules\Notifications\Services\SmsNotificationService::send(
            $phone,
            'تنبيه: اللاعب ' . ($data['player_name'] ?? '') .
            ' تجاوز حد الغياب (' . ($data['absence_count'] ?? 0) . ' مرات) في مجموعة ' .
            ($data['group_name'] ?? '') . '. يرجى المتابعة.'
        );
    }
}, 80);

EventBus::listen('sa.gate.access_denied', function (array $data): void {
    Logger::warning('SA Gate denial: ' . ($data['player_name'] ?? 'unknown') . ' - ' . ($data['reason'] ?? ''), $data);
}, 50);

EventBus::listen('sa.waitlist.offer', function (array $data): void {
    $phone = $data['phone'] ?? '';
    if ($phone !== '') {
        \App\Modules\Notifications\Services\SmsNotificationService::send(
            $phone,
            'توجد مقعد شاغر في مجموعة ' . ($data['group_name'] ?? '') .
            ' للاعب ' . ($data['player_name'] ?? '') .
            '. الرجاء التأكيد خلال 48 ساعة عبر مكتب التسجيل.'
        );
    }
}, 80);
