<?php
// league_fixtures_scraper.php (v16.0 - Final with Timer Field Support)

// --- إعدادات النظام ---
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';

// --- القائمة الصلبة ---
$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));
}

function getArabicDate($dateStr) {
    if (preg_match('/[أ-ي]/u', $dateStr)) return $dateStr; 
    $timestamp = strtotime($dateStr);
    if (!$timestamp) return $dateStr;
    $days = ['Sat' => 'السبت', 'Sun' => 'الاحد', 'Mon' => 'الاثنين', 'Tue' => 'الثلاثاء', 'Wed' => 'الاربعاء', 'Thu' => 'الخميس', 'Fri' => 'الجمعة'];
    $months = ['Jan' => 'يناير', 'Feb' => 'فبراير', 'Mar' => 'مارس', 'Apr' => 'أبريل', 'May' => 'مايو', 'Jun' => 'يونيو', 'Jul' => 'يوليو', 'Aug' => 'أغسطس', 'Sep' => 'سبتمبر', 'Oct' => 'أكتوبر', 'Nov' => 'نوفمبر', 'Dec' => 'ديسمبر'];
    return $days[date('D', $timestamp)] . " , " . date('d', $timestamp) . " " . $months[date('M', $timestamp)] . " " . date('Y', $timestamp);
}

function formatArabicTime($timeStr) {
    if (!$timeStr || !preg_match('/\d+:\d+/', $timeStr)) return false;
    $timestamp = strtotime($timeStr);
    if (!$timestamp) return false;
    $time = date('h:i', $timestamp);
    $ampm = date('a', $timestamp);
    $ampmAr = ($ampm == 'am') ? 'ص' : 'م';
    return "$time $ampmAr";
}

function cleanStatus($status) {
    if (strpos($status, 'لم تبدأ') !== false) return 'لم تبدأ';
    if (strpos($status, 'انتهت') !== false) return 'انتهت';
    return $status;
}

