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

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

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

$botToken = '6984456345:AAH2c4sr8kRtbUTWzx71hddcdX2GE1m5WVQ';
$channelUsername = '@playercubevideo'; // کانال مقصد

/* --------- توابع کمکی --------- */
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');
    }
}
function isFinished(?string $eps): bool {
    return in_array($eps, ['FT','AET','PEN','FT_PEN','AP'], true);
}

/* --------- ساخت پیش‌نمایش نتایج امروز --------- */
// اگر هنوز قبلِ ساعت 02:00 هستیم، تاریخ را دیروز بگیر تا نتایج روز قبل حفظ شود
$nowHour = (int)date('G'); // 0..23
$today   = $nowHour < 2 ? date('Y-m-d', strtotime('-1 day')) : 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";

$previewText = "📭 No match results found for featured teams today.";
$json = @file_get_contents($apiUrl);
if ($json) {
    $data        = json_decode($json);
    $featuredIds = getFeaturedTeams($db);
    $grouped     = [];

    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;

                if (!isFinished($event->Eps ?? null)) continue;

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

                $grouped[$leagueName][] = "🔹 {$home} {$g1}–{$g2} {$away}";
            }
        }
    }

    if (!empty($grouped)) {
        $previewText = "<b>📋 Match Results ({$today})</b>\n─────────────\n\n";
        foreach ($grouped as $league => $matches) {
            $previewText .= "🔮 <b>{$league}</b>\n\n";
            $previewText .= implode("\n", $matches) . "\n\n";
        }
            $previewText .= "──────────────\n";
            $previewText .= "🔎 Live scores and highlights available on:\n\n@Playerscubebot";
    }
}

/* --------- ارسال دستی یا خودکار (با دیباگ) --------- */
$flash = '';

function sendResultsNow(string $botToken, string $channelUsername, string $previewText): bool {
    $api = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $resp = @file_get_contents($api.'?'.http_build_query([
        'chat_id'    => $channelUsername,
        'text'       => $previewText,
        'parse_mode' => 'HTML'
    ]));

    if ($resp === false) {
        error_log("❌ Telegram send failed (no response)");
        return false;
    }
    $j = json_decode($resp, true);
    if (!($j['ok'] ?? false)) {
        error_log("❌ Telegram API error: " . $resp);
        return false;
    }
    error_log("✅ Telegram message sent automatically");
    return true;
}

/* بررسی ورود به شرط‌ها */
error_log("🟡 DEBUG: GET params => " . json_encode($_GET));
error_log("🟡 DEBUG: POST params => " . json_encode($_POST));

if ((isset($_POST['action']) && $_POST['action'] === 'send_now') || isset($_GET['auto_send'])) {
    error_log("🟢 DEBUG: sendResultsNow() triggered");
    $ok = sendResultsNow($botToken, $channelUsername, $previewText);
    if ($ok) {
        $flash = '✅ Results message sent to channel.';
    }
} else {
    error_log("🔴 DEBUG: Condition not matched — no send triggered");
}

?>
<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8">
<title>نتایج مهمترین بازی‌های</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">📋 نتایج مهمترین بازی‌های</h1>

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

  <form method="post">
    <!-- پیش‌نمایش امن در فرم -->
    <textarea name="message" rows="14" class="w-full p-3 text-black rounded mb-3"><?= htmlspecialchars($previewText) ?></textarea>
    <button type="submit" name="action" value="send_now" class="bg-blue-600 px-4 py-2 rounded">📤 ارسال الان به کانال</button>
  </form>

  <div class="mt-4">
    <a href="dashboard.php" class="text-blue-600 hover:text-blue-800 font-medium">⬅️ بازگشت به داشبورد</a>
  </div>
</div>
</body>
</html>
