<?php
// match_stats_history.php (v3.1 - Complete with h2h_matches & Logging)

/**
 * هذا الملف مسؤول عن جلب بيانات الإحصاءات التاريخية
 * (المواجهات المباشرة، الترتيب، آخر 5 مباريات)
 * من صفحة تفاصيل المباراة.
 */

// التأكد من تضمين المكتبة
if (!function_exists('file_get_html')) {
    require_once __DIR__ . '/simple_html_dom.php';
}

/**
 * دالة لجلب الإحصاءات التاريخية من صفحة تفاصيل المباراة
 * @param string $matchUrl الرابط الكامل لصفحة تفاصيل المباراة
 * @return array|null مصفوفة تحتوي على الإحصاءات أو null عند الفشل
 */
function scrapeMatchStatsHistory($matchUrl) {
    // error_log("--- Starting scrapeMatchStatsHistory for: " . $matchUrl . " ---"); // Log start

    // استخدام cURL لجلب المحتوى
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $matchUrl);
    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, 20);
    $htmlContent = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

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

    $html = str_get_html($htmlContent);

    if (!$html) {
        // error_log("[StatsHistory] Failed to parse HTML.");
        return null;
    }

    $stats = [
        'h2h_summary'   => [],
        'h2h_matches'   => [], // Initialize h2h_matches array
        'standings'     => [],
        'last5_team1' => [],
        'last5_team2' => []
    ];

    // العثور على حاوية الإحصاءات الرئيسية
    $tabBody = $html->find('div.tabBody', 0); // (Implicitly, as it contains all elements)
    if (!$tabBody) {
        // error_log("[StatsHistory] Could not find main stats container 'div.tabBody'.");
        $html->clear(); unset($html);
        return null;
    } else {
        // error_log("[StatsHistory] Found 'div.tabBody'.");
    }

    // --- 1. جلب ملخص المواجهات المباشرة (h2h_summary) ---
    $h2hTitle = null;
    // Find the H1 title specifically
    foreach($tabBody->find('h1.tabTitle') as $titleEl) { //
       $titleSpan = $titleEl->find('span', 0);
       // ★ استخدام clean_scraped_text هنا للتحقق من العنوان بدقة
       if ($titleSpan && strpos(clean_scraped_text($titleSpan->plaintext), 'تاريخ مواجهات') !== false) {
          $h2hTitle = $titleEl;
          // error_log("[StatsHistory] Found H2H title: " . clean_scraped_text($titleSpan->plaintext));
          break;
       }
    }

    if ($h2hTitle) {
        $h2hCard = $h2hTitle->next_sibling('div.card'); // (Card follows H1)
        if ($h2hCard) {
             // error_log("[StatsHistory] Found H2H card.");
            $team1NameEl = $h2hCard->find('.fastHis.text-right span', 0); //
            $team2NameEl = $h2hCard->find('.fastHis.text-left span', 0); //
            
            // ★ التعديل: استخدام clean_scraped_text
            $stats['h2h_summary']['team1_name'] = $team1NameEl ? clean_scraped_text($team1NameEl->plaintext) : null;
            $stats['h2h_summary']['team2_name'] = $team2NameEl ? clean_scraped_text($team2NameEl->plaintext) : null;
            
            // error_log("[StatsHistory] Team Names Found: T1='{$stats['h2h_summary']['team1_name']}', T2='{$stats['h2h_summary']['team2_name']}'");

            $historyChart = $h2hCard->find('.historyChart', 0); //
            if ($historyChart) {
                // error_log("[StatsHistory] Found historyChart div.");
                // Target the SPAN inside the P tag for numbers
                $team1WinsSpan = $historyChart->find('.historyChartTeamAWin p span', 0); //
                $drawsSpan = $historyChart->find('.historyChartDraw p span', 0); //
                $team2WinsSpan = $historyChart->find('.historyChartTeamBWin p span', 0); //

                // Log the raw text found
                // ★ التعديل: تنظيف النص الخام قبل الطباعة والتحويل
                $rawT1Wins = $team1WinsSpan ? clean_scraped_text($team1WinsSpan->plaintext) : 'NOT_FOUND';
                $rawDraws = $drawsSpan ? clean_scraped_text($drawsSpan->plaintext) : 'NOT_FOUND';
                $rawT2Wins = $team2WinsSpan ? clean_scraped_text($team2WinsSpan->plaintext) : 'NOT_FOUND';
                // error_log("[StatsHistory] Raw H2H Numbers: Wins1='{$rawT1Wins}', Draws='{$rawDraws}', Wins2='{$rawT2Wins}'");

                // Extract numbers safely using intval which handles non-numeric better
                $stats['h2h_summary']['team1_wins'] = $team1WinsSpan ? intval($rawT1Wins) : 0;
                $stats['h2h_summary']['draws']      = $drawsSpan ? intval($rawDraws) : 0;
                $stats['h2h_summary']['team2_wins'] = $team2WinsSpan ? intval($rawT2Wins) : 0;
                 // error_log("[StatsHistory] Parsed H2H Numbers: Wins1={$stats['h2h_summary']['team1_wins']}, Draws={$stats['h2h_summary']['draws']}, Wins2={$stats['h2h_summary']['team2_wins']}");

            } else {
                 // error_log("[StatsHistory] Could not find '.historyChart' div inside H2H card.");
                 // Default to 0 if chart not found
                 $stats['h2h_summary']['team1_wins'] = 0; $stats['h2h_summary']['draws'] = 0; $stats['h2h_summary']['team2_wins'] = 0;
            }
        } else {
             // error_log("[StatsHistory] Could not find 'div.card' after H2H title.");
             // Default to 0 if card not found
             $stats['h2h_summary']['team1_wins'] = 0; $stats['h2h_summary']['draws'] = 0; $stats['h2h_summary']['team2_wins'] = 0;
        }
    } else {
         // error_log("[StatsHistory] H2H title ('تاريخ مواجهات') not found.");
         // Default to 0 if title not found
         $stats['h2h_summary']['team1_wins'] = 0; $stats['h2h_summary']['draws'] = 0; $stats['h2h_summary']['team2_wins'] = 0;
    }

    // --- 1.5. جلب آخر المواجهات المباشرة (h2h_matches) ---
    $h2hMatchesTitleFound = false;
    foreach($tabBody->find('h2.tabTitle') as $titleEl) { //
        $titleSpan = $titleEl->find('span', 0);
        // ★ التعديل: تنظيف النص عند البحث
        if ($titleSpan && strpos(clean_scraped_text($titleSpan->plaintext), 'نتائج اخر مباريات بين') !== false) {
             // error_log("[StatsHistory] Found H2H Matches title: " . clean_scraped_text($titleSpan->plaintext));
             $h2hMatchesTitleFound = true;
            $h2hMatchesCard = $titleEl->next_sibling('div.card'); //
            if ($h2hMatchesCard) {
                // error_log("[StatsHistory] Found H2H Matches card.");
                $matchesInCard = 0;
                foreach ($h2hMatchesCard->find('div.TeamVsTeam') as $matchRow) { //
                    $matchesInCard++;
                    $datePlace = $matchRow->find('.dateAndPlace p', 0); //
                $date = ''; // قيمة افتراضية للتاريخ (سيحتوي على البطولة أيضاً)
               

                if ($datePlace) {
                    // ★ التعديل: تنظيف التاريخ
                    $date = clean_scraped_text($datePlace->plaintext); // الحصول على النص الكامل كما هو
                } else {
                    // error_log("[StatsHistory H2H Matches] Could not find '.dateAndPlace p' in row.");
                }
                    $teamA_name = $matchRow->find('.teamA a', 0); // (Often the first team listed)
                    $teamA_score_span = $matchRow->find('.teamA .col-2 span', 0); // (Score for first team)
                    $teamB_name = $matchRow->find('.teamB a', 0); // (Often the second team listed)
                    $teamB_score_span = $matchRow->find('.teamB .col-2 span', 0); // (Score for second team)

                    // Populate the h2h_matches array
                    $stats['h2h_matches'][] = [
                        'date' => $date, 
                        
                        // ★ التعديل: تنظيف الأسماء والنتائج
                        'teamA_name'  => $teamA_name ? clean_scraped_text($teamA_name->plaintext) : '?',
                        'teamA_score' => $teamA_score_span ? clean_scraped_text($teamA_score_span->plaintext) : '-',
                        'teamB_name'  => $teamB_name ? clean_scraped_text($teamB_name->plaintext) : '?',
                        'teamB_score' => $teamB_score_span ? clean_scraped_text($teamB_score_span->plaintext) : '-'
                    ];
                }
                 // error_log("[StatsHistory] Found {$matchesInCard} matches in H2H Matches card.");
            } else {
                 // error_log("[StatsHistory] Could not find 'div.card' after H2H Matches title.");
            }
            break; // Stop searching once H2H matches title is found
        }
    }
     if(!$h2hMatchesTitleFound) {
          // error_log("[StatsHistory] H2H Matches title ('نتائج اخر مباريات بين') not found.");
     }
    // --- نهاية إضافة سحب h2h_matches ---


  // --- 2. جلب جدول الترتيب (standings) ---
    // --- ▼▼▼ START REPLACEMENT (v3.3 - Professional Approach) ▼▼▼ ---
    $standingsTable = null;
    $standingsFound = false; // Use a simpler flag name

    // Strategy: Find the specific card containing the standings table more reliably.
    // Look for the table first, then check its parent card.
    // error_log("[StatsHistory Standings] Searching for 'table.leagueTable'...");
    $potentialTables = $tabBody->find('table.leagueTable'); // Find all league tables

    if (empty($potentialTables)) {
        // error_log("[StatsHistory Standings] No elements found matching 'table.leagueTable'.");
    } else {
        // error_log("[StatsHistory Standings] Found " . count($potentialTables) . " potential table(s) matching 'table.leagueTable'.");
        foreach ($potentialTables as $tableIndex => $table) {
            // Check if this table has the expected structure (a tbody with data rows containing 'div.color span')
            $firstDataCell = $table->find('tbody tr td div.color span', 0); // Look for the specific data structure
            $groupHeader = $table->find('th.groupTitle', 0); // Look for group header

            // We assume the standings table is the one containing data cells with 'div.color span'
            if ($firstDataCell || $groupHeader) { // If it has either data structure or a group header, assume it's the one
                $standingsTable = $table;
                $standingsFound = true;
                // error_log("[StatsHistory Standings] Selected table index {$tableIndex} as the likely standings table.");
                break; // Use the first table found that matches
            } else {
                // error_log("[StatsHistory Standings] Table index {$tableIndex} skipped, doesn't contain expected 'div.color span' or 'th.groupTitle'.");
            }
        }
        if (!$standingsFound) {
             // error_log("[StatsHistory Standings] None of the found 'table.leagueTable' elements seemed to be the correct standings table.");
        }
    }


    // Process the table if found
    if ($standingsTable) {
        // Precise helper function to get stat value from 'div.color span'
        $getStat = function($td, $colIndex) {
            if (!$td) {
                // error_log("[getStat Col {$colIndex}] Error: TD object is null.");
                return '0';
            }
            // Directly target the expected structure
            $valueEl = $td->find('div.color span', 0); //
            if ($valueEl) {
                // ★ التعديل: تنظيف النص
                $rawText = clean_scraped_text($valueEl->plaintext);
                // // error_log("[getStat Col {$colIndex}] Found via 'div.color span': '{$rawText}'");
                return $rawText !== '' ? $rawText : '0';
            } else {
                // Fallback ONLY if the primary structure is missing
                // ★ التعديل: تنظيف النص
                $rawText = clean_scraped_text($td->plaintext);
                // error_log("[getStat Col {$colIndex}] Warning: Could not find 'div.color span'. Falling back to TD plaintext: '{$rawText}'");
                return $rawText !== '' ? $rawText : '0';
            }
        };

        $rowCount = 0;
        $teamsAdded = 0;
        // Iterate through ALL rows directly within the found table
        foreach ($standingsTable->find('tr') as $rowIndex => $row) {
            $rowCount++;
            // Skip rows that ONLY contain TH elements (headers)
            if ($row->find('th', 0) && !$row->find('td', 0)) { //
                // error_log("[StatsHistory Standings] Skipping header row {$rowIndex}: " . trim($row->plaintext));
                continue;
            }

            // Target TD elements specifically
            $cols = $row->find('td');
            $colCount = count($cols);
            // // error_log("[StatsHistory Standings] Row {$rowIndex} has {$colCount} TD elements.");

            // Expecting exactly 10 TD elements for a data row based on HTML structure
            if ($colCount == 10) { //
                 $rankTd = $cols[0]; //
                 $teamTd = $cols[1]; //
                 $playedTd = $cols[2]; //
                 $winsTd = $cols[3]; // Implicit +1
                 $drawsTd = $cols[4]; // Implicit +2
                 $lossesTd = $cols[5]; // Implicit +3
                 $gfTd = $cols[6]; // Implicit +4
                 $gaTd = $cols[7]; // Implicit +5
                 $gdTd = $cols[8]; // Implicit +6
                 $pointsTd = $cols[9]; // Implicit +7

                 // Extract Rank (might be inside <b>)
                 $rankB = $rankTd->find('b', 0);
                 // ★ التعديل: تنظيف النص
                 $rank = $rankB ? clean_scraped_text($rankB->plaintext) : clean_scraped_text($rankTd->plaintext);

                 // Extract Team Name
                 $teamNameEl = $teamTd->find('a', 0);
                 // ★ التعديل: استخدام clean_scraped_text التي تقوم بـ html_entity_decode وأكثر
                 $teamName = $teamNameEl ? clean_scraped_text($teamNameEl->plaintext) : 'Unknown';

                 // Log extracted data for debugging the first few rows
                 if ($teamsAdded < 3) {
                      // error_log("[StatsHistory Standings] Row {$rowIndex} Data: Rank='{$rank}', Team='{$teamName}', Played='{$getStat($playedTd, 2)}', Wins='{$getStat($winsTd, 3)}', Draws='{$getStat($drawsTd, 4)}', Losses='{$getStat($lossesTd, 5)}', GF='{$getStat($gfTd, 6)}', GA='{$getStat($gaTd, 7)}', GD='{$getStat($gdTd, 8)}', Points='{$getStat($pointsTd, 9)}'");
                 }

                 // Add data to the array
                 $stats['standings'][] = [
                    'rank'          => $rank,
                    'team_name'     => $teamName,
                    'played'        => $getStat($playedTd, 2),
                    'wins'          => $getStat($winsTd, 3),
                    'draws'         => $getStat($drawsTd, 4),
                    'losses'        => $getStat($lossesTd, 5),
                    'goals_for'     => $getStat($gfTd, 6),
                    'goals_against' => $getStat($gaTd, 7),
                    'goal_diff'     => $getStat($gdTd, 8),
                    'points'        => $getStat($pointsTd, 9)
                 ];
                 $teamsAdded++;

            } else {
                 // Log rows that don't match the expected TD count
                 if ($colCount > 0) { // Avoid logging header rows again if they slip through
                    // error_log("[StatsHistory Standings] Row {$rowIndex} skipped, expected 10 TD elements, found {$colCount}. Row HTML sample: " . substr($row->outertext, 0, 150));
                 }
            }
        } // End row loop
         // error_log("[StatsHistory] Finished processing standings table. Processed {$rowCount} rows, added {$teamsAdded} teams.");
    } // End if ($standingsTable)
    // --- ▲▲▲ نهاية الكود الخاص بالترتيب ▲▲▲ ---


    // --- 3. جلب آخر 5 مباريات (للفريقين) ---
    // (الكود هنا يبدو صحيحاً بناءً على JSON السابق، سنضيف فقط بعض التسجيل)
    $last5Titles = $tabBody->find('h2.tabTitle'); // (Implicit H2 for Last 5)
    $team1Last5_scraped = false;
    $last5FoundCount = 0;

    foreach ($last5Titles as $titleEl) {
        $titleSpan = $titleEl->find('span', 0);
        // ★ التعديل: تنظيف النص
        if ($titleSpan && strpos(clean_scraped_text($titleSpan->plaintext), 'نتائج اخر 5 مباريات') !== false) {
             // error_log("[StatsHistory] Found Last 5 title: " . clean_scraped_text($titleSpan->plaintext));
             $last5FoundCount++;
            $targetArrayKey = !$team1Last5_scraped ? 'last5_team1' : 'last5_team2';
            $card = $titleEl->next_sibling('div.card'); // (Card follows title)

            if ($card) {
                // error_log("[StatsHistory] Found card for {$targetArrayKey}.");
                $matchesInCard = 0;
                foreach ($card->find('div.TeamVsTeam') as $matchRow) { //
                     $matchesInCard++;
                    $datePlace = $matchRow->find('.dateAndPlace p', 0); //
                $date = ''; // قيمة افتراضية للتاريخ (سيحتوي على البطولة أيضاً)
                

                if ($datePlace) {
                    // ★ التعديل: تنظيف التاريخ
                    $date = clean_scraped_text($datePlace->plaintext); // الحصول على النص الكامل كما هو
                } else {
                     // error_log("[StatsHistory Last5] Could not find '.dateAndPlace p' in row.");
                }
                    $teamA_name = $matchRow->find('.teamA a', 0); //
                    $teamA_score_span = $matchRow->find('.teamA .col-2 span', 0); //
                    $teamB_name = $matchRow->find('.teamB a', 0); // (Implicit B)
                    $teamB_score_span = $matchRow->find('.teamB .col-2 span', 0); // (Implicit B score)

                    $stats[$targetArrayKey][] = [
                        'date' => $date,
                        // ★ التعديل: تنظيف الأسماء والنتائج
                        'teamA_name'  => $teamA_name ? clean_scraped_text($teamA_name->plaintext) : '?',
                        'teamA_score' => $teamA_score_span ? clean_scraped_text($teamA_score_span->plaintext) : '-',
                        'teamB_name'  => $teamB_name ? clean_scraped_text($teamB_name->plaintext) : '?',
                        'teamB_score' => $teamB_score_span ? clean_scraped_text($teamB_score_span->plaintext) : '-'
                    ];
                }
                 // error_log("[StatsHistory] Found {$matchesInCard} matches in card for {$targetArrayKey}.");
            } else {
                 // error_log("[StatsHistory] Could not find 'div.card' after Last 5 title for {$targetArrayKey}.");
            }
            $team1Last5_scraped = true;
        }
    }
     if($last5FoundCount < 2) {
         // error_log("[StatsHistory] Warning: Found only {$last5FoundCount} 'Last 5' sections (expected 2).");
     }


    // تنظيف الذاكرة
    $html->clear(); unset($html);
    
    // error_log("[StatsHistory FINAL CHECK] Before return, h2h_matches structure: " . print_r($stats['h2h_matches'], true));
    // error_log("[StatsHistory FINAL CHECK] Before return, last5_team1 structure: " . print_r($stats['last5_team1'], true));
    
    // error_log("[StatsHistory] Finished scraping. H2H Wins1=" . ($stats['h2h_summary']['team1_wins'] ?? 'N/A') . ", H2H Matches=" . count($stats['h2h_matches']) . ", Standings Count=" . count($stats['standings']) . ", Last5_T1 Count=" . count($stats['last5_team1']));
    return $stats;
}

?>