<?php

// scraper.php (النسخة المتطورة - مزودة بالمحرك الذكي للحالات Smart Status Engine)

date_default_timezone_set('Africa/Cairo');

// --- دالة التنظيف والتعامل مع الحروف الخاصة ---
if (!function_exists('clean_scraped_text')) {
    function clean_scraped_text($text) {
        if ($text === null || $text === '') return '';
        $text = trim($text);
        $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
        return $text;
    }
}

// (تضمين جميع الملفات المطلوبة)
require __DIR__ . '/config.php';
require __DIR__. '/matches.php';
require __DIR__. '/lineups.php';
require __DIR__. '/events.php';
require __DIR__. '/match_stats_history.php';
require __DIR__. '/filgoal_scraper.php'; 

function log_debug($message) {
    $logFile = __DIR__ . '/filgoal_debug.log'; 
    $timestamp = date('Y-m-d H:i:s');
    @file_put_contents($logFile, "[{$timestamp}] - {$message}\n", FILE_APPEND);
}

function fetchMatchUpdatesFromAPI() {
    $url = 'https://api.btolat.com/api/matches/GetAllMatchStatus';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $data = json_decode($response, true);
        return (json_last_error() === JSON_ERROR_NONE) ? $data : null;
    }
    return null;
}

function btolat_universal_normalize($name) {
    if ($name === null) return '';
    $name = mb_strtolower(trim($name), 'UTF-8');
    $name = str_replace(['أ', 'إ', 'آ', 'ٱ'], 'ا', $name); 
    $name = str_replace('ى', 'ي', $name); 
    $name = str_replace('ة', 'ه', $name); 
    $name = str_replace('ؤ', 'و', $name);
    $name = str_replace('ئ', 'ي', $name);
    $name = str_replace('ء', '', $name); 
    $prefixes = ['نادي ', 'فريق ', 'شباب '];
    $name = str_replace($prefixes, '', $name);
    $suffixes = [' الرياضي', ' السعودي', ' المصري', ' 05', ' اف سي', ' إف سي', ' سي اف', ' اف سى'];
    $name = str_replace($suffixes, '', $name);
    $renames = [
        'غزل المحله' => 'المحله', 'الاتحاد السكندري' => 'الاتحاد',
        'مودرن سبورت' => 'فيوتشر', 'مودرن فيوتشر' => 'فيوتشر',
        'مانشستر سيتي' => 'مان سيتي', 'مانشستر يونايتد' => 'مان يونايتد',
        'توتنهام هوتسبير' => 'توتنهام', 'باريس سان جيرمان' => 'باريس',
        'أتلتيكو مدريد' => 'اتلتيكو'
    ];
    $name = str_replace(array_keys($renames), array_values($renames), $name);
    return str_replace(' ', '', $name);
}

