<?php
// leagues_scraper.php (v4.0 - Only scrapes leagues list)

ini_set('max_execution_time', 120); // دقيقتان كافية الآن
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/scraper_errors.log');

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

// --- دوال الاتصال وجلب المحتوى ---
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,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    try {
         $db = new PDO($dsn, DB_USER, DB_PASS, $options);
         return $db;
    } catch (PDOException $e) {
         error_log("FATAL DB Connection 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/91.0.4472.124 Safari/537.36');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 45); 
    $htmlContent = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    if ($httpCode != 200 || !$htmlContent) {
         $errorMsg = "[Leagues List Scraper] Failed to retrieve HTML from {$url}. HTTP Code: {$httpCode}.";
         if ($curlError) { $errorMsg .= " cURL Error: " . $curlError; }
         error_log($errorMsg);
        return null;
    }
    return $htmlContent;
}

/**
 * الدالة الرئيسية لتحديث قائمة البطولات فقط
 */
function updateLeaguesList() {
    error_log("--- Starting Leagues List Update Run ---");
    echo "<h1>Updating Leagues List...</h1>";

    $db = connectToDB();
    if (!$db) {
        die("FATAL: Could not connect to DB. Check scraper_errors.log");
    }

    $leaguesListTable = DB_PREFIX . 'leagues_list';
    $leaguesCount = 0;

    try {
        $targetUrl = "https://www.btolat.com/leagues";
        $htmlContent = fetchPageContent($targetUrl);
        if ($htmlContent) {
            $html = str_get_html($htmlContent);
            if ($html) {
                // تم تصحيح السطر التالي بإزالة الشوائب
                $leaguesFound = $html->find('a.leagueBox.col'); 
                
                if (!empty($leaguesFound)) {
                    $stmt = $db->prepare("
                        INSERT INTO {$leaguesListTable} (league_id, league_name, league_slug, league_url, league_logo)
                        VALUES (:league_id, :league_name, :league_slug, :league_url, :league_logo)
                        ON DUPLICATE KEY UPDATE
                            league_name = VALUES(league_name),
                            league_slug = VALUES(league_slug),
                            league_url = VALUES(league_url),
                            league_logo = VALUES(league_logo),
                            last_scraped = CURRENT_TIMESTAMP
                    ");

                     foreach ($leaguesFound as $league) {
                        // تم تصحيح السطر التالي
                        $href = $league->href; 
                        
                        if (preg_match('/\/league\/(\d+)\/([^\/]+)/', $href, $matches)) {
                            $leagueId = (int)$matches[1];
                            $leagueSlug = $matches[2];
                            $leagueUrl = "https://www.btolat.com" . $href;
                            
                            // تم تصحيح الأسطر التالية
                            $nameElement = $league->find('h3', 0);
                            $leagueName = $nameElement ? trim($nameElement->plaintext) : 'Unknown League';
                            
                            $logoElement = $league->find('img', 0); 
                            $leagueLogo = $logoElement ? $logoElement->src : null;
                            
                            if ($leagueLogo && substr($leagueLogo, 0, 2) === '//') { $leagueLogo = 'https:' . $leagueLogo; }

                             try {
                                $stmt->bindParam(':league_id', $leagueId, PDO::PARAM_INT);
                                $stmt->bindParam(':league_name', $leagueName, PDO::PARAM_STR);
                                $stmt->bindParam(':league_slug', $leagueSlug, PDO::PARAM_STR);
                                $stmt->bindParam(':league_url', $leagueUrl, PDO::PARAM_STR);
                                $stmt->bindParam(':league_logo', $leagueLogo, PDO::PARAM_STR);
                                $stmt->execute();
                                $leaguesCount++;
                             } catch (PDOException $e) { error_log("[Leagues List Scraper] Failed to insert/update league ID {$leagueId}: " . $e->getMessage()); }
                        } else { error_log("[Leagues List Scraper] Could not parse league ID/slug from href: " . $href); }
                    } // end foreach league
                    error_log("[Leagues List Scraper] OK: Leagues list updated/inserted: {$leaguesCount}");
                    echo "<p>OK: Leagues list updated/inserted: {$leaguesCount}</p>";
                } else {
                    error_log("[Leagues List Scraper] Warning: No leagues found on the main page.");
                    echo "<p>Warning: No leagues found on the main page.</p>";
                 }
                $html->clear(); unset($html);
            } else {
                error_log("[Leagues List Scraper] Error: Could not parse main leagues page HTML.");
                echo "<p style='color:red;'>Error: Could not parse main leagues page HTML.</p>";
            }
        } else {
             error_log("[Leagues List Scraper] Error: Could not fetch main leagues page.");
             echo "<p style='color:red;'>Error: Could not fetch main leagues page.</p>";
        }
    } catch (Exception $e) {
        error_log("[Leagues List Scraper] General Error during run: " . $e->getMessage());
        echo "<p style='color:red;'>General Error during leagues list update. Check scraper_errors.log</p>";
    }

    error_log("--- Leagues List Update Finished ---");
    echo "<h2>Leagues list update process completed. Check 'scraper_errors.log' for details.</h2>";
}

// --- تنفيذ التحديث ---
updateLeaguesList();

?>