<?php
// league_standings_scraper.php (v4.0 - Smart Injection + 95 Leagues + Live Score Fix)

// --- إعدادات النظام ---
ini_set('max_execution_time', 0);
ini_set('memory_limit', '512M');
ini_set('display_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/scraper_errors.log');

if (!defined('MAX_FILE_SIZE')) define('MAX_FILE_SIZE', 10000000);

require __DIR__ . '/config.php';
require __DIR__ . '/simple_html_dom.php';

// --- القائمة الصلبة (95 بطولة) ---
$TARGET_LEAGUES_IDS = [
    1204, 1399, 1269, 1229, 1221, 1322, 1352, 1425, 1205, 1193, 1368, 1313, 1420, 2024, 1356, 1289, 1440, 18869, 1001, 1005, 1007, 18853, 1059, 1513, 1635, 1063, 18924, 1967, 2663, 4198, 5362, 18931, 1722, 4262, 1022, 1023, 1515, 1779, 2607, 1011, 1037, 1039, 1040, 1056, 1038, 1937, 1041, 1798, 2045, 1048, 1049, 1050, 1051, 1054, 1052, 1531, 4529, 1603, 1198, 1199, 1611, 1218, 1219, 1633, 1226, 1620, 1264, 1626, 1397, 1624, 1636, 1354, 1622, 2090, 2265, 18875, 5271, 2403, 2922, 1941, 18854, 18887, 5198, 19044, 1, 3, 1148, 1534, 1535, 1759, 1803, 2392, 2633, 1284, 1769
];

// --- دوال الاتصال ---
function connectToDB() {
    $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];
    try { return new PDO($dsn, DB_USER, DB_PASS, $options); } 
    catch (PDOException $e) { error_log("DB Error: " . $e->getMessage()); return null; }
}

