<?php
// league_top_scorers_scraper.php (v2.0 - Fix Character Encoding)

// --- إعدادات الأخطاء والوقت ---
ini_set('max_execution_time', 600); // 10 دقائق
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
ini_set('log_errors', 1);
$log_file = __DIR__ . '/scraper_errors.log';
ini_set('error_log', $log_file);

// --- دالة التنظيف والتعامل مع الحروف الخاصة (المركزية) ---
// هذه الدالة تحول الرموز مثل &#244; إلى ô
if (!function_exists('clean_scraped_text')) {
    function clean_scraped_text($text) {
        if ($text === null || $text === '') return '';
        // 1. إزالة المسافات الزائدة
        $text = trim($text);
        // 2. فك تشفير رموز HTML (لحل مشكلة الحروف اللاتينية والعربية)
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        return $text;
    }
}

@error_log("--- [Top Scorers Scraper v2.0] Starting execution ---");

// --- تضمين الملفات المطلوبة ---
if (!file_exists(__DIR__ . '/config.php')) {
    $errorMsg = "[Top Scorers Scraper] FATAL ERROR: config.php not found in " . __DIR__;
    error_log($errorMsg); die($errorMsg);
}
require __DIR__ . '/config.php';

if (!file_exists(__DIR__ . '/simple_html_dom.php')) {
    $errorMsg = "[Top Scorers Scraper] FATAL ERROR: simple_html_dom.php not found in " . __DIR__;
    error_log($errorMsg); die($errorMsg);
}
require __DIR__ . '/simple_html_dom.php';

// --- دوال الاتصال وجلب المحتوى ---
function connectToDB() {
     if (!defined('DB_HOST') || !defined('DB_NAME') || !defined('DB_USER') || !defined('DB_PASS')) {
        error_log("[Top Scorers Scraper] FATAL DB Connection Error: Database constants not defined."); return null;
    }
    $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);
         error_log("[Top Scorers Scraper] Database connection successful.");
         return $db;
    } catch (PDOException $e) {
         error_log("[Top Scorers Scraper] FATAL DB Connection Error: " . $e->getMessage()); return null;
    }
}

function fetchPageContent($url) {
    error_log("[Top Scorers Scraper] Fetching URL: " . $url);
    $ch = curl_init();
    if ($ch === false) { error_log("cURL Error: Failed to initialize for URL: " . $url); return null; }
    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);
    if ($htmlContent === false) {
        error_log("cURL Error executing fetch for {$url}: " . $curlError . " (HTTP Code: {$httpCode})");
        curl_close($ch); return null;
    }
    curl_close($ch);
    if ($httpCode != 200) {
        error_log("[Top Scorers Scraper] Failed HTTP request for {$url}. Code: {$httpCode}."); return null;
    }
    error_log("[Top Scorers Scraper] Successfully fetched URL: " . $url . " (HTTP " . $httpCode . ")");
    return $htmlContent;
}

/**
 * دالة استخراج ID من رابط href
 */
function extractIdFromHref($href, $pattern) {
    if ($href && preg_match($pattern, $href, $matches)) {
        return (int)$matches[1];
    }
    return null;
}

/**
 * سحب وتخزين قائمة الهدافين لبطولة واحدة (v2.0 - مع إصلاح الترميز)
 */
