<?php
declare(strict_types=1);

use App\Core\Registries\MenuRegistry;
use App\Core\Registries\PermissionRegistry;
use App\Core\EventBus;
use App\Core\Logger;
use App\Modules\Notifications\Services\NotificationTriggerService;

MenuRegistry::register('notifications', [
    'label_ar'   => 'الإخطارات',
    'label_en'   => 'Notifications',
    'icon'       => 'bell',
    'route'      => '/notifications/log',
    'permission' => 'sms.view_log',
    'parent'     => null,
    'order'      => 900,
    'children'   => [
        ['label_ar' => 'سجل الرسائل',  'label_en' => 'SMS Log',       'route' => '/notifications/log',       'permission' => 'sms.view_log',       'order' => 1],
        ['label_ar' => 'إرسال رسالة',  'label_en' => 'Send SMS',      'route' => '/notifications/send',      'permission' => 'sms.send_single',    'order' => 2],
        ['label_ar' => 'القوالب',       'label_en' => 'Templates',     'route' => '/notifications/templates', 'permission' => 'sms.edit_templates', 'order' => 3],
        ['label_ar' => 'المشغّلات التلقائية', 'label_en' => 'Auto Triggers', 'route' => '/notifications/triggers', 'permission' => 'notification.triggers.view', 'order' => 4],
    ],
]);

PermissionRegistry::register('notifications', [
    'sms.send_single'              => ['ar' => 'إرسال رسالة فردية',          'en' => 'Send Single SMS'],
    'sms.send_bulk'                => ['ar' => 'إرسال رسائل جماعية',         'en' => 'Send Bulk SMS'],
    'sms.view_log'                 => ['ar' => 'عرض سجل الرسائل',            'en' => 'View SMS Log'],
    'sms.edit_templates'           => ['ar' => 'تعديل القوالب',              'en' => 'Edit Templates'],
    'notification.triggers.view'   => ['ar' => 'عرض مشغّلات الإخطارات',      'en' => 'View Notification Triggers'],
    'notification.triggers.manage' => ['ar' => 'إدارة مشغّلات الإخطارات',    'en' => 'Manage Notification Triggers'],
]);

// ─── Automated Notification Trigger Listeners ─────────────────────────────────
// Each listener delegates to NotificationTriggerService::processEvent which looks
// up active triggers in the database and dispatches notifications accordingly.

/**
 * Session cancelled — notify enrolled players.
 */
EventBus::listen('session.cancelled', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('session.cancelled', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [session.cancelled]: {$e->getMessage()}");
    }
}, -10);

/**
 * Session rescheduled — notify enrolled players of new date/time.
 */
EventBus::listen('session.rescheduled', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('session.rescheduled', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [session.rescheduled]: {$e->getMessage()}");
    }
}, -10);

/**
 * Player transferred to a new group — notify the player.
 */
EventBus::listen('group.player_transferred', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('group.player_transferred', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [group.player_transferred]: {$e->getMessage()}");
    }
}, -10);

/**
 * Reservation confirmed — send confirmation to the booker.
 */
EventBus::listen('reservation.confirmed', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('reservation.confirmed', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [reservation.confirmed]: {$e->getMessage()}");
    }
}, -10);

/**
 * Reservation reminder — sent by cron for tomorrow's reservations.
 */
EventBus::listen('reservation.reminder', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('reservation.reminder', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [reservation.reminder]: {$e->getMessage()}");
    }
}, -10);

/**
 * Carnet low balance — notify member when carnet entries are running low.
 */
EventBus::listen('carnet.low_balance', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('carnet.low_balance', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [carnet.low_balance]: {$e->getMessage()}");
    }
}, -10);

/**
 * Carnet guest entry recorded — optional notification to member.
 */
EventBus::listen('carnet_guest.entry_recorded', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('carnet_guest.entry_recorded', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [carnet_guest.entry_recorded]: {$e->getMessage()}");
    }
}, -10);

/**
 * Coach payment processed — notify coach of payment.
 */
EventBus::listen('coach.payment_processed', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('coach.payment_processed', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [coach.payment_processed]: {$e->getMessage()}");
    }
}, -10);

/**
 * Player evaluation submitted — notify player/parent.
 */
EventBus::listen('player.evaluation_submitted', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('player.evaluation_submitted', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [player.evaluation_submitted]: {$e->getMessage()}");
    }
}, -10);

/**
 * Player medical expiry — dispatched by cron, triggers notification.
 */
EventBus::listen('player.medical_expiry', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('player.medical_expiry', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [player.medical_expiry]: {$e->getMessage()}");
    }
}, -10);

/**
 * Tournament registration open — notify eligible players.
 */
EventBus::listen('tournament.registration_open', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('tournament.registration_open', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [tournament.registration_open]: {$e->getMessage()}");
    }
}, -10);

/**
 * Player injury reported — notify parent immediately.
 */
EventBus::listen('player.injury_reported', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('player.injury_reported', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [player.injury_reported]: {$e->getMessage()}");
    }
}, -10);

/**
 * Player achievement earned — notify player/parent.
 */
EventBus::listen('player.achievement_earned', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('player.achievement_earned', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [player.achievement_earned]: {$e->getMessage()}");
    }
}, -10);

/**
 * Schedule change requested — notify admin.
 */
EventBus::listen('schedule.change_requested', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('schedule.change_requested', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [schedule.change_requested]: {$e->getMessage()}");
    }
}, -10);

/**
 * Group transfer approved — notify player/parent.
 */
EventBus::listen('group.transfer_approved', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('group.transfer_approved', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [group.transfer_approved]: {$e->getMessage()}");
    }
}, -10);

/**
 * Private match booked — notify facility manager.
 */
EventBus::listen('private_match.booked', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('private_match.booked', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [private_match.booked]: {$e->getMessage()}");
    }
}, -10);

/**
 * Session feedback submitted — notify coach.
 */
EventBus::listen('session.feedback_submitted', function (array $data): void {
    try {
        NotificationTriggerService::processEvent('session.feedback_submitted', $data);
    } catch (\Throwable $e) {
        Logger::error("Notification trigger error [session.feedback_submitted]: {$e->getMessage()}");
    }
}, -10);

// ─── SMS/WhatsApp Notification Service for Parents ─────────────────────────────
\App\Modules\Notifications\Services\SmsNotificationService::registerListeners();