// =================================================================
// ★★★ دالة إصلاح ما تم حقنه سابقاً (مع إضافة العداد) ★★★
// =================================================================
function fixPreviousInjections($db) {
    echo "<h3>🛠️ Running Fix for Previously Injected Matches...</h3>";
    
    $sql = "SELECT league_id, week_name, matches_json 
            FROM " . DB_PREFIX . "league_fixture_weeks 
            WHERE matches_json LIKE '%\"is_injected\":true%' 
               OR matches_json LIKE '%\"is_injected\": true%'";
               
    $stmt = $db->query($sql);
    $rows = $stmt->fetchAll();
    $fixedCount = 0;

    foreach ($rows as $row) {
        $jsonArr = json_decode($row['matches_json'], true);
        $modified = false;

        foreach ($jsonArr as &$match) {
            if (isset($match['is_injected']) && $match['is_injected'] === true) {
                
                $mId = $match['btolat_id'];
                $sqlFresh = "SELECT time, date, status, timer FROM " . DB_PREFIX . "matches WHERE match_id = ? LIMIT 1";
                $stmtFresh = $db->prepare($sqlFresh);
                $stmtFresh->execute([$mId]);
                $freshData = $stmtFresh->fetch();

                if ($freshData) {
                    $newDateText = getArabicDate($freshData['date']);
                    
                    $newTimeDisplay = '';
                    $timerValue = null; // متغير للعداد
                    $cleanStat = cleanStatus($freshData['status']);

                    if (strpos($freshData['status'], 'مباشر') !== false || strpos($freshData['status'], 'شوط') !== false) {
                        $newTimeDisplay = !empty($freshData['timer']) ? $freshData['timer'] : 'مباشر';
                        $timerValue = $newTimeDisplay; // حفظ العداد
                    } else {
                        $formattedTime = formatArabicTime($freshData['time']);
                        $newTimeDisplay = $formattedTime ? $formattedTime : $cleanStat;
                    }

                    // تحديث القيم
                    $match['date_text'] = $newDateText;
                    $match['time'] = $newTimeDisplay;
                    $match['status'] = $cleanStat;
                    $match['timer'] = $timerValue; // ★ إضافة حقل العداد ★
                    
                    $modified = true;
                    $fixedCount++;
                }
            }
        }
        unset($match);

        if ($modified) {
            $newJson = json_encode($jsonArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            $updateStmt = $db->prepare("UPDATE " . DB_PREFIX . "league_fixture_weeks 
                                        SET matches_json = ? 
                                        WHERE league_id = ? AND week_name = ?");
            $updateStmt->execute([$newJson, $row['league_id'], $row['week_name']]);
        }
    }
    echo "<p style='color:blue'><strong>✅ Done: Fixed time/status/timer for $fixedCount matches.</strong></p><hr>";
}

// =================================================================
// ★★★ المحرك الرئيسي ★★★
// =================================================================
function syncLiveMatchesInternal($db) {
    echo "<h3>🔄 Starting Super Intelligent Sync (Anti-Duplicate + Timer Support)...</h3>";
    
    $sqlLive = "SELECT m.match_id, m.score, m.status, m.time, m.timer, m.team1, m.team2, m.league, m.date, m.team1_logo, m.team2_logo 
                FROM " . DB_PREFIX . "matches m
                WHERE m.date = CURDATE()
                ORDER BY m.match_id DESC";
    
    $stmt = $db->query($sqlLive);
    $rawMatches = $stmt->fetchAll();

    if (empty($rawMatches)) { echo "<p>No matches found in 'matches' table for today.</p>"; return; }

    $uniqueMatches = [];
    $seenMatches = [];
    foreach ($rawMatches as $match) {
        $t1 = normalizeArabicText($match['team1']);
        $t2 = normalizeArabicText($match['team2']);
        $teams = [$t1, $t2]; sort($teams);
        $matchKey = $teams[0] . "|" . $teams[1];
        if (!isset($seenMatches[$matchKey])) {
            $seenMatches[$matchKey] = true;
            $uniqueMatches[] = $match;
        }
    }

    echo "<p>Processing " . count($uniqueMatches) . " unique matches.</p>";

    $updatesCount = 0; $repairCount = 0; $injectedCount = 0;

    foreach ($uniqueMatches as $match) {
        $mId = $match['match_id'];
        $newScore = $match['score'];
        $rawStatus = $match['status'];
        $newStatus = cleanStatus($rawStatus);
        
        $newTimer = null; // متغير العداد

        if (strpos($rawStatus, 'مباشر') !== false || strpos($rawStatus, 'شوط') !== false) {
            $newTimer = !empty($match['timer']) ? $match['timer'] : 'مباشر';
            $newDisplayTime = $newTimer;
        } else {
            $formatted = formatArabicTime($match['time']); 
            $newDisplayTime = $formatted ? $formatted : $newStatus;
        }

        $team1Live = normalizeArabicText($match['team1']);
        $team2Live = normalizeArabicText($match['team2']);
        $leagueNameRaw = $match['league'];
        
        $foundAndUpdated = false;

        // 1. المحاولة بالـ ID
        $sqlFindById = "SELECT league_id, week_name, matches_json FROM " . DB_PREFIX . "league_fixture_weeks WHERE matches_json LIKE '%$mId%' LIMIT 1";
        $row = $db->query($sqlFindById)->fetch();

        if ($row) {
            if (updateJsonRow($db, $row, $mId, $newScore, $newStatus, $newDisplayTime, $newTimer)) {
                echo "<p style='color:green'>✅ Synced via ID: $mId</p>"; $updatesCount++;
            }
            $foundAndUpdated = true;
        } 
        
        // 2. المحاولة بالأسماء
        if (!$foundAndUpdated) {
            $sqlGetLeagueId = "SELECT league_id FROM " . DB_PREFIX . "leagues_list WHERE league_name LIKE ? OR league_name = ? LIMIT 1";
            $stmtLg = $db->prepare($sqlGetLeagueId);
            $stmtLg->execute(["%{$leagueNameRaw}%", $leagueNameRaw]);
            $leagueRow = $stmtLg->fetch();

            if ($leagueRow) {
                $targetLeagueId = $leagueRow['league_id'];
                $sqlFindByLeague = "SELECT league_id, week_name, matches_json FROM " . DB_PREFIX . "league_fixture_weeks WHERE league_id = ?";
                $stmtWeeks = $db->prepare($sqlFindByLeague);
                $stmtWeeks->execute([$targetLeagueId]);
                $allWeeks = $stmtWeeks->fetchAll();

                foreach ($allWeeks as $weekRow) {
                    $jsonArr = json_decode($weekRow['matches_json'], true);
                    $jsonModified = false;
                    foreach ($jsonArr as &$jsonMatch) {
                        $jsonTeam1 = normalizeArabicText($jsonMatch['team1_name']);
                        $jsonTeam2 = normalizeArabicText($jsonMatch['team2_name']);
                        if ($jsonTeam1 == $team1Live && $jsonTeam2 == $team2Live) {
                            $oldIdFromUrl = 0;
                            if (isset($jsonMatch['details_url']) && preg_match('/\/details\/(\d+)/', $jsonMatch['details_url'], $uMatches)) $oldIdFromUrl = $uMatches[1];
                            
                            if ($oldIdFromUrl != $mId) {
                                if (isset($jsonMatch['details_url'])) $jsonMatch['details_url'] = preg_replace('/\/details\/\d+/', "/details/$mId", $jsonMatch['details_url']);
                                $jsonMatch['score'] = $newScore;
                                $jsonMatch['status'] = $newStatus;
                                $jsonMatch['time'] = $newDisplayTime;
                                $jsonMatch['timer'] = $newTimer; // ★ تحديث العداد ★
                                
                                $jsonModified = true; $repairCount++; $foundAndUpdated = true;
                                echo "<p style='color:blue; font-weight:bold'>🔧 REPAIRED: New ID: $mId</p>";
                            } else {
                                if ($jsonMatch['score'] != $newScore || $jsonMatch['status'] != $newStatus || $jsonMatch['time'] != $newDisplayTime || ($jsonMatch['timer'] ?? '') != $newTimer) {
                                    $jsonMatch['score'] = $newScore; $jsonMatch['status'] = $newStatus; $jsonMatch['time'] = $newDisplayTime;
                                    $jsonMatch['timer'] = $newTimer; // ★ تحديث العداد ★
                                    $jsonModified = true; $updatesCount++;
                                }
                                $foundAndUpdated = true;
                            }
                        }
                    }
                    unset($jsonMatch);
                    if ($jsonModified) {
                        $newJson = json_encode($jsonArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                        $updateStmt = $db->prepare("UPDATE " . DB_PREFIX . "league_fixture_weeks SET matches_json = ? WHERE league_id = ? AND week_name = ?");
                        $updateStmt->execute([$newJson, $weekRow['league_id'], $weekRow['week_name']]);
                        break;
                    }
                }

                // 3. الحقن (INJECTION)
                if (!$foundAndUpdated) {
                    $match['display_time'] = $newDisplayTime; 
                    $match['clean_status'] = $newStatus;
                    $match['clean_timer'] = $newTimer; // تمرير العداد للحقن
                    
                    $injected = injectNewMatchToSchedule($db, $targetLeagueId, $match);
                    if ($injected) {
                        echo "<p style='color:purple; font-weight:bold'>💉 INJECTED: ({$match['team1']} vs {$match['team2']}) Time: $newDisplayTime</p>";
                        $injectedCount++;
                    }
                }
            }
        }
    }
    
    echo "<p><strong>Stats: $updatesCount Updates | $repairCount Repairs | $injectedCount Injections</strong></p><hr>";
}

// =================================================================
// ★★★ دالة الحقن (مع حقل العداد timer) ★★★
// =================================================================
function injectNewMatchToSchedule($db, $leagueId, $matchData) {
    $sqlGetWeek = "SELECT week_name, matches_json FROM " . DB_PREFIX . "league_fixture_weeks WHERE league_id = ? ORDER BY last_scraped DESC LIMIT 1";
    $stmt = $db->prepare($sqlGetWeek);
    $stmt->execute([$leagueId]);
    $weekRow = $stmt->fetch();

    if (!$weekRow) return false;

    $jsonArr = json_decode($weekRow['matches_json'], true);
    if (!is_array($jsonArr)) $jsonArr = [];

    // التحقق من عدم التكرار (ID والأسماء)
    $newTeam1 = normalizeArabicText($matchData['team1']);
    $newTeam2 = normalizeArabicText($matchData['team2']);

    foreach ($jsonArr as &$existing) {
        if (isset($existing['btolat_id']) && $existing['btolat_id'] == $matchData['match_id']) return false;
        
        // فحص الأسماء لدمج التكرار بدلاً من الإضافة
        $exTeam1 = normalizeArabicText($existing['team1_name']);
        $exTeam2 = normalizeArabicText($existing['team2_name']);
        
        if ($exTeam1 == $newTeam1 && $exTeam2 == $newTeam2) {
            // تحديث الموجودة بدلاً من إضافة جديدة
            $existing['btolat_id'] = (int)$matchData['match_id'];
            $existing['details_url'] = "https://www.btolat.com/matches/details/" . $matchData['match_id'];
            $existing['score'] = $matchData['score'];
            $existing['status'] = $matchData['clean_status'];
            $existing['time'] = $matchData['display_time'];
            $existing['timer'] = $matchData['clean_timer']; // ★ إضافة العداد ★
            $existing['is_injected'] = true;
            
            $newJson = json_encode($jsonArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            $updateStmt = $db->prepare("UPDATE " . DB_PREFIX . "league_fixture_weeks SET matches_json = ? WHERE league_id = ? AND week_name = ?");
            $updateStmt->execute([$newJson, $leagueId, $weekRow['week_name']]);
            return true;
        }
    }
    unset($existing);

    // حقن جديد
    $newMatchObj = [
        'btolat_id' => (int)$matchData['match_id'],
        'date_text' => getArabicDate($matchData['date']), 
        'time' => $matchData['display_time'], 
        'timer' => $matchData['clean_timer'], // ★ حقل العداد الجديد ★
        'status' => $matchData['clean_status'], 
        'score' => $matchData['score'],
        'team1_name' => $matchData['team1'],
        'team1_logo' => $matchData['team1_logo'],
        'team1_btolat_id' => 0,
        'team2_name' => $matchData['team2'],
        'team2_logo' => $matchData['team2_logo'],
        'team2_btolat_id' => 0,
        'details_url' => "https://www.btolat.com/matches/details/" . $matchData['match_id'],
        'is_injected' => true
    ];

    $jsonArr[] = $newMatchObj;
    $newJson = json_encode($jsonArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $updateStmt = $db->prepare("UPDATE " . DB_PREFIX . "league_fixture_weeks SET matches_json = ? WHERE league_id = ? AND week_name = ?");
    return $updateStmt->execute([$newJson, $leagueId, $weekRow['week_name']]);
}

function updateJsonRow($db, $row, $mId, $newScore, $newStatus, $newTime, $newTimer) {
    $targetLeagueId = $row['league_id'];
    $targetWeekName = $row['week_name'];
    $jsonArr = json_decode($row['matches_json'], true);
    $updated = false;
    foreach ($jsonArr as &$jsonMatch) {
        if (isset($jsonMatch['details_url']) && strpos($jsonMatch['details_url'], (string)$mId) !== false) {
            if ($jsonMatch['score'] != $newScore || $jsonMatch['status'] != $newStatus || $jsonMatch['time'] != $newTime || ($jsonMatch['timer'] ?? '') != $newTimer) {
                $jsonMatch['score'] = $newScore;
                $jsonMatch['status'] = $newStatus;
                $jsonMatch['time'] = $newTime; 
                $jsonMatch['timer'] = $newTimer; // ★ تحديث العداد ★
                $updated = true;
            }
        }
    }
    unset($jsonMatch);
    if ($updated) {
        $newJson = json_encode($jsonArr, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $updateStmt = $db->prepare("UPDATE " . DB_PREFIX . "league_fixture_weeks SET matches_json = ? WHERE league_id = ? AND week_name = ?");
        $updateStmt->execute([$newJson, $targetLeagueId, $targetWeekName]);
        return true;
    }
    return false;
}

// --- دوال المعالجة (كما هي) ---
function extractTeamIdFromHref($href) {
    if ($href && preg_match('/\/team\/(\d+)\//', $href, $matches)) return (int)$matches[1];
    return null;
}

function processHtmlForMatches($htmlObject, $weekName, $leagueId, $stmtInsert) {
    // ... (نفس كود processHtmlForMatches السابق تماماً) ...
    // اختصاراً للمساحة، لكن تأكد من وجوده في ملفك
    // الكود لم يتغير هنا
    $matches_for_this_week = [];
    $legTitle = $htmlObject->find('h3.legTitle', 0);
    if ($legTitle) $weekName = trim($legTitle->plaintext);
    $matchTable = $htmlObject->find('div.matchtableX', 0);
    if (!$matchTable) return false;
    $currentDate = null;
    foreach ($matchTable->find('div.matchDate') as $dateDiv) {
        $h4 = $dateDiv->find('h4', 0);
        if ($h4) $currentDate = trim($h4->plaintext);
        $ulElement = $dateDiv->next_sibling();
        if ($ulElement && $ulElement->tag == 'ul') {
            foreach ($ulElement->find('li.fullMatchBox') as $matchLi) {
                $matchBtolatId = $matchLi->id ? (int)$matchLi->id : null;
                if (!$matchBtolatId) continue;
                $matchData = [
                    'btolat_id' => $matchBtolatId, 
                    'date_text' => $currentDate,
                    'time' => null, 'status' => null, 'score' => null,
                    'team1_name' => '', 'team1_logo' => '', 'team1_btolat_id' => null,
                    'team2_name' => '', 'team2_logo' => '', 'team2_btolat_id' => null,
                    'details_url' => null
                ];
                $t1 = $matchLi->find('a.team1', 0);
                if ($t1) {
                    $matchData['team1_name'] = trim($t1->plaintext);
                    $img = $t1->find('img', 0);
                    $matchData['team1_logo'] = $img ? ($img->{'data-original'} ?? $img->src) : null;
                    $matchData['team1_btolat_id'] = extractTeamIdFromHref($t1->href);
                }
                $t2 = $matchLi->find('a.team2', 0);
                if ($t2) {
                    $matchData['team2_name'] = trim($t2->plaintext);
                    $img = $t2->find('img', 0);
                    $matchData['team2_logo'] = $img ? ($img->{'data-original'} ?? $img->src) : null;
                    $matchData['team2_btolat_id'] = extractTeamIdFromHref($t2->href);
                }
                $stat = $matchLi->find('a.stat', 0);
                if ($stat) {
                    $matchData['details_url'] = "https://www.btolat.com" . $stat->href; 
                    $timeEl = $stat->find('span.matchDate span', 0);
                    if ($timeEl) $matchData['time'] = trim(html_entity_decode($timeEl->plaintext, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
                    $statusEl = $stat->find('div.status', 0);
                    if ($statusEl) $matchData['status'] = trim(html_entity_decode($statusEl->plaintext, ENT_QUOTES | ENT_HTML5, 'UTF-8'));
                    $g1 = $stat->find('div.team1G', 0);
                    $g2 = $stat->find('div.team2G', 0);
                    if ($g1 && $g2) $matchData['score'] = trim($g1->plaintext) . ' - ' . trim($g2->plaintext);
                }
                if ($matchData['team1_logo'] && strpos($matchData['team1_logo'], '//') === 0) $matchData['team1_logo'] = 'https:' . $matchData['team1_logo'];
                if ($matchData['team2_logo'] && strpos($matchData['team2_logo'], '//') === 0) $matchData['team2_logo'] = 'https:' . $matchData['team2_logo'];
                $matches_for_this_week[] = $matchData;
            }
        }
    }
    if (!empty($matches_for_this_week)) {
        $json = json_encode($matches_for_this_week, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $stmtInsert->execute([':league_id' => $leagueId, ':week_name' => $weekName, ':matches_json' => $json]);
        return true;
    }
    return false;
}

function scrapeCurrentWeekOnly($leagueId, $leagueSlug, $stmtInsert) {
    $url = "https://www.btolat.com/league/fixtures/{$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;

    $selectedWeekName = 'Current Week';
    $select = $html->find('select#weekId', 0);
    if ($select) {
        foreach ($select->find('option') as $opt) {
            if ($opt->selected) {
                $selectedWeekName = trim($opt->plaintext);
                break;
            }
        }
    }
    $result = processHtmlForMatches($html, $selectedWeekName, $leagueId, $stmtInsert);
    $html->clear(); unset($html);
    return $result;
}

function scrapeAllWeeks($leagueId, $leagueSlug, $stmtInsert) {
    $baseUrl = "https://www.btolat.com/league/fixtures/{$leagueId}/{$leagueSlug}";
    $content = fetchPageContent($baseUrl);
    if (!$content) return 0;
    $html = str_get_html($content);
    if (!$html) return 0;

    $weeksMap = [];
    $select = $html->find('select#weekId', 0);
    if ($select) {
        foreach ($select->find('option') as $opt) {
            $val = trim($opt->value);
            if ($val && $val != '0') $weeksMap[$val] = trim($opt->plaintext);
        }
    }
    processHtmlForMatches($html, $weeksMap[array_key_first($weeksMap)] ?? 'Current', $leagueId, $stmtInsert);
    $html->clear(); unset($html);
    $count = 1;
    foreach ($weeksMap as $wId => $wName) {
        $url = $baseUrl . "?weekId=" . $wId;
        $subContent = fetchPageContent($url);
        if ($subContent) {
            $subHtml = str_get_html($subContent);
            if ($subHtml) {
                processHtmlForMatches($subHtml, $wName, $leagueId, $stmtInsert);
                $subHtml->clear(); unset($subHtml);
                $count++;
            }
        }
        usleep(250000); 
    }
    return $count;
}

// =================================================================
// ★★★ المحرك الرئيسي ★★★
// =================================================================
function runSmartSystem($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_fixture_weeks (league_id, week_name, matches_json) VALUES (:league_id, :week_name, :matches_json) ON DUPLICATE KEY UPDATE matches_json=VALUES(matches_json), last_scraped=CURRENT_TIMESTAMP");

    // ★★★ شغل هذا السطر مرة واحدة ثم قم بتعليقه ★★★
    fixPreviousInjections($db); 

    // === المسار 1: المزامنة الذكية ===
    if ($mode == 'live' || $mode == 'auto') {
        syncLiveMatchesInternal($db); 
    }

    // === المسار 2: التحديث الخارجي ===
    if ($mode == 'live' || $mode == 'auto') {
        echo "<h2>🚀 Mode: External Strict Smart Fetch</h2>";
        $sqlSmart = "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 m.status NOT LIKE '%مؤجلة%'
                     AND l.league_id IN ($idsString)";
        $stmt = $db->query($sqlSmart);
        $leagues = $stmt->fetchAll();
        if (empty($leagues)) {
            echo "<p style='color:orange'>No active matches found for external fetch.</p>";
        } else {
            foreach ($leagues as $lg) {
                $success = scrapeCurrentWeekOnly($lg['league_id'], $lg['league_slug'], $stmtInsert);
                if ($success) {
                    echo "<p style='color:green'>✅ External Fetch: Updated [{$lg['league_slug']}]</p>";
                    $db->query("UPDATE " . DB_PREFIX . "leagues_list SET last_scraped = NOW() WHERE league_id = {$lg['league_id']}");
                }
            }
        }
    }

    // === المسار 3: الأرشيف الكامل ===
    if ($mode == 'full' || $mode == 'auto') {
        echo "<h2>📚 Mode: Full Archive</h2>";
        $sqlFull = "SELECT league_id, league_slug FROM " . DB_PREFIX . "leagues_list WHERE league_id IN ($idsString) AND (last_full_scan < (NOW() - INTERVAL 24 HOUR) OR last_full_scan IS NULL) ORDER BY last_full_scan ASC LIMIT 2"; 
        $stmt = $db->query($sqlFull);
        $leagues = $stmt->fetchAll();
        if (empty($leagues)) {
             $checkCount = $db->query("SELECT COUNT(*) FROM " . DB_PREFIX . "leagues_list WHERE league_id IN ($idsString)")->fetchColumn();
             if ($checkCount == 0) echo "<p style='color:red;'>Warning: Database empty. Run leagues_scraper.php first.</p>";
             else echo "<p>All target leagues fully archived.</p>";
        }
        foreach ($leagues as $lg) {
            echo "<p>Full Scan: {$lg['league_slug']}...</p>";
            scrapeAllWeeks($lg['league_id'], $lg['league_slug'], $stmtInsert);
            $db->query("UPDATE " . DB_PREFIX . "leagues_list SET last_full_scan = NOW(), 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']; }

runSmartSystem($mode, $TARGET_LEAGUES_IDS);
?>