<?php
require_once 'config.php';
require_once 'functions.php';
require_once __DIR__ . '/../../../LiveScore/persiantranslate.php';

if (!function_exists('getFeaturedTeams')) {
    function getFeaturedTeams(PDO $db): array {
        $stmt = $db->query("SELECT team_id FROM featured_teams WHERE is_active=1");
        return array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'team_id');
    }
}

if (!function_exists('sendToChannel')) {
    function sendToChannel(string $botToken, string $channelUsername, string $text): void {
        $api = "https://api.telegram.org/bot{$botToken}/sendMessage";
        @file_get_contents($api.'?'.http_build_query([
            'chat_id'    => $channelUsername,
            'text'       => $text,
            'parse_mode' => 'HTML'
        ]));
    }
}

$botToken        = '6984456345:AAH2c4sr8kRtbUTWzx71hddcdX2GE1m5WVQ';
$channelUsername = '@KickPrediict';

$featuredIds = array_map('intval', getFeaturedTeams($db));

$data = [
    'Stages' => [
        (object)[
            'Snm' => 'Test League',
            'Events' => [
                (object)[
                    'T1' => [(object)['ID' => $featuredIds[0] ?? 111, 'Nm' => 'تیم تست میزبان']],
                    'T2' => [(object)['ID' => 999, 'Nm' => 'تیم تست مهمان']],
                    'Tr1' => 2,
                    'Tr2' => 1,
                    'Eps' => 'FT',
                    'Eid' => '999999',
                ]
            ]
        ]
    ]
];

foreach ($data['Stages'] as $stage) {
    $leagueName = getleagues($stage->Snm ?? 'لیگ نامشخص');
    foreach ($stage->Events as $event) {
        $homeId = (int)($event->T1[0]->ID ?? 0);
        $awayId = (int)($event->T2[0]->ID ?? 0);
        if (!in_array($homeId, $featuredIds, true) && !in_array($awayId, $featuredIds, true)) continue;
        if ($event->Eps !== 'FT') continue;

        $home = getTeamName($event->T1[0]->Nm ?? '');
        $away = getTeamName($event->T2[0]->Nm ?? '');
        $g1   = convertToPersianNumbers((string)($event->Tr1 ?? '—'));
        $g2   = convertToPersianNumbers((string)($event->Tr2 ?? '—'));

        $text = "🏁 پایان بازی | {$leagueName}\n🔹 {$home} {$g1}–{$g2} {$away}";

        sendToChannel($botToken, $channelUsername, $text);
        echo "Message sent: {$text}\n";
    }
}