function fetchPageContent($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

// --- أدوات التنسيق (لتوحيد الأسماء) ---
function normalizeArabicText($text) {
    if (!$text) return '';
    $text = trim($text);
    $text = mb_strtolower($text, 'UTF-8');
    $patterns = ['/[أإآ]/u' => 'ا', '/ة/u' => 'ه', '/ى/u' => 'ي', '/[ًٌٍَُِّْ]/u' => '', '/ـ/u' => ''];
    $text = preg_replace(array_keys($patterns), array_values($patterns), $text);
    $removeWords = ['نادي', 'فريق', 'منتخب', 'الرياضي', 'لكرة القدم', 'تحت 20', 'تحت 19', 'تحت 23', 'الاولمبي', 'للسيدات', 'u20', 'u19', 'u23', 'women', 'fc', 'sc'];
    foreach ($removeWords as $word) { $text = preg_replace('/\b' . preg_quote($word, '/') . '\b/u', '', $text); }
    $text = preg_replace('/[^\p{L}\p{N}\s]/u', '', $text);
    return trim(preg_replace('/\s+/', ' ', $text));
}

// =================================================================
// ★★★ دالة الحقن الصارمة (v5): تظهر النتيجة فقط أثناء المباراة وتحذفها عند الانتهاء ★★★
// =================================================================
function injectLiveScoresFromMatches($db, $leagueId, &$standings) {
    // 1. جلب اسم الدوري
    $stmt = $db->prepare("SELECT league_name FROM " . DB_PREFIX . "leagues_list WHERE league_id = ?");
    $stmt->execute([$leagueId]);
    $leagueName = $stmt->fetchColumn();
    
    if (!$leagueName) return;

    // 2. جلب مباريات اليوم (لمعرفة حالتها لحظياً)
    $sql = "SELECT team1, team2, score, status, timer FROM " . DB_PREFIX . "matches 
            WHERE league = ? AND date = CURDATE()";
            
    $stmtM = $db->prepare($sql);
    $stmtM->execute([$leagueName]);
    $todaysMatches = $stmtM->fetchAll();

    if (empty($todaysMatches)) return;

    // 3. تحديث المصفوفة بناءً على حالة المباراة
    foreach ($todaysMatches as $match) {
        $t1 = normalizeArabicText($match['team1']);
        $t2 = normalizeArabicText($match['team2']);
        $score = trim($match['score']);
        $status = $match['status'];

        // تحديد هل المباراة جارية الآن؟
        $isLive = (
            strpos($status, 'مباشر') !== false || 
            strpos($status, 'شوط') !== false || 
            strpos($status, 'Live') !== false || 
            strpos($status, 'وقت') !== false ||
            !empty($match['timer'])
        );

        // التحقق من الانتهاء
        $isEnded = (strpos($status, 'انتهت') !== false || strpos($status, 'Fin') !== false);

        foreach ($standings as &$row) {
            $rowTeam = normalizeArabicText($row['team_name']);
            
            // إذا وجدنا الفريق في جدول الترتيب
            if ($rowTeam == $t1 || $rowTeam == $t2) {
                
                // الحالة أ: المباراة جارية (حقن النتيجة + تفعيل الوميض)
                if ($isLive && !empty($score) && strpos($score, '-') !== false) {
                    $scoreParts = explode('-', $score);
                    $s1 = trim($scoreParts[0]);
                    $s2 = trim($scoreParts[1]);
                    
                    if ($rowTeam == $t1) {
                        $row['live_score'] = "{$s1} - {$s2}";
                    } else {
                        $row['live_score'] = "{$s2} - {$s1}";
                    }
                    $row['is_match_live'] = true; // لتفعيل الوميض
                } 
                // الحالة ب: المباراة انتهت أو لم تبدأ (تنظيف النتيجة + إيقاف الوميض)
                else {
                    $row['live_score'] = null;    // حذف النتيجة من الـ JSON
                    $row['is_match_live'] = false; // إيقاف الوميض
                }
            }
        }
    }
}
// --- دالة سحب الترتيب (Core Scraping Function) ---
function scrapeAndStoreLeagueStandings($leagueId, $leagueSlug, $db, $stmtInsert) {
    $url = "https://www.btolat.com/league/standings/{$leagueId}/{$leagueSlug}";
    $content = fetchPageContent($url);
    
    if (!$content) return false;
    
    $html = str_get_html($content);
    if (!$html) $html = str_get_html(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));
    if (!$html) return false;

    $standings = [];
    $tables = $html->find('table.leagueTable');

    if (!empty($tables)) {
        foreach ($tables as $tableIndex => $table) {
            $groupHeader = $table->find('th.groupTitle', 0);
            $groupName = $groupHeader ? trim($groupHeader->plaintext) : "Group " . ($tableIndex + 1);

            foreach ($table->find('tr') as $row) {
                if ($row->find('th', 0)) continue; 
                $cols = $row->find('td');
                if (count($cols) < 8) continue; 

                $rowData = [
                    'rank' => trim($cols[0]->plaintext),
                    'team_name' => '', 'team_logo' => '', 'team_btolat_id' => null,
                    'live_score' => null, 
                    'played' => '0', 'wins' => '0', 'draws' => '0', 'losses' => '0',
                    'goals_for' => '0', 'goals_against' => '0', 'goal_diff' => '0', 'points' => '0',
                    'group_name' => $groupName
                ];

                // بيانات الفريق
                $teamCol = $cols[1];
                $teamLink = $teamCol->find('a', 0);
                if ($teamLink) {
                    $rowData['team_name'] = trim($teamLink->plaintext);
                    if (preg_match('/\/team\/(\d+)\//', $teamLink->href, $m)) $rowData['team_btolat_id'] = (int)$m[1];
                    $img = $teamLink->find('img', 0);
                    $logoSrc = $img ? ($img->{'data-original'} ?? $img->src) : null;
                    if ($logoSrc) $rowData['team_logo'] = (strpos($logoSrc, '//') === 0) ? 'https:' . $logoSrc : $logoSrc;
                } else {
                    $rowData['team_name'] = trim($teamCol->plaintext);
                }

                // محاولة سحب النتيجة من المصدر أولاً
                $liveScoreHtml = $teamCol->find('b.stndlivscor', 0);
                if ($liveScoreHtml) {
                    $scoreSpan = $liveScoreHtml->find('span.score', 0);
                    if ($scoreSpan) {
                        $cleanScore = trim($scoreSpan->plaintext);
                        $cleanScore = str_replace(['&nbsp;', ' '], [' ', ''], $cleanScore); 
                        if (!empty($cleanScore)) {
                            $rowData['live_score'] = $cleanScore; 
                        }
                    }
                }

                // الإحصائيات
                $getVal = function($idx) use ($cols) { return isset($cols[$idx]) ? trim($cols[$idx]->plaintext) : '0'; };
                $rowData['played'] = $getVal(2);
                $rowData['wins'] = $getVal(3);
                $rowData['draws'] = $getVal(4);
                $rowData['losses'] = $getVal(5);
                $rowData['goals_for'] = $getVal(6);
                $rowData['goals_against'] = $getVal(7);
                $rowData['goal_diff'] = $getVal(8);
                $rowData['points'] = $getVal(9);

                $standings[] = $rowData;
            }
        }
    }
    
    $html->clear(); unset($html);

    // ★★★ الحقن الذكي: دمج النتائج من جدول المباريات لضمان الدقة ★★★
    if (!empty($standings)) {
        injectLiveScoresFromMatches($db, $leagueId, $standings);
        
        $json = json_encode($standings, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $stmtInsert->execute([':league_id' => $leagueId, ':standings_json' => $json]);
        return true;
    }
    return false;
}

// =================================================================
// ★★★ المحرك الذكي (Smart Engine) ★★★
// =================================================================
function runSmartStandingsSystem($mode, $targetIds) {
    global $TARGET_LEAGUES_IDS;
    $db = connectToDB();
    if (!$db) exit;

    if (empty($targetIds)) { echo "<p>No target leagues defined.</p>"; return; }
    $idsString = implode(',', $targetIds);
    
    $stmtInsert = $db->prepare("INSERT INTO " . DB_PREFIX . "league_standings (league_id, standings_json, last_scraped) VALUES (:league_id, :standings_json, NOW()) ON DUPLICATE KEY UPDATE standings_json = VALUES(standings_json), last_scraped = NOW()");

    // === المسار 1: التحديث الذكي المباشر (Smart Live Update) ===
    if ($mode == 'live' || $mode == 'auto') {
        echo "<h2>🚀 Mode: Smart Live Standings</h2>";

        // البحث عن البطولات التي لها مباريات جارية الآن
        $sqlLiveLeagues = "SELECT DISTINCT l.league_id, l.league_slug 
                           FROM " . DB_PREFIX . "leagues_list l
                           JOIN " . DB_PREFIX . "matches m ON l.league_name = m.league
                           WHERE m.date = CURDATE()
                           AND (m.status LIKE '%مباشر%' OR m.status LIKE '%شوط%' OR m.status LIKE '%Live%' OR m.timer IS NOT NULL)
                           AND l.league_id IN ($idsString)";

        $stmt = $db->query($sqlLiveLeagues);
        $activeLeagues = $stmt->fetchAll();

        if (!empty($activeLeagues)) {
            echo "<p style='color:green'>Found " . count($activeLeagues) . " leagues with LIVE matches. Updating Standings...</p>";
            foreach ($activeLeagues as $lg) {
                $success = scrapeAndStoreLeagueStandings($lg['league_id'], $lg['league_slug'], $db, $stmtInsert);
                if ($success) echo "<p>✅ Updated Live Standings: {$lg['league_slug']}</p>";
            }
        } else {
            echo "<p style='color:orange'>No LIVE matches found right now. Skipping Live update.</p>";
            
            // Backup: تحديث البطولات التي ستلعب قريباً
            $sqlTodayLeagues = "SELECT DISTINCT l.league_id, l.league_slug 
                                FROM " . DB_PREFIX . "leagues_list l
                                JOIN " . DB_PREFIX . "matches m ON l.league_name = m.league
                                WHERE m.date = CURDATE()
                                AND m.status NOT LIKE '%انتهت%'
                                AND l.league_id IN ($idsString)
                                AND (l.last_scraped < (NOW() - INTERVAL 15 MINUTE) OR l.last_scraped IS NULL)
                                LIMIT 3"; 
            
            $stmtBackup = $db->query($sqlTodayLeagues);
            $backupLeagues = $stmtBackup->fetchAll();
            
            if (!empty($backupLeagues)) {
                echo "<p>Running Pre-Match Backup Update...</p>";
                foreach ($backupLeagues as $lg) {
                    scrapeAndStoreLeagueStandings($lg['league_id'], $lg['league_slug'], $db, $stmtInsert);
                    echo "<p>Updated (Pre-Match): {$lg['league_slug']}</p>";
                }
            }
        }
    }

    // === المسار 2: الأرشيف الكامل (Full Archive) ===
    if ($mode == 'full') {
        echo "<h2>📚 Mode: Full Archive Scan</h2>";
        
        $sqlFull = "SELECT league_id, league_slug 
                    FROM " . DB_PREFIX . "leagues_list 
                    WHERE league_id IN ($idsString) 
                    AND (last_scraped < (NOW() - INTERVAL 12 HOUR) OR last_scraped IS NULL)
                    ORDER BY last_scraped ASC 
                    LIMIT 5";
                    
        $stmt = $db->query($sqlFull);
        $leagues = $stmt->fetchAll();

        foreach ($leagues as $lg) {
            echo "<p>Full Scan: {$lg['league_slug']}...</p>";
            scrapeAndStoreLeagueStandings($lg['league_id'], $lg['league_slug'], $db, $stmtInsert);
            // تحديث وقت الفحص حتى لو لم يتغير الترتيب لكي لا نعيد فحصه فوراً
            $db->query("UPDATE " . DB_PREFIX . "leagues_list SET last_scraped = NOW() WHERE league_id = {$lg['league_id']}");
        }
    }
}

// --- التعامل مع المدخلات ---
$mode = 'auto'; 
if (isset($argv[1])) {
    parse_str($argv[1], $cli_params);
    if (isset($cli_params['mode'])) $mode = $cli_params['mode'];
} elseif (isset($_GET['mode'])) {
    $mode = $_GET['mode'];
}

runSmartStandingsSystem($mode, $TARGET_LEAGUES_IDS);
?>