<?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' => 'Registration',    'route' => '/sa/registration',   'permission' => 'sa.registration.manage','order' => 2],
        ['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' => 'Pool Grid',       'route' => '/sa/pool-grid',      'permission' => 'sa.pool-grid.manage',  'order' => 5],
        ['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' => '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],
    ],
]);

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_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.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'],
]);

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

EventBus::listen('payment_request.completed', function (array $data): void {
    $entityType = $data['related_entity_type'] ?? '';
    try {
        if ($entityType === 'sa_registration_form') {
            $registrationId = (int) ($data['related_entity_id'] ?? 0);
            if ($registrationId > 0) {
                $db = App::getInstance()->db();
                $db->update('sa_registrations', [
                    'form_payment_status' => 'paid',
                    'updated_at'          => date('Y-m-d H:i:s'),
                ], 'id = ?', [$registrationId]);
            }
            return;
        }

        if ($entityType === 'sa_registrations') {
            $registrationId = (int) ($data['related_entity_id'] ?? 0);
            $paymentId = (int) ($data['payment_id'] ?? 0);
            if ($registrationId > 0) {
                \App\Modules\SportsActivity\Services\RegistrationWizardService::completeRegistration($registrationId, $paymentId);
            }
            return;
        }

        $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)]);
        } elseif ($entityType === 'sa_group_players') {
            $enrollmentId = (int) ($data['related_entity_id'] ?? 0);
            $paymentId = (int) ($data['payment_id'] ?? 0);
            if ($enrollmentId < 1 || $paymentId < 1) return;

            \App\Modules\SportsActivity\Services\EnrollmentService::activateEnrollment($enrollmentId, $paymentId);

            $enrollment = $db->selectOne(
                "SELECT gp.player_id, gp.group_id, g.name_ar as group_name
                 FROM sa_group_players gp
                 LEFT JOIN sa_groups g ON g.id = gp.group_id
                 WHERE gp.id = ?",
                [$enrollmentId]
            );
            if ($enrollment) {
                $periodStart = date('Y-m-d');
                $periodEnd = date('Y-m-t');
                $subNumber = 'SUB-' . date('Ymd') . '-' . str_pad((string) random_int(1, 9999), 4, '0', STR_PAD_LEFT);

                $db->insert('sa_subscriptions', [
                    'subscription_number' => $subNumber,
                    'player_id'           => (int) $enrollment['player_id'],
                    'group_id'            => (int) $enrollment['group_id'],
                    'period_start'        => $periodStart,
                    'period_end'          => $periodEnd,
                    'amount'              => $data['amount'] ?? '0.00',
                    'discount_amount'     => '0.00',
                    'final_amount'        => $data['amount'] ?? '0.00',
                    'payment_status'      => 'paid',
                    'paid_at'             => date('Y-m-d H:i:s'),
                    'paid_amount'         => $data['amount'] ?? '0.00',
                    'payment_id'          => $paymentId,
                    'receipt_id'          => $data['receipt_id'] ?? null,
                    'receipt_number'      => $data['receipt_number'] ?? null,
                    'created_at'          => date('Y-m-d H:i:s'),
                    'updated_at'          => date('Y-m-d H:i:s'),
                ]);
            }
        }
    } 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']]);
        }

        $enrollment = $db->selectOne(
            "SELECT id FROM sa_group_players WHERE activated_by_payment_id = ? AND status = 'active'",
            [$paymentId]
        );
        if ($enrollment) {
            \App\Modules\SportsActivity\Services\EnrollmentService::deactivateEnrollment((int) $enrollment['id']);
        }
    } catch (\Throwable $e) {
        Logger::error('SA payment.voided listener failed: ' . $e->getMessage());
    }
}, 60);