function updateMatches() {
    @file_put_contents(__DIR__ . '/filgoal_debug.log', "--- [ " . date('Y-m-d H:i:s') . " ] --- بدء عملية Scraper الرئيسية ---\n", 0);
    
    $dates = [date('Y-m-d', strtotime('-1 day')), date('Y-m-d'), date('Y-m-d', strtotime('+1 day'))];

    try {
        $db = new PDO("mysql:host=". DB_HOST. ";dbname=". DB_NAME.";charset=utf8mb4", DB_USER, DB_PASS, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false
        ]);
    } catch (PDOException $e) {
        log_debug("[Scraper] ❌ فشل الاتصال بقاعدة البيانات: " . $e->getMessage());
        return;
    }

    $apiUpdates = fetchMatchUpdatesFromAPI();
    $updatesMap = [];
    if (is_array($apiUpdates)) {
        foreach ($apiUpdates as $update) {
            if (isset($update['ID'])) { $updatesMap[$update['ID']] = $update; }
        }
    }

    foreach ($dates as $date) {
        $filgoalDataMap = [];
        try { $filgoalDataMap = scrapeFilGoalData($date); } catch (Exception $e) {}
        
        $matches = scrapeMatches($date); 
        if (!is_array($matches) || empty($matches)) continue;

        foreach ($matches as $match) {
            if (!isset($match['match_id'])) continue;
            $matchId = $match['match_id'];

            $stadium = null; 
            $filgoalChannels = []; 
            if (!empty($filgoalDataMap)) {
                $t1_k = btolat_universal_normalize($match['team1']);
                $t2_k = btolat_universal_normalize($match['team2']);
                $lg_k = btolat_universal_normalize($match['league']);
                
                $keys = [$lg_k.'-'.$t1_k.'-'.$t2_k, $lg_k.'-'.$t2_k.'-'.$t1_k, $t1_k.'-'.$t2_k, $t2_k.'-'.$t1_k, $lg_k.'-'.$t1_k, $lg_k.'-'.$t2_k];
                foreach ($keys as $key) {
                    if (isset($filgoalDataMap[$key])) {
                        $stadium = $filgoalDataMap[$key]['stadium'];
                        $filgoalChannels = $filgoalDataMap[$key]['channels'];
                        break;
                    }
                }
            }
            
            $html_status = trim($match['status'] ?? '');
            $html_timer = trim($match['timer'] ?? '');
            $final_status = $html_status;
            $final_timer = $html_timer;

            if (isset($updatesMap[$matchId])) {
                $update = $updatesMap[$matchId];
                
                // 1. تنظيف الأهداف وحماية الصفر
                if (($match['team1_score'] ?? '') === '' && ($match['team2_score'] ?? '') === '') {
                    if (isset($update['local_goals']) && preg_match('/\d+/', $update['local_goals'], $m)) $match['team1_score'] = $m[0];
                    if (isset($update['visitor_goals']) && preg_match('/\d+/', $update['visitor_goals'], $m)) $match['team2_score'] = $m[0];
                    if (($match['team1_score'] ?? '') !== '' && ($match['team2_score'] ?? '') !== '') {
                        $match['score'] = $match['team1_score'] . ' - ' . $match['team2_score'];
                    }
                }

                // =========================================================
                // 2. المحرك الذكي الموحد للحالات (Smart Status Engine)
                // =========================================================
                $mStatusEnum = $update['MatchStatusEnum'] ?? '';
                $mStatus = $update['Mstatus'] ?? '';
                $statusDetails = $update['StatusDetailsName'] ?? '';
                $statusAr = $update['statusAr'] ?? '';
                $isLive = $update['IsLive'] ?? false;
                
                $mTimer = $update['Mtimer'] ?? null; 
                $api_timer = ($mTimer !== null && $mTimer !== '') ? ((strpos($mTimer, '+') !== false && is_numeric($update['InjectMinute'] ?? null)) ? $mTimer . $update['InjectMinute'] : $mTimer) : null;

                // تجميع كل الدلالات من الـ HTML والـ JSON في جملة واحدة للبحث فيها
                $all_text = mb_strtolower($html_status . ' ' . $html_timer . ' ' . $statusDetails . ' ' . $statusAr . ' ' . $mStatus . ' ' . $mStatusEnum, 'UTF-8');
                
                // أ. انتهت (Finished / FT)
                if (stripos($mStatusEnum, 'Finished') !== false || strtoupper($mStatus) === 'FT' || mb_strpos($all_text, 'انته') !== false) {
                    $final_status = 'انتهت';
                    $final_timer = null;
                }
                // ب. بين الشوطين (HT / استراحة)
                elseif (strtoupper($mStatus) === 'HT' || mb_strpos($all_text, 'استراح') !== false || mb_strpos($all_text, 'إستراح') !== false || mb_strpos($all_text, 'بين الشوط') !== false) {
                    $final_status = 'بين الشوطين';
                    $final_timer = null;
                }
                // ج. ركلات ترجيح
                elseif (!empty($update['IsPenalties']) || mb_strpos($all_text, 'ركلات') !== false || mb_strpos($all_text, 'ترجيح') !== false) {
                    $final_status = 'ركلات ترجيح';
                    $final_timer = null;
                }
                // د. مؤجلة / ملغاة
                elseif (stripos($mStatusEnum, 'Postponed') !== false || mb_strpos($all_text, 'تأجل') !== false) {
                    $final_status = 'تأجلت';
                    $final_timer = null;
                }
                elseif (stripos($mStatusEnum, 'Canceled') !== false || mb_strpos($all_text, 'لغي') !== false || mb_strpos($all_text, 'إلغاء') !== false) {
                    $final_status = 'إلغاء';
                    $final_timer = null;
                }
                // هـ. الأشواط والأوقات الإضافية
                elseif (mb_strpos($all_text, 'إضافي') !== false || mb_strpos($all_text, 'اضافي') !== false) {
                    if (mb_strpos($all_text, 'أول') !== false || mb_strpos($all_text, 'اول') !== false) $final_status = 'وقت إضافي أول';
                    elseif (mb_strpos($all_text, 'ثاني') !== false) $final_status = 'وقت إضافي ثاني';
                    else $final_status = 'وقت إضافي';
                    $final_timer = $api_timer ?? $html_timer;
                }
                elseif (strtoupper($mStatus) === '1H' || mb_strpos($all_text, 'شوط أول') !== false) {
                    $final_status = 'الشوط الأول';
                    $final_timer = $api_timer ?? $html_timer;
                }
                elseif (strtoupper($mStatus) === '2H' || mb_strpos($all_text, 'شوط ثاني') !== false) {
                    $final_status = 'الشوط الثاني';
                    $final_timer = $api_timer ?? $html_timer;
                }
                // و. مباشر عام
                elseif ($isLive || stripos($mStatusEnum, 'Playing') !== false || mb_strpos($all_text, 'مباشر') !== false || (!empty($api_timer) && $api_timer !== '0')) {
                    if (!empty($statusDetails) && $statusDetails !== 'مباشر') $final_status = $statusDetails;
                    elseif (!empty($statusAr) && $statusAr !== 'مباشر') $final_status = $statusAr;
                    else $final_status = 'مباشر';
                    $final_timer = $api_timer ?? $html_timer;
                }
                // ز. لم تبدأ
                else {
                    if (stripos($mStatusEnum, 'NotStarted') !== false || mb_strpos($all_text, 'لم تبدأ') !== false) {
                        $final_status = 'لم تبدأ';
                    } else {
                        $final_status = !empty($statusDetails) ? $statusDetails : (!empty($html_status) ? $html_status : 'لم تبدأ');
                    }
                    $final_timer = null;
                }
                // =========================================================

            } else {
                // حماية للحالات التي لا تملك JSON
                $all_text = mb_strtolower($html_status . ' ' . $html_timer, 'UTF-8');
                if (mb_strpos($all_text, 'انته') !== false) { $final_status = 'انتهت'; $final_timer = null; }
                elseif (mb_strpos($all_text, 'استراح') !== false || mb_strpos($all_text, 'إستراح') !== false || mb_strpos($all_text, 'بين الشوط') !== false) { $final_status = 'بين الشوطين'; $final_timer = null; }
                elseif (mb_strpos($all_text, 'ركلات') !== false || mb_strpos($all_text, 'ترجيح') !== false) { $final_status = 'ركلات ترجيح'; $final_timer = null; }
                elseif (mb_strpos($all_text, 'تأجل') !== false) { $final_status = 'تأجلت'; $final_timer = null; }
            }
            
            $match['status'] = $final_status;
            $match['timer'] = $final_timer;
            $match['league'] = $match['league'] ?? 'Unknown League';
            $match['link'] = $match['link'] ?? null;
            $channelsString = !empty($filgoalChannels) ? implode(',', $filgoalChannels) : (is_array($match['channels'] ?? null) ? implode(',', $match['channels']) : '');

            // الإدخال في قاعدة البيانات (حماية Strict Mode)
            try {
                $stmt = $db->prepare("SELECT match_id, time FROM ". DB_PREFIX. "matches WHERE match_id = :match_id LIMIT 1");
                $stmt->execute([':match_id' => $matchId]);
                $existingMatch = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $final_time = $match['time'] ?? '00:00:00';
                if ($existingMatch && ($final_time === '00:00:00' || $final_time === '')) {
                    $final_time = $existingMatch['time'];
                }

                if ($existingMatch) {
                    $stmt = $db->prepare("UPDATE ". DB_PREFIX. "matches SET
                        league = :league, time = :time, timer = :timer, status = :status, team1 = :team1, team2 = :team2, 
                        team1_logo = :team1_logo, team2_logo = :team2_logo, score = :score, team1_score = :team1_score, 
                        team2_score = :team2_score, channels = :channels, link = :link, stadium = :stadium,
                        team1_pen_score = :team1_pen_score, team2_pen_score = :team2_pen_score WHERE match_id = :match_id");
                } else {
                    $stmt = $db->prepare("INSERT INTO ". DB_PREFIX. "matches
                        (match_id, league, date, time, timer, status, team1, team2, team1_logo, team2_logo, score, team1_score, team2_score, channels, link, stadium, team1_pen_score, team2_pen_score)
                        VALUES (:match_id, :league, :date, :time, :timer, :status, :team1, :team2, :team1_logo, :team2_logo, :score, :team1_score, :team2_score, :channels, :link, :stadium, :team1_pen_score, :team2_pen_score)");
                    $stmt->bindValue(':date', $match['date']); 
                }

                $stmt->bindValue(':match_id', $matchId, PDO::PARAM_INT);
                $stmt->bindValue(':league', $match['league']);
                $stmt->bindValue(':time', $final_time);
                $stmt->bindValue(':timer', ($match['timer'] === '' || $match['timer'] === null) ? null : $match['timer']); 
                $stmt->bindValue(':status', $match['status']);
                $stmt->bindValue(':team1', $match['team1']);
                $stmt->bindValue(':team2', $match['team2']);
                $stmt->bindValue(':team1_logo', $match['team1_logo']);
                $stmt->bindValue(':team2_logo', $match['team2_logo']);
                $stmt->bindValue(':score', ($match['score'] === '' || $match['score'] === null) ? null : $match['score']);
                
                $t1_score = (isset($match['team1_score']) && $match['team1_score'] !== '') ? $match['team1_score'] : null;
                $t2_score = (isset($match['team2_score']) && $match['team2_score'] !== '') ? $match['team2_score'] : null;
                $stmt->bindValue(':team1_score', $t1_score); 
                $stmt->bindValue(':team2_score', $t2_score); 
                
                $stmt->bindValue(':channels', $channelsString);
                $stmt->bindValue(':link', ($match['link'] === '' || $match['link'] === null) ? null : $match['link']); 
                $stmt->bindValue(':stadium', ($stadium === '' || $stadium === null) ? null : $stadium); 
                
                $t1_pen = (isset($match['team1_pen_score']) && $match['team1_pen_score'] !== '') ? $match['team1_pen_score'] : null;
                $t2_pen = (isset($match['team2_pen_score']) && $match['team2_pen_score'] !== '') ? $match['team2_pen_score'] : null;
                $stmt->bindValue(':team1_pen_score', $t1_pen);
                $stmt->bindValue(':team2_pen_score', $t2_pen);
                
                $stmt->execute();
                
            } catch (PDOException $e) {
                log_debug("[Scraper] ❌ فشل تخزين بيانات المباراة ({$matchId}): " . $e->getMessage());
                continue; 
            }

            // تفاصيل المباراة
            $matchLineups = null; $matchEvents = null; $matchStatsHistory = null;
            try { $matchLineups = scrapeLineups($matchId); } catch (Exception $e) {}
            try { $matchEvents = scrapeMatchEvents($matchId); } catch (Exception $e) {}
            if (!empty($match['link'])) {
                try { $matchStatsHistory = scrapeMatchStatsHistory($match['link']); } catch (Exception $e) {}
            }

            try {
                $stmt = $db->prepare("SELECT lineups, events, statistics FROM ". DB_PREFIX. "match_details WHERE match_id = :match_id LIMIT 1");
                $stmt->execute([':match_id' => $matchId]);
                $existingDetails = $stmt->fetch(PDO::FETCH_ASSOC);
                
                $newLineupsJson = ($matchLineups !== null) ? json_encode($matchLineups, JSON_UNESCAPED_UNICODE) : '[]';
                $newEventsJson = ($matchEvents !== null) ? json_encode($matchEvents, JSON_UNESCAPED_UNICODE) : '[]';
                $newStatsHistoryJson = ($matchStatsHistory !== null) ? json_encode($matchStatsHistory, JSON_UNESCAPED_UNICODE) : null;
                
                $updates = []; $params = [];
                if (!$existingDetails) {
                    $stmt = $db->prepare("INSERT INTO ". DB_PREFIX. "match_details (match_id, lineups, events, statistics) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$matchId, $newLineupsJson, $newEventsJson, $newStatsHistoryJson]);
                } else {
                    if ($existingDetails['lineups'] !== $newLineupsJson) { $updates[] = "lineups = ?"; $params[] = $newLineupsJson; }
                    if ($existingDetails['events'] !== $newEventsJson) { $updates[] = "events = ?"; $params[] = $newEventsJson; }
                    if ($newStatsHistoryJson !== null && $existingDetails['statistics'] !== $newStatsHistoryJson) { $updates[] = "statistics = ?"; $params[] = $newStatsHistoryJson; }
                    
                    if (!empty($updates)) {
                        $params[] = $matchId;
                        $stmt = $db->prepare("UPDATE ". DB_PREFIX. "match_details SET " . implode(', ', $updates) . " WHERE match_id = ?");
                        $stmt->execute($params);
                    }
                }
            } catch (PDOException $e) {
                log_debug("[Scraper] ❌ فشل تخزين تفاصيل المباراة ({$matchId}): " . $e->getMessage());
            }
        } 
    } 
    log_debug("[Scraper] --- اكتملت دالة updateMatches() --- \n");
}

updateMatches();
echo "Scraping process completed with Smart Status Engine.";
?>