<?php
declare(strict_types=1);

namespace App\Modules\Notifications\Services;

use App\Core\App;
use App\Core\EventBus;

class SmsNotificationService
{
    public static function send(string $phone, string $message, string $channel = 'sms'): bool
    {
        $db = App::getInstance()->db();

        $db->insert('notification_sms_log', [
            'phone'      => $phone,
            'message'    => $message,
            'channel'    => $channel,
            'status'     => 'queued',
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        $config = App::getInstance()->config('sms') ?? [];
        $provider = $config['provider'] ?? 'log';

        if ($provider === 'log') {
            $db->update('notification_sms_log', ['status' => 'sent', 'sent_at' => date('Y-m-d H:i:s')], '`phone` = ? AND `status` = ? ORDER BY id DESC LIMIT 1', [$phone, 'queued']);
            return true;
        }

        return true;
    }

    public static function sendToParent(int $parentId, string $message): bool
    {
        $db = App::getInstance()->db();
        $parent = $db->selectOne("SELECT phone FROM parent_accounts WHERE id = ?", [$parentId]);
        if (!$parent || empty($parent['phone'])) return false;

        return self::send($parent['phone'], $message);
    }

    public static function sendBulk(array $phones, string $message): int
    {
        $sent = 0;
        foreach ($phones as $phone) {
            if (self::send($phone, $message)) {
                $sent++;
            }
        }
        return $sent;
    }

    public static function registerListeners(): void
    {
        EventBus::listen('medical.expiring_soon', function (array $data) {
            $db = App::getInstance()->db();
            $parentLinks = $db->select(
                "SELECT pa.phone FROM parent_player_links ppl
                 JOIN parent_accounts pa ON pa.id = ppl.parent_id
                 WHERE ppl.player_id = ?",
                [(int) $data['player_id']]
            );
            foreach ($parentLinks as $link) {
                if (!empty($link['phone'])) {
                    self::send($link['phone'], 'تنبيه: الشهادة الطبية للاعب ستنتهي خلال ' . $data['days_left'] . ' يوم. يرجى التجديد.');
                }
            }
        }, 80);

        EventBus::listen('session.attendance_marked', function (array $data) {
            if (($data['status'] ?? '') !== 'absent') return;
            $db = App::getInstance()->db();
            $parentLinks = $db->select(
                "SELECT pa.phone FROM parent_player_links ppl
                 JOIN parent_accounts pa ON pa.id = ppl.parent_id
                 WHERE ppl.player_id = ?",
                [(int) ($data['player_id'] ?? 0)]
            );
            foreach ($parentLinks as $link) {
                if (!empty($link['phone'])) {
                    self::send($link['phone'], 'تنبيه: تم تسجيل غياب اللاعب في جلسة اليوم.');
                }
            }
        }, 80);

        EventBus::listen('waitlist.spot_offered', function (array $data) {
            $db = App::getInstance()->db();
            $player = $db->selectOne("SELECT p.full_name_ar FROM players p WHERE id = ?", [(int) ($data['player_id'] ?? 0)]);
            $parentLinks = $db->select(
                "SELECT pa.phone FROM parent_player_links ppl
                 JOIN parent_accounts pa ON pa.id = ppl.parent_id
                 WHERE ppl.player_id = ?",
                [(int) ($data['player_id'] ?? 0)]
            );
            foreach ($parentLinks as $link) {
                if (!empty($link['phone'])) {
                    self::send($link['phone'], 'مكان متاح! يوجد مكان شاغر في المجموعة للاعب ' . ($player['full_name_ar'] ?? '') . '. يرجى التأكيد خلال 48 ساعة.');
                }
            }
        }, 80);
    }
}
