<?php
// matches.php (Updated for Btolat New Structure)

require_once __DIR__ . '/simple_html_dom.php';

function scrapeMatches($date) {
    // الرابط الجديد لمركز المباريات
    $baseUrl = "https://www.btolat.com/matches-center";
    $url = $baseUrl;
    $queryString = [];

    if ($date) {
        $formattedDate = date('m.d.Y', strtotime($date));
        $queryString[] = "d={$formattedDate}";
    }
    $queryString[] = "_=" . time();
    $url .= "?" . implode('&', $queryString);

    // إعدادات cURL لجلب الصفحة
    $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/119.0.0.0 Safari/537.36'); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
    $htmlContent = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode != 200 || !$htmlContent) {
         // error_log("Failed to retrieve HTML from {$url}. HTTP Code: {$httpCode}");
        return null;
    }

    $html = str_get_html($htmlContent);
    if (!$html) {
         // error_log("Failed to parse HTML from {$url} using simple_html_dom.");
        return null;
    }

    $matches = [];
    $matchTables = $html->find('div.mleague-card');

    if (empty($matchTables)) {
        // error_log("No match tables found with selector 'div.mleague-card' on page: " . $url);
    }

    foreach ($matchTables as $matchTable) {
         $leagueElement = $matchTable->find('div.m-header div.m-info h2', 0);
         $league = $leagueElement ? trim($leagueElement->plaintext) : 'Unknown League';

        foreach ($matchTable->find('ul li[id]') as $match) { 

            $rawId = $match->id;
            $matchId = str_replace('m_', '', $rawId);

            if ($matchId && is_numeric($matchId)) {
                
                // 1. استخراج الحالة الإنجليزية من الكلاس (مهمة جداً لملفات API الـ JSON لاحقاً)
                $liClass = $match->class ?? '';
                $matchStatusEnum = 'NotStarted';
                if (stripos($liClass, 'NotStarted') !== false) $matchStatusEnum = 'NotStarted';
                elseif (stripos($liClass, 'Playing') !== false) $matchStatusEnum = 'Playing';
                elseif (stripos($liClass, 'Finished') !== false) $matchStatusEnum = 'Finished';
                elseif (stripos($liClass, 'Postpone') !== false) $matchStatusEnum = 'Postponed';
                elseif (stripos($liClass, 'Canceled') !== false) $matchStatusEnum = 'Canceled';

                $team1Element = $match->find('a.team', 0);
                $team2Element = $match->find('a.team', 1);
                
                $team1NameElement = $team1Element ? $team1Element->find('span', 0) : null;
                $team1 = $team1NameElement ? trim($team1NameElement->plaintext) : 'Unknown Team 1';
                
                $team2NameElement = $team2Element ? $team2Element->find('span', 0) : null;
                $team2 = $team2NameElement ? trim($team2NameElement->plaintext) : 'Unknown Team 2';
                
                $team1LogoElement = $team1Element ? $team1Element->find('img', 0) : null;
                $team2LogoElement = $team2Element ? $team2Element->find('img', 0) : null;
                
                $team1Logo = '';
                if ($team1LogoElement) { 
                    $team1Logo = $team1LogoElement->hasAttribute('data-src') ? $team1LogoElement->getAttribute('data-src') : $team1LogoElement->src; 
                }
                
                $team2Logo = '';
                if ($team2LogoElement) { 
                    $team2Logo = $team2LogoElement->hasAttribute('data-src') ? $team2LogoElement->getAttribute('data-src') : $team2LogoElement->src; 
                }

                $scoreElement = $match->find('div.scoreRresult', 0);
                $score = ''; $team1Score = ''; $team2Score = '';
                $pen1_score = null; $pen2_score = null;
                
                if ($scoreElement) {
                    $team1ScoreElement = $scoreElement->find('div.team1Score', 0);
                    $team2ScoreElement = $scoreElement->find('div.team2Score', 0);
                    
                    // 2. تنظيف الأهداف وجلب الأرقام فقط لمنع انهيار الـ JSON بوجود مسافات
                    if ($team1ScoreElement) { 
                        $t1_text = trim($team1ScoreElement->plaintext);
                        if (preg_match('/\d+/', $t1_text, $m)) $team1Score = $m[0];
                    }
                    if ($team2ScoreElement) { 
                        $t2_text = trim($team2ScoreElement->plaintext);
                        if (preg_match('/\d+/', $t2_text, $m)) $team2Score = $m[0];
                    }
                    
                    if ($team1Score !== '' && $team2Score !== '') {
                        $score = "{$team1Score} - {$team2Score}";
                    }

                    // 3. تأمين جلب ضربات الجزاء لعدم التداخل مع عنصر "الوقت"
                    $nextElement = $scoreElement->next_sibling();
                    if ($nextElement && ($nextElement->tag === 'div' || $nextElement->tag === 'span') && strpos($nextElement->class, 'match-time') === false) {
                        $penaltyText = trim($nextElement->plaintext);
                        if (preg_match('/(\d+)\s*-\s*(\d+)/', $penaltyText, $pen_matches)) {
                            $pen1_score = $pen_matches[1];
                            $pen2_score = $pen_matches[2];
                        }
                    }
                }

                $statusElement = $match->find('span.status-badge', 0);
                $status = $statusElement ? trim($statusElement->plaintext) : '';

                $timeElement = $match->find('span.match-time', 0);
                $matchTimeOrTimer = $timeElement ? trim($timeElement->plaintext) : '';

                $matchTime = '00:00:00'; 
                $matchTimerDisplay = null;
                
                if (preg_match('/م|ص|AM|PM/ui', $matchTimeOrTimer)) {
                    $matchTime = btolat_parse_time_string($matchTimeOrTimer);
                } elseif (!empty($matchTimeOrTimer)) {
                    // تنظيف الدقيقة (مثلاً إزالة علامة ' من 24')
                    $matchTimerDisplay = str_replace("'", "", $matchTimeOrTimer); 
                }

                if ($matchTimerDisplay && (mb_strpos($matchTimerDisplay, 'إستراح') !== false || mb_strpos($matchTimerDisplay, 'استراح') !== false)) {
                    $status = 'بين الشوطين';
                    $matchTimerDisplay = null;
                }

                $channels = [];
                $channelsList = $match->find('div.m-channellist a'); 
                foreach ($channelsList as $channel) {
                    if ($channel->hasAttribute('title')) { $channels[] = trim($channel->title); }
                }

                $matchDateFormatted = $date ? date('Y-m-d', strtotime($date)) : date('Y-m-d');
                $matchLink = "https://www.btolat.com/matches/details/" . $matchId;

                $matches[] = [
                    'match_id' => $matchId,
                    'date' => $matchDateFormatted,
                    'league' => $league,
                    'team1' => $team1,
                    'team2' => $team2,
                    'team1_logo' => $team1Logo,
                    'team2_logo' => $team2Logo,
                    'time' => $matchTime,
                    'score' => $score,
                    'team1_score' => $team1Score,
                    'team2_score' => $team2Score,
                    'status' => $status,
                    'match_status_enum' => $matchStatusEnum, // تم إضافتها للاستخدام المتقدم
                    'channels' => $channels,
                    'timer' => $matchTimerDisplay,
                    'team1_pen_score' => $pen1_score,
                    'team2_pen_score' => $pen2_score,
                    'link' => $matchLink
                ];
            } else {
                 // error_log("Found list item without a valid numeric ID in league table: " . $league . " - Raw ID: " . $rawId);
            }
        } 
    } 

     if ($html) {
         $html->clear();
         unset($html);
     }
    return $matches;
} 

function btolat_parse_time_string($timeStr) {
    if (empty($timeStr)) {
        return '00:00:00';
    }

    $timeStr = preg_replace('/[^\d:\sAMPampصمصم\-\']/u', '', $timeStr);
    $timeStr = trim($timeStr);

    if (strpos($timeStr, '00:00') !== false) {
        return '00:00:00';
    }

    $timeStr = preg_replace('/\s*(ص)\s*/u', ' AM', $timeStr);
    $timeStr = preg_replace('/\s*(م)\s*/u', ' PM', $timeStr);
    $timeStr = preg_replace('/\s+/', ' ', $timeStr);
    $timeStr = trim($timeStr);

    if (strpos($timeStr, "'") !== false) {
        return '00:00:00';
    }

    $timestamp = strtotime($timeStr);

    if ($timestamp !== false) {
        return date('H:i:s', $timestamp);
    }
    
    return '00:00:00';
}
?>