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

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

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

/* ===== ایجاد جدول مخصوص انگلیسی ===== */
try {
    $db->exec("
        CREATE TABLE IF NOT EXISTS sent_events_en (
            event_hash VARCHAR(64) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (event_hash)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
    ");
    error_log("✅ Table check done (sent_events_en).");
} catch (Throwable $e) {
    error_log('❌ Create table error: ' . $e->getMessage());
}

/* ===== توابع ===== */
function getFeaturedTeams(PDO $db): array {
    try {
        $stmt = $db->query("SELECT team_id FROM featured_teams WHERE is_active=1");
        return array_map('intval', array_column($stmt->fetchAll(PDO::FETCH_ASSOC), 'team_id'));
    } catch (Throwable $e) {
        error_log('getFeaturedTeams error: ' . $e->getMessage());
        return [];
    }
}

function isFinished(?string $eps): bool {
    return in_array($eps, ['FT','AET','PEN','FT_PEN','AP'], true);
}

function wasSent(PDO $db, string $hash): bool {
    $stmt = $db->prepare("SELECT 1 FROM sent_events_en WHERE event_hash=? LIMIT 1");
    $stmt->execute([$hash]);
    return (bool)$stmt->fetchColumn();
}

function markSent(PDO $db, string $hash): void {
    try {
        $stmt = $db->prepare("INSERT IGNORE INTO sent_events_en (event_hash) VALUES (?)");
        $stmt->execute([$hash]);
        error_log("✅ markSent executed for hash: $hash");
    } catch (Throwable $e) {
        error_log("❌ markSent insert failed: " . $e->getMessage());
    }
}

function sendToChannel(string $botToken, array $channelUsernames, string $text): bool {
    $api = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $okAll = true;
    foreach ($channelUsernames as $channelUsername) {
        $payload = [
            'chat_id' => $channelUsername,
            'text'    => $text,
            'parse_mode' => 'HTML',
            'disable_web_page_preview' => true,
        ];
        $ctx = stream_context_create(['http'=>[
            'method'=>'POST',
            'header'=>"Content-Type: application/x-www-form-urlencoded\r\n",
            'content'=>http_build_query($payload),
            'timeout'=>15,
        ]]);
        $resp = @file_get_contents($api, false, $ctx);
        if ($resp === false) {
            $err = error_get_last();
            error_log("❌ Telegram send failed ({$channelUsername}): " . ($err['message'] ?? 'unknown'));
            $okAll = false;
        } else {
            $j = json_decode($resp, true);
            error_log("Telegram response: " . $resp);
            if (!($j['ok'] ?? false)) {
                error_log("❌ Telegram API error ({$channelUsername}): " . $resp);
                $okAll = false;
            } else {
                error_log("✅ Message sent successfully to {$channelUsername}");
            }
        }
        usleep(200000);
    }
    return $okAll;
}

/* ===== گرفتن فید ===== */
$nowHour = (int)date('G'); // 0..23
$today   = $nowHour < 2 ? date('Y-m-d', strtotime('-1 day')) : date('Y-m-d');
$apiDate = str_replace('-', '', $today);

$json = @file_get_contents("https://prod-public-api.livescore.com/v1/api/app/date/soccer/{$apiDate}/3.30");
if (!$json) {
    $json = @file_get_contents("https://prod-public-api.livescore.com/v1/api/app/live/soccer/3.30");
}
if (!$json) {
    error_log("❌ No JSON fetched from LiveScore API");
    exit;
}

$data = json_decode($json);
if (!isset($data->Stages) || !is_array($data->Stages)) {
    error_log("❌ Invalid data format from API");
    exit;
}

$featuredIds = getFeaturedTeams($db);
error_log("✅ Featured teams: " . implode(',', $featuredIds));

/* ===== پردازش ===== */
foreach ($data->Stages as $stage) {
    if (empty($stage->Events) || !is_array($stage->Events)) continue;

    $leagueName = ($stage->Cnm ?? '') . ' / ' . ($stage->Snm ?? 'Unknown League');

    foreach ($stage->Events as $event) {
        $homeId = (int)($event->T1[0]->ID ?? 0);
        $awayId = (int)($event->T2[0]->ID ?? 0);

        if (!empty($featuredIds) && !in_array($homeId,$featuredIds,true) && !in_array($awayId,$featuredIds,true)) {
            continue;
        }

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

        $eid  = (string)($event->Eid ?? '');
        if ($eid === '') {
            $esd = (string)($event->Esd ?? '');
            $eid = md5($homeId.'-'.$awayId.'-'.$esd.'-FT');
        }
        $hash = sha1('EN-FT-'.$eid);

        if (wasSent($db, $hash)) {
            error_log("⏭ Skip duplicate: $hash");
            continue;
        }

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

        $text = "✅ Full Time\n\n⚽️ {$leagueName}\n\n🎯 {$home} {$g1}–{$g2} {$away}\n\n@Playerscubebot";

        $ok = sendToChannel($botToken, [$channelUsername], $text);
        if ($ok) {
            markSent($db, $hash);
        } else {
            error_log("❌ sendToChannel returned false for $hash");
        }
        usleep(200000);
    }
}
?>
