<?php
declare(strict_types=1);
ini_set('display_errors', '1');
error_reporting(E_ALL);

header('Content-Type: text/html; charset=utf-8');

date_default_timezone_set('Europe/Vienna');
putenv('TZ=Europe/Vienna');

require_once 'config.php';
require_once 'functions.php';

// تابع گرفتن تیم‌های منتخب
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');
}

// توکن و یوزرنیم کانال (مقدار درست رو بگذار)
$botToken = '6984456345:AAH2c4sr8kRtbUTWzx71hddcdX2GE1m5WVQ';
$channelUsername = '@playercubevideo'; // کانال مقصد

// دکمه‌های پنل
if (isset($_POST['action']) && $_POST['action'] === 'send_now') {
    $message = $_POST['message'] ?? '';
    if ($message !== '') {
        $apiUrl = "https://api.telegram.org/bot{$botToken}/sendMessage";
        file_get_contents($apiUrl . '?' . http_build_query([
            'chat_id' => $channelUsername,
            'text' => $message,
            'parse_mode' => 'HTML'
        ]));
        $flash = '✅ پیام به کانال ارسال شد.';
    }
}

// امروزمیلادی
$today = date('Y-m-d');
$apiDate = str_replace('-', '', $today);
$apiUrl = "https://prod-public-api.livescore.com/v1/api/app/date/soccer/{$apiDate}/0.00?countryCode=AT&locale=en";
$json = @file_get_contents($apiUrl);
if (!$json) {
    $previewText = "❌ Error fetching data from API";
} else {
    $data = json_decode($json);
    $featuredIds = getFeaturedTeams($db);

    $lines = [];
    if (isset($data->Stages)) {
        foreach ($data->Stages as $stage) {
            if (empty($stage->Events)) continue;
            $leagueName = $stage->Snm ?? 'Unknown League';

            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;
                }

            // Match time (as-is from API, no timezone conversion)
// Match time (converted to Austria local time)
        $formattedTime = '?';
        if (isset($event->Esd) && $event->Esd) {
            $esdStr = (string)$event->Esd; // e.g. 20251010153000
            if (strlen($esdStr) >= 12) {
                // parse as UTC, then convert to Vienna time
                $utc = new DateTimeZone('UTC');
                $vienna = new DateTimeZone('Europe/Vienna');
                $dt = DateTime::createFromFormat('YmdHi', substr($esdStr, 0, 12), $utc);
                if ($dt instanceof DateTime) {
                    $formattedTime = $dt->setTimezone($vienna)->format('H:i');
                }
            }
        }

                $home = $event->T1[0]->Nm ?? 'Home';
                $away = $event->T2[0]->Nm ?? 'Away';

                // گروه‌بندی بر اساس لیگ
                if (!isset($grouped[$leagueName])) {
                    $grouped[$leagueName] = [];
                }
                $grouped[$leagueName][] = "🔹 {$home} {$formattedTime} {$away}";

            }
        }
    }

if (!empty($grouped)) {
$previewText = "<b>🔥 Today's Featured Matches ({$today})</b>\n──────────────\n\n";

    foreach ($grouped as $league => $matches) {
    $previewText .= "🔮  <b>$league</b>\n\n";
        foreach ($matches as $match) {
            $previewText .= "{$match}\n";
        }
        $previewText .= "\n"; // فاصله بین لیگ‌ها
    }

    // — امضا زیر پیش‌نمایش —
    $botUser    = isset($BotUserName) ? $BotUserName : '@PlayersCubebot';
    // $channelUsr = isset($channelUsername) ? $channelUsername : '@KickPrediict';
    $previewText .= "───────────────\n";
    $previewText .= "🔎 Live scores and stream links in:\n\n{$botUser}";
} else {
    $previewText = "📭 No featured team matches scheduled for today.";
}

}

// اضافه کردن بخش خودکار برای کرون جاب
if (isset($_GET['auto_send']) && $_GET['auto_send'] === '1') {
    $message = $previewText ?? '';
    if ($message !== '' && $message !== "📭 No featured team matches scheduled for today.") {
        $apiUrl = "https://api.telegram.org/bot{$botToken}/sendMessage";
        file_get_contents($apiUrl . '?' . http_build_query([
            'chat_id' => $channelUsername,
            'text' => $message,
            'parse_mode' => 'HTML'
        ]));
        exit;
    }
}

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');
    }
}

?>
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Today's Featured Matches</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
</head>
<body class="bg-gray-900 text-white p-4">
<div class="max-w-4xl mx-auto">
    <h1 class="text-xl font-bold mb-4">🔥 Today's Featured Matches</h1>

    <?php if (!empty($flash)): ?>
        <div class="bg-green-600 p-3 rounded mb-4"><?= htmlspecialchars($flash) ?></div>
    <?php endif; ?>

    <form method="post">
        <textarea name="message" rows="12" class="w-full p-3 text-black rounded mb-3"><?= htmlspecialchars($previewText) ?></textarea>
        <div class="flex gap-2">
            <button type="submit" name="action" value="send_now" class="bg-blue-600 px-4 py-2 rounded">📤 Send to Chanel</button>
        </div>
    </form>

        <div class="mt-8 text-center">
            <a href="dashboard.php" class="text-blue-600 hover:text-blue-800 font-medium">⬅️ Back to Dashboard</a>
        </div>
</div>
</body>
</html>
