<?php
declare(strict_types=1);

use App\Core\EventBus;
use App\Modules\PlayerApi\Services\PlayerNotificationService;

EventBus::listen('coach.day_off_requested', function (array $data) {
    $db = \App\Core\App::getInstance()->db();
    $players = $db->select(
        "SELECT gm.player_id FROM group_memberships gm
         INNER JOIN training_groups tg ON tg.id = gm.group_id
         WHERE tg.coach_id = ? AND gm.status = 'active'",
        [$data['coach_id']]
    );

    foreach ($players as $p) {
        PlayerNotificationService::notify(
            (int) $p['player_id'],
            'session',
            'إلغاء تدريب',
            'تم إلغاء تدريب يوم ' . ($data['request_date'] ?? '') . ' بسبب إجازة المدرب',
            $data
        );
    }
});

EventBus::listen('coach.replacement_confirmed', function (array $data) {
    $db = \App\Core\App::getInstance()->db();
    $players = $db->select(
        "SELECT gm.player_id FROM group_memberships gm
         INNER JOIN training_groups tg ON tg.id = gm.group_id
         WHERE tg.coach_id = ? AND gm.status = 'active'",
        [$data['original_coach_id']]
    );

    foreach ($players as $p) {
        PlayerNotificationService::notify(
            (int) $p['player_id'],
            'session',
            'مدرب بديل',
            'سيحل المدرب ' . ($data['replacement_name'] ?? '') . ' محل المدرب يوم ' . ($data['request_date'] ?? ''),
            $data
        );
    }
});