function scrapeAndStoreLeagueTopScorers($leagueId, $leagueSlug, $db, $stmtInsert) {
    $url = "https://www.btolat.com/league/topscores/{$leagueId}/{$leagueSlug}";
    error_log("--- [TS Scraper v2.0] Processing League {$leagueId} ({$leagueSlug}) ---");
    
    $htmlContent = fetchPageContent($url);
    if (!$htmlContent) {
        error_log("[TS L{$leagueId}] Failed fetch. Skip.");
        return false;
    }
    if (!function_exists('str_get_html')) {
        error_log("[TS L{$leagueId}] FATAL: simple_html_dom library not loaded correctly.");
        return false;
    }
    
    // محاولة قراءة HTML مع تحديد الترميز UTF-8
    $html = str_get_html(mb_convert_encoding($htmlContent, 'HTML-ENTITIES', 'UTF-8'));
    
    if (!$html || !is_object($html)) {
        error_log("[TS L{$leagueId}] Failed parse. Skip.");
        if (isset($html)) { unset($html); }
        return false;
    }

    $topScorers = [];
    $table = $html->find('table.leagueTable.topScores', 0);

    if ($table && is_object($table)) {
        error_log("[TS L{$leagueId}] Found top scores table.");
        $rowIndex = 0;
        $rows = $table->find('tbody tr');

        if (empty($rows)) {
             error_log("[TS L{$leagueId}] No <tr> elements found within tbody.");
        }

        foreach ($rows as $row) {
            $rowIndex++;
            // Skip header
            if ($row->find('th.groupTitle', 0)) {
                 continue;
            }

            $cols = $row->find('td');

            if (!empty($cols) && count($cols) >= 4) {
                try {
                     $playerData = [
                        'rank' => null, 'player_name' => null, 'player_logo' => null, 'player_btolat_id' => null,
                        'team_name' => null, 'team_logo' => null, 'team_btolat_id' => null, 'goals' => null
                    ];

                    // --- Rank (Cell 0) ---
                    $rankElement = $cols[0]->find('b', 0);
                    // ★ استخدام clean_scraped_text
                    $playerData['rank'] = $rankElement ? clean_scraped_text($rankElement->plaintext) : clean_scraped_text($cols[0]->plaintext);

                    // --- Player (Cell 1) ---
                    $playerLink = $cols[1]->find('a', 0);
                    if ($playerLink) {
                        $playerNameElement = $playerLink->find('b', 0);
                        // ★ استخدام clean_scraped_text (هام جداً هنا للاسم)
                        $playerData['player_name'] = $playerNameElement ? clean_scraped_text($playerNameElement->plaintext) : clean_scraped_text($playerLink->plaintext);
                        
                        $playerData['player_btolat_id'] = extractIdFromHref($playerLink->href, '/\/player\/(\d+)\//');
                        $playerImg = $playerLink->find('img', 0);
                        if ($playerImg) {
                            $logoSrc = $playerImg->src ?? null;
                            if ($logoSrc) {
                                $playerData['player_logo'] = (strpos($logoSrc, '//') === 0) ? 'https:' . $logoSrc : $logoSrc;
                            }
                        }
                    }

                    // --- Team (Cell 2) ---
                    $teamLink = $cols[2]->find('a', 0);
                    if ($teamLink) {
                        $teamNameElement = $teamLink->find('b', 0);
                        // ★ استخدام clean_scraped_text
                        $playerData['team_name'] = $teamNameElement ? clean_scraped_text($teamNameElement->plaintext) : clean_scraped_text($teamLink->plaintext);
                        
                        $playerData['team_btolat_id'] = extractIdFromHref($teamLink->href, '/\/team\/(\d+)\//');
                        $teamImg = $teamLink->find('img', 0);
                        if ($teamImg) {
                            $logoSrc = $teamImg->src ?? null;
                            if ($logoSrc) {
                                $playerData['team_logo'] = (strpos($logoSrc, '//') === 0) ? 'https:' . $logoSrc : $logoSrc;
                            }
                        }
                    }

                    // --- Goals (Cell 3) ---
                    $goalsElement = $cols[3]->find('div.color span', 0);
                    // ★ استخدام clean_scraped_text
                    $playerData['goals'] = $goalsElement ? clean_scraped_text($goalsElement->plaintext) : null;

                    // --- Final check and add ---
                    if (!empty($playerData['player_name']) && is_numeric($playerData['rank']) && is_numeric($playerData['goals'])) {
                        $topScorers[] = $playerData;
                    } else {
                        // Log skip silently
                    }

                } catch (Throwable $t) {
                     error_log("[TS L{$leagueId} R{$rowIndex}] EXCEPTION processing row: " . $t->getMessage());
                     continue;
                }
            }
        }

        error_log("[TS L{$leagueId}] Finished processing rows. Found " . count($topScorers) . " valid players.");

    } else {
        error_log("[TS L{$leagueId}] No top scores table found.");
    }

    // --- تخزين النتائج ---
    // استخدام JSON_UNESCAPED_UNICODE ضروري لحفظ الحروف العربية واللاتينية كما هي
    $topScorersJson = json_encode($topScorers, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $jsonError = json_last_error();

    $success = false;
    if ($jsonError === JSON_ERROR_NONE) {
        try {
            $stmtInsert->execute([':league_id' => $leagueId, ':top_scorers_json' => $topScorersJson]);
            error_log("[TS L{$leagueId}] DB store success.");
            $success = true;
        } catch (PDOException $e) {
            error_log("[TS L{$leagueId}] DB Error storing top scorers: " . $e->getMessage());
        }
    } else {
         error_log("[TS L{$leagueId}] JSON Encode Error: " . json_last_error_msg());
    }

    if (isset($html) && is_object($html)) {
        $html->clear();
        unset($html);
    }
    return $success;
}


/**
 * الدالة الرئيسية لتشغيل سكربت جلب الهدافين
 */
function runTopScorersScraper() {
    error_log("--- Starting Top Scorers Scraper Run [v2.0] ---");
    echo "<h1>Starting Top Scorers Scraper v2.0...</h1>";

    $db = connectToDB();
    if (!$db) { echo "<p style='color:red;'>FATAL DB Error. Check logs.</p>"; error_log("[Top Scorers Scraper] Stopped: DB connection fail."); exit; }

    $leaguesListTable = DB_PREFIX . 'leagues_list';
    $topScorersTable = DB_PREFIX . 'league_top_scorers';
    $leaguesProcessed = 0; $leaguesUpdated = 0;

    $important_league_ids = [
        1193, 1368, 1204, 1399, 1229, 1269, 1221, 1313, 2024, 1440,
        1356, 1420, 1425, 1289, 1059, 1005, 1513, 1515, 1001, 1635,
        1022, 1007, 1039, 18854
    ];

    if (empty($important_league_ids)) { $msg="Error: Important leagues list empty."; error_log($msg); echo "<p style='color:red;'>{$msg}</p>"; exit; }

    try {
        $placeholders = implode(',', array_fill(0, count($important_league_ids), '?'));
        $sqlSelectLeagues = "SELECT league_id, league_slug FROM {$leaguesListTable} WHERE league_id IN ({$placeholders})";
        $stmtLeagues = $db->prepare($sqlSelectLeagues);
        $stmtLeagues->execute($important_league_ids);
        $leaguesToUpdate = $stmtLeagues->fetchAll();
        $totalLeagues = count($leaguesToUpdate);

        error_log("[Top Scorers Scraper] Found {$totalLeagues} important leagues.");
        echo "<p>Found {$totalLeagues} important leagues to process.</p>";

         $sqlInsert = "INSERT INTO {$topScorersTable} ( league_id, top_scorers_json ) VALUES ( :league_id, :top_scorers_json ) ON DUPLICATE KEY UPDATE top_scorers_json = VALUES(top_scorers_json), last_scraped = CURRENT_TIMESTAMP";
         $stmtInsert = $db->prepare($sqlInsert);

        foreach ($leaguesToUpdate as $index => $leagueInfo) {
            $leagueId = $leagueInfo['league_id']; $leagueSlug = $leagueInfo['league_slug'];
            echo "<p>Processing " . ($index + 1) . "/{$totalLeagues}: {$leagueSlug}... ";
            flush(); ob_flush();

            $success = scrapeAndStoreLeagueTopScorers($leagueId, $leagueSlug, $db, $stmtInsert);

            if ($success) { echo "<span style='color:green;'>OK.</span></p>"; $leaguesUpdated++; }
            else { echo "<span style='color:orange;'>Failed/Empty.</span></p>"; }
            $leaguesProcessed++;
            usleep(400000); 
        }

        error_log("[Top Scorers Scraper] Finished: {$leaguesProcessed} leagues processed.");
        echo "<p>Finished processing.</p>";

    } catch (Throwable $t) {
        $errorMsg = "[Top Scorers Scraper] FATAL Error: " . $t->getMessage();
        error_log($errorMsg);
        echo "<p style='color:red;'>FATAL Error. Check logs.</p>";
     }

    error_log("--- Top Scorers Scraper Run Finished ---");
}

if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) {
    runTopScorersScraper();
}
?>