<?php
declare(strict_types=1);
ini_set('display_errors','1');
error_reporting(E_ALL);

require_once 'persiantranslate.php';

// helper: pick()  → اولین کلید موجود را از آرایه برمی‌گرداند
if (!function_exists('pick')) {
    function pick(array $arr, array $keys, $default = null) {
        foreach ($keys as $k) {
            if (array_key_exists($k, $arr)) {
                return $arr[$k];
            }
        }
        return $default;
    }
}

// ===== input =====
$eid = $_GET['eid'] ?? '1528815';
$eid = preg_replace('/\D/','', $eid);
$raw = isset($_GET['raw']); // ?raw=1 برای دیدن JSON خام

$BASE = 'https://prod-public-api.livescore.com/v1/api/app';

// ===== http =====
function http_get(string $url): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER => [
            'Accept: application/json,text/plain,*/*',
            'Accept-Language: en-US,en;q=0.9',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0 Safari/537.36',
            'Origin: https://www.livescore.com',
            'Referer: https://www.livescore.com/',
        ],
    ]);
    $body = curl_exec($ch);
    $err  = curl_error($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return [$code,$err,$body];
}

function get_json_first_ok(array $urls): ?array {
    foreach ($urls as $u) {
        [$code,$err,$body] = http_get($u);
        if ($code === 200 && $body) {
            $data = json_decode($body, true);
            if (is_array($data)) return $data;
        }
    }
    return null;
}

function looks_var_disallowed(array $ev): bool {
    // متن رویداد را یکجا پایین‌حرفی کن و به‌دنبال نشانه‌های VAR و ابطال بگرد
    $s = strtolower(json_encode($ev, JSON_UNESCAPED_UNICODE));
    return (str_contains($s,'var') && (str_contains($s,'disallow') || str_contains($s,'no goal') || str_contains($s,'overturned')));
}

function looks_penalty_missed(array $ev): bool {
    // 1) متن‌ها (اگر موجود بود)
    $s = strtolower(json_encode($ev, JSON_UNESCAPED_UNICODE));
    if (str_contains($s,'pen') && (str_contains($s,'miss') || str_contains($s,'saved') || str_contains($s,'save') || str_contains($s,'post') || str_contains($s,'bar') || str_contains($s,'over') || str_contains($s,'wide'))) {
        return true;
    }

    // 2) هِیوریستیک بدون متن: «penalty دیده می‌شود» + «score این رویداد تغییر نکرد/ندارد»
    $hasPenContext = str_contains($s,'pen'); // PEN / penalty
    $sc = $ev['Sc'] ?? $ev['score'] ?? null;
    $hasScore = (is_array($sc) && count($sc)>=2) || (is_string($sc) && $sc!=='');
    if ($hasPenContext && !$hasScore) return true;

    // 3) کدهای احتمالی رویداد (اگر IT وجود داشته باشد)
    $it = $ev['IT'] ?? $ev['type'] ?? null;
    // برخی فیدها برای پنالتی خراب از کدهای متفاوت استفاده می‌کنند
    if (in_array((int)$it, [38, 66, 67, 68], true)) return true;

    return false;
}

function __nm(array $p): string {
    $n = $p['Pn'] ?? '';
    if (!$n) {
        $firstName = $p['Fn'] ?? '';
        $lastName = $p['Ln'] ?? '';
        $n = trim($firstName . ' ' . $lastName);
    }
    return $n ?: '';
}

function __pid(array $p): ?string {
    foreach (['ID','Pid','playerId','PidO'] as $k) {
        if (!empty($p[$k])) return (string)$p[$k];
    }
    return null;
}

// ===== incident sources (گسترده) =====
$incUrls = [
    "$BASE/incidents/soccer/$eid?MD=1&locale=en",
    "$BASE/details/soccer/$eid?MD=1&locale=en",
    "$BASE/match/soccer/$eid/details?MD=1&locale=en",
    "$BASE/event/soccer/$eid?MD=1&locale=en",
    "$BASE/match/soccer/$eid?MD=1&locale=en",
];
$incData = get_json_first_ok($incUrls);

// ===== get match data from live API =====
$liveUrl = "https://prod-public-api.livescore.com/v1/api/app/live/soccer/3.30";
$liveData = get_json_first_ok([$liveUrl]);

// تیم‌ها را از liveData استخراج کن - نسخه بهبود یافته
function get_teams_from_live_data(array $liveData, string $eid): array {
    $homeTeamName = 'تیم خانگی';
    $awayTeamName = 'تیم میهمان';
    
    if (empty($liveData)) {
        return [$homeTeamName, $awayTeamName];
    }
    
    // دیباگ: لاگ ساختار داده برای بررسی
    // error_log("Live Data Structure: " . json_encode(array_keys($liveData)));
    
    // روش ۱: جستجو در Stages -> Events
    if (isset($liveData['Stages']) && is_array($liveData['Stages'])) {
        foreach ($liveData['Stages'] as $stage) {
            if (isset($stage['Events']) && is_array($stage['Events'])) {
                foreach ($stage['Events'] as $event) {
                    $eventEid = (string)($event['Eid'] ?? '');
                    if ($eventEid === $eid) {
                        $homeTeamName = $event['T1'][0]['Nm'] ?? $event['T1']['Nm'] ?? $event['T1'][0]['Name'] ?? $event['T1']['Name'] ?? 'تیم خانگی';
                        $awayTeamName = $event['T2'][0]['Nm'] ?? $event['T2']['Nm'] ?? $event['T2'][0]['Name'] ?? $event['T2']['Name'] ?? 'تیم میهمان';
                        return [$homeTeamName, $awayTeamName];
                    }
                }
            }
        }
    }
    
    // روش ۲: جستجو در Events مستقیم
    if (isset($liveData['Events']) && is_array($liveData['Events'])) {
        foreach ($liveData['Events'] as $event) {
            $eventEid = (string)($event['Eid'] ?? '');
            if ($eventEid === $eid) {
                $homeTeamName = $event['T1'][0]['Nm'] ?? $event['T1']['Nm'] ?? $event['T1'][0]['Name'] ?? $event['T1']['Name'] ?? 'تیم خانگی';
                $awayTeamName = $event['T2'][0]['Nm'] ?? $event['T2']['Nm'] ?? $event['T2'][0]['Name'] ?? $event['T2']['Name'] ?? 'تیم میهمان';
                return [$homeTeamName, $awayTeamName];
            }
        }
    }
    
    // روش ۳: اگر eid مطابقت نداشت، اولین ایونت رو بگیر
    if (isset($liveData['Stages'][0]['Events'][0])) {
        $firstEvent = $liveData['Stages'][0]['Events'][0];
        $homeTeamName = $firstEvent['T1'][0]['Nm'] ?? $firstEvent['T1']['Nm'] ?? $firstEvent['T1'][0]['Name'] ?? $firstEvent['T1']['Name'] ?? 'تیم خانگی';
        $awayTeamName = $firstEvent['T2'][0]['Nm'] ?? $firstEvent['T2']['Nm'] ?? $firstEvent['T2'][0]['Name'] ?? $firstEvent['T2']['Name'] ?? 'تیم میهمان';
    }
    
    return [$homeTeamName, $awayTeamName];
}

list($homeTeamName, $awayTeamName) = get_teams_from_live_data($liveData ?? [], $eid);
// دیباگ: نمایش نام تیم‌ها برای اطمینان
error_log("Home Team: " . $homeTeamName);
error_log("Away Team: " . $awayTeamName);

if (!$incData) { 
    if ($raw) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['error' => '❌ incidents/details داده نداد.'], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
        exit;
    }
    $error_message = '❌ اطلاعات رویدادها در دسترس نیست.';
}

// ===== recursive collector: هر آرایه‌ای که شبیه رویداد است را بردار =====
function is_event_like($item): bool {
    if (!is_array($item)) return false;
    $keys = ['Min','MinEx','IT','Tm','Sc','Pn','ID','Aid','type','score','minute','playerId'];
    foreach ($keys as $k) if (array_key_exists($k, $item)) return true;
    return false;
}

function collect_incidents_recursive($node, array &$out): void {
    if (is_array($node)) {
        $allEvents = true;
        $hasAny = false;
        foreach ($node as $v) {
            if (is_array($v)) { $hasAny = true; if (!is_event_like($v)) { $allEvents = false; } }
            else { $allEvents = false; }
        }
        if ($hasAny && $allEvents) {
            foreach ($node as $v) $out[] = $v;
            return;
        }
        foreach ($node as $k=>$v) collect_incidents_recursive($v, $out);
    }
}

$incs = [];
collect_incidents_recursive($incData, $incs);

// حذف آیتم‌های غیرایونتیِ آشکار
$incs = array_values(array_filter($incs, function($ev){
    if (!is_array($ev)) return false;
    $min = $ev['Min'] ?? $ev['minute'] ?? null;
    $it  = $ev['IT'] ?? $ev['type'] ?? null;
    $pn  = $ev['Pn'] ?? null;
    $sc  = $ev['Sc'] ?? $ev['score'] ?? null;
    return $min !== null || $pn !== null || $sc !== null || $it !== null;
}));

// ===== lineups برای map اسامی =====
$luUrls = [
    "$BASE/lineups/soccer/$eid?MD=1&locale=en",
    "$BASE/match/soccer/$eid/lineups?MD=1&locale=en",
    "$BASE/match/soccer/$eid?MD=1&locale=en",
    "$BASE/details/soccer/$eid?MD=1&locale=en",
];
$luData = get_json_first_ok($luUrls);

function build_player_map(array $data): array {
    $map = [];
    $paths = [
        ['Lu','T1','Ps'], ['Lu','T2','Ps'],
        ['Lineups','T1','Ps'], ['Lineups','T2','Ps'],
        ['T1','Ps'], ['T2','Ps'],
        ['Team1','Players'], ['Team2','Players'],
        ['Players'],
    ];
    $get = function($arr,$path){
        $x=$arr; foreach($path as $k){ if(is_array($x) && isset($x[$k])){ $x=$x[$k]; } else { return null; } } return $x;
    };
    foreach ($paths as $p) {
        $players = $get($data,$p);
        if (!is_array($players)) continue;
        foreach ($players as $pl) {
            if (!is_array($pl)) continue;
            $id = $pl['ID'] ?? $pl['Pid'] ?? $pl['PidO'] ?? $pl['playerId'] ?? null;
            if (!$id) continue;
            $name = $pl['Pn'] ?? trim(($pl['Fn'] ?? '').' '.($pl['Ln'] ?? '')) ?? $pl['Name'] ?? null;
            if ($name) $map[(string)$id] = $name;
        }
    }
    return $map;
}
$playerMap = $luData ? build_player_map($luData) : [];

// ===== استخراج نام تیم‌ها از luData یا incData =====
function get_team_names(array $incData, array $luData): array {
    $homeTeamName = 'تیم خانگی';
    $awayTeamName = 'تیم میهمان';
    
    // مسیرهای بیشتر اضافه شده
    $paths = [
        ['Stages','0','T1','0','Nm'], ['Stages','0','T1','0','Tn'],
        ['Stages','0','T1','Nm'], ['Stages','0','T1','Tn'],
        ['T1','0','Nm'], ['T1','0','Tn'],
        ['T1','Nm'], ['T1','Tn'],
        ['Lu','T1','Nm'], ['Lineups','T1','Nm'], ['Team1','Name'],
    ];
    $get = function($arr,$path){
        $x=$arr; foreach($path as $k){ if(is_array($x) && isset($x[$k])){ $x=$x[$k]; } else { return null; } } return $x;
    };
    
    // اول incData چک کن
    foreach ($paths as $p) {
        $name = $get($incData, $p);
        if ($name && $name !== 'خانه') $homeTeamName = $name;
    }
    
    $pathsAway = [
        ['Stages','0','T2','0','Nm'], ['Stages','0','T2','0','Tn'],
        ['Stages','0','T2','Nm'], ['Stages','0','T2','Tn'],
        ['T2','0','Nm'], ['T2','0','Tn'],
        ['T2','Nm'], ['T2','Tn'],
        ['Lu','T2','Nm'], ['Lineups','T2','Nm'], ['Team2','Name'],
    ];
    foreach ($pathsAway as $p) {
        $name = $get($incData, $p);
        if ($name && $name !== 'میهمان') $awayTeamName = $name;
    }
    
    // اگر نبود، luData چک کن
    if ($homeTeamName === 'تیم خانگی') {
        foreach ($paths as $p) {
            $name = $get($luData, $p);
            if ($name && $name !== 'خانه') $homeTeamName = $name;
        }
    }
    if ($awayTeamName === 'تیم میهمان') {
        foreach ($pathsAway as $p) {
            $name = $get($luData, $p);
            if ($name && $name !== 'میهمان') $awayTeamName = $name;
        }
    }
    
    return [$homeTeamName, $awayTeamName];
}

if ($homeTeamName === 'تیم خانگی' || $awayTeamName === 'تیم میهمان') {
    list($homeTeamName, $awayTeamName) = get_team_names($incData ?? [], $luData ?? []);
}

// ===== نوع رویداد =====
function map_event_type($it, $hasScore): array {
    $map = [
        36 => ['key'=>'GOAL','emoji'=>'⚽','tag'=>null],
        37 => ['key'=>'GOAL','emoji'=>'⚽','tag'=>'PEN'],
        39 => ['key'=>'GOAL','emoji'=>'⚽','tag'=>'OG'],
        43 => ['key'=>'YC','emoji'=>'🟨','tag'=>null],
        44 => ['key'=>'RC','emoji'=>'🟥','tag'=>null],
        45 => ['key'=>'2YC','emoji'=>'🟨🟥','tag'=>null],
    ];
    if (isset($map[$it])) return $map[$it];
    if ($hasScore) return ['key'=>'GOAL','emoji'=>'⚽','tag'=>null];
    return ['key'=>'EVT','emoji'=>'•','tag'=>null];
}

// تابع برای پیدا کردن بازی فعلی از بین داده‌های لایو
function get_current_match_from_live($liveData, $eid) {
    if (isset($liveData['Stages'])) {
        foreach ($liveData['Stages'] as $stage) {
            if (isset($stage['Events'])) {
                foreach ($stage['Events'] as $event) {
                    if (($event['Eid'] ?? '') == $eid) {
                        return $event;
                    }
                }
            }
        }
    }
    return null;
}

// دریافت داده‌های لایو
$liveUrl = "https://prod-public-api.livescore.com/v1/api/app/live/soccer/3.30";
$liveData = get_json_first_ok([$liveUrl]);
$currentMatch = $liveData ? get_current_match_from_live($liveData, $eid) : null;

// تابع تبدیل اعداد انگلیسی به فارسی
function convertToPersianNumbers($number) {
    $english = array('0','1','2','3','4','5','6','7','8','9');
    $persian = array('۰','۱','۲','۳','۴','۵','۶','۷','۸','۹');
    return str_replace($english, $persian, (string)$number);
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>رویدادهای بازی</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Bai+Jamjuree:wght@200;300;400;500;600;700&family=Vazirmatn:wght@100..900&display=swap" rel="stylesheet">
<meta http-equiv="refresh" content="30">

<style>
:root {
  --border: rgba(255,255,255,.12);
  --muted: #aab5c6;
  --accent: #ff7a1a;
}
body {
  margin: 0;
  padding: 16px 16px calc(16px + env(safe-area-inset-bottom) + 72px);
  min-height: 100dvh;
  font-family: 'Bai Jamjuree','Vazirmatn',sans-serif;
  color: #e8eef7;
  background: linear-gradient(180deg, #0a111a 0%, #0b0f16 30%, #0a1118 100%);
}
.container { max-width: 900px; margin: 0 auto; }
.card {
  background: linear-gradient(180deg, rgba(76, 175, 80, 0.06), rgba(76, 175, 80, 0.06));
  border: 1px solid var(--border);
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0,0,0,.25);
}
.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  direction: ltr;
}
.brand {
  background: linear-gradient(90deg, #2E7D32 0%, #4CAF50 40%, #B2FF59 75%, #E8FFF7 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  filter: drop-shadow(0 2px 10px rgba(76,175,80,.25));
}
.event-card {
  display: flex;
  flex-direction: column;
  padding: 12px 16px;
  margin-bottom: 8px;
}
.event-header { display: flex; justify-content: center; margin-bottom: 8px; }
.event-body { display: flex; align-items: center; justify-content: space-between; }
.event-left { display: flex; align-items: center; gap: 10px; }
.event-right { font-size: 14px; color: var(--muted); }
.player-cell { display: flex; flex-direction: column; gap: 2px; }
.player-name { font-size: 14px; font-weight: 500; }
.assist-name { font-size: 12px; color: var(--muted); }
/*.live-score-box {*/
/*    background: rgba(10,17,26,.85);*/
/*    border: 1px solid rgba(255,255,255,0.1);*/
/*    border-radius: 6px;*/
/*    padding: 15px;*/
/*    margin-bottom: 20px;*/
/*    box-shadow: 0 4px 15px rgba(0,0,0,0.3);*/
/*}*/
.tag { font-size: 12px; color: var(--accent); margin-right: 4px; }
.team-name { font-size: 14px; font-weight: bold; color: #4CAF50; }
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 50;
  background: rgba(10,17,26,.85);
  border-top: 1px solid var(--border);
  backdrop-filter: blur(8px);
}
.bottom-nav .wrap {
  display: flex;
  justify-content: space-between;
  gap: 4px;
}
.bottom-nav a.item {
  flex: 1;
  padding: 8px 0 10px;
  text-align: center;
  font-size: 12px;
  color: var(--muted);
  text-decoration: none;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}
.bottom-nav a.item i { font-size: 18px; }
.bottom-nav a.item.active { color: #4CAF50; }
.bottom-nav .safe { height: env(safe-area-inset-bottom); }
</style>
</head>
<body>
<div class="container">
    <!-- Header -->
    <header class="card header-bar px-4 py-3">
        <h1 class="text-xl md:text-2xl brand font-extrabold">LiveCube</h1>
    </header>

    <!-- عنوان صفحه -->
    <div class="card flex items-center justify-between" style="padding:20px 16px; margin-top:14px">
        <span class="text-lg font-semibold text-gray-200">رویدادهای بازی</span>
    </div>
    
        <!-- نتیجه لایو بازی -->
        <?php if ($currentMatch): ?>
        <div class="card mt-4 p-4 mb-3 text-center" style="background: linear-gradient(135deg, rgba(20,46,30,.9), rgba(45,85,60,.85)); border: 1px solid rgba(255,255,255,0.1);">
            <div class="flex justify-between items-center mb-2">
                <!-- تیم خانگی -->
                <div class="flex items-center" style="flex: 1; justify-content: flex-start;">
                    <?php if (!empty($currentMatch['T1'][0]['Img'])): ?>
                    <img src="https://lsm-static-prod.livescore.com/medium/<?= $currentMatch['T1'][0]['Img'] ?>" 
                         style="width: 30px; height: 30px; margin-left: 10px;">
                    <?php endif; ?>
                    <div class="text-sm font-bold "><?= htmlspecialchars(getTeamName($homeTeamName)) ?></div>
                </div>
                
<?php
$st = $currentMatch['Eps'] ?? '';
$tr1 = (string)($currentMatch['Tr1'] ?? '0');
$tr2 = (string)($currentMatch['Tr2'] ?? '0');
$s1  = convertToPersianNumbers($tr1);
$s2  = convertToPersianNumbers($tr2);

// اگر بازی به پنالتی رسیده، اسکور پنالتی را در پرانتز کنار نتیجه اصلی نشان بده
if (in_array($st, ['AP','PEN','FT_PEN'], true) && isset($currentMatch['Trp1'], $currentMatch['Trp2'])) {
    $p1 = convertToPersianNumbers((string)$currentMatch['Trp1']);
    $p2 = convertToPersianNumbers((string)$currentMatch['Trp2']);
    $s1 .= " ({$p1})";
    $s2 .= " ({$p2})";
}
?>
<div class="text-xl font-bold " style="margin: 0 15px;">
    <?= $s1 ?> - <?= $s2 ?>
</div>
                
                <!-- تیم میهمان -->
                <div class="flex items-center" style="flex: 1; justify-content: flex-end;">
                    <div class="text-sm font-bold"><?= htmlspecialchars(getTeamName($awayTeamName)) ?></div>
                    <?php if (!empty($currentMatch['T2'][0]['Img'])): ?>
                    <img src="https://lsm-static-prod.livescore.com/medium/<?= $currentMatch['T2'][0]['Img'] ?>" 
                         style="width: 30px; height: 30px; margin-right: 10px;">
                    <?php endif; ?>
                </div>
            </div>
        
        <!-- وضعیت بازی -->
        <div class="text-xs" style="color: #aab5c6; margin-top: 8px;">
            <?php
            $status = $currentMatch['Eps'] ?? '';
            $minute = $currentMatch['Min'] ?? '';
            
            // دیباگ: تمام فیلدهای مربوطه رو چک کنیم
            error_log("Match status fields - Eps: " . ($currentMatch['Eps'] ?? 'N/A') . 
                      ", Min: " . ($currentMatch['Min'] ?? 'N/A') . 
                      ", Ewt: " . ($currentMatch['Ewt'] ?? 'N/A'));
            
            // اگر Eps شامل دقیقه هست (مثل "52'")
            if (preg_match('/^(\d+)\'?$/', $status, $matches)) {
                $minuteValue = $matches[1];
                echo convertToPersianNumbers($minuteValue) . ' دقیقه';
            }
            elseif ($status === 'FT') {
                echo 'پایان بازی';
            }
            elseif ($status === 'HT') {
                echo 'نیمه اول';
            }
            elseif ($status === 'NS') {
                echo 'شروع نشده';
            }
            elseif (!empty($minute) && $minute != '0') {
                echo convertToPersianNumbers($minute) . ' دقیقه';
            }
            else {
                echo 'در حال بازی';
            }
            ?>
        </div>
        
        </div>
        <?php endif; ?>


    <!-- رویدادها -->
    <div style="margin-top:14px;">
        <?php if (isset($error_message)): ?>
            <div class="card text-[var(--muted)] p-4">📭 <?= htmlspecialchars($error_message) ?></div>
        <?php elseif ($raw): ?>
            <div class="card p-4"><pre class="text-[var(--muted)]"><?= htmlspecialchars(json_encode($incData, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT)) ?></pre></div>
        <?php else: ?>
            <?php foreach ($incs as $index => $ev): ?>
                <?php
                // مقداردهی اولیه متغیرها
                $scorerName = '—';
                $assistName = null;
                
                // دقیقه
                $min   = $ev['Min'] ?? $ev['minute'] ?? null;
                $minEx = $ev['MinEx'] ?? $ev['extra'] ?? null;
                $minStr = $min !== null ? (string)$min : '';
                if ($minEx && $minEx > 0) $minStr .= " +$minEx";
                if ($minStr !== '') $minStr .= "'";
                $minStr = convertToPersianNumbers($minStr);

                // اسکور لحظه‌ای
                $sc = $ev['Sc'] ?? $ev['score'] ?? null;
                $score = '';
                $hasScore = false;
                
                if (is_array($sc) && count($sc) >= 2) { 
                    $score = $sc[0] . ' - ' . $sc[1]; 
                    $hasScore = true; 
                } elseif (is_string($sc) && $sc !== '') { 
                    $score = $sc; 
                    $hasScore = true; 
                }

                // نوع رویداد
                $it = pick($ev, ['IT','type','Type','IncType','EvType'], null);
                $etype = map_event_type($it, $hasScore);
// --- VAR مردود ---
if ($etype['key'] === 'GOAL' && looks_var_disallowed($ev)) {
    $etype = ['key'=>'VAR_NO_GOAL','emoji'=>'❌','tag'=>'VAR'];
    $score = ''; $hasScore = false;
}

// --- پنالتیِ گل‌نشده ---
// هم خودِ رویداد و هم Incs تودرتو را بررسی کن
$penMiss = looks_penalty_missed($ev);
if (!$penMiss && isset($ev['Incs']) && is_array($ev['Incs'])) {
    foreach ($ev['Incs'] as $inc) {
        if (is_array($inc) && looks_penalty_missed($inc)) { $penMiss = true; break; }
    }
}
if ($penMiss) {
    $etype = ['key'=>'PEN_MISS','emoji'=>'❌','tag'=>'PEN'];
    $score = ''; $hasScore = false;
}
                
                // بررسی اگر رویداد دارای ساختار تودرتو (Incs) است
                if (isset($ev['Incs']) && is_array($ev['Incs'])) {
                    foreach ($ev['Incs'] as $inc) {
                        if (!is_array($inc)) continue;
                        
                        $incType = $inc['IT'] ?? null;
                        
                        // گلزن (IT: 36)
                        if ($incType == 36) {
                            $scorerName = $inc['Pn'] ?? __nm($inc) ?? '—';
                            if ($scorerName === '—' && isset($inc['ID']) && isset($playerMap[(string)$inc['ID']])) {
                                $scorerName = $playerMap[(string)$inc['ID']];
                            }
                        }
                        
                        // پاسور (IT: 63)
                        if ($incType == 63 && empty($assistName)) {
                            $assistName = $inc['Pn'] ?? __nm($inc) ?? null;
                            if (empty($assistName) && isset($inc['ID']) && isset($playerMap[(string)$inc['ID']])) {
                                $assistName = $playerMap[(string)$inc['ID']];
                            }
                        }
                    }
                } else {
                    // پردازش رویدادهای معمولی
                    $scorerName = $ev['Pn'] ?? $ev['PlayerName'] ?? '—';
                    
                    if (isset($ev['Pl']) && is_array($ev['Pl'])) {
                        foreach ($ev['Pl'] as $playerIndex => $player) {
                            if (!is_array($player)) continue;
                            
                            $playerId = __pid($player);
                            $playerName = __nm($player);
                            
                            if ($playerIndex === 0 && ($scorerName === '—' || empty($scorerName))) {
                                $scorerName = $playerName ?: (isset($playerMap[$playerId]) ? $playerMap[$playerId] : '—');
                            } 
                            elseif ($playerIndex === 1 && empty($assistName)) {
                                $assistName = $playerName ?: (isset($playerMap[$playerId]) ? $playerMap[$playerId] : null);
                            }
                        }
                    }
                    
                    if ($scorerName === '—') {
                        $scorerId = $ev['ID'] ?? $ev['Pid'] ?? $ev['playerId'] ?? null;
                        if ($scorerId && isset($playerMap[(string)$scorerId])) {
                            $scorerName = $playerMap[(string)$scorerId];
                        }
                    }
                    
                    if (empty($assistName)) {
                        $assistId = $ev['Aid'] ?? $ev['assistId'] ?? $ev['AssistId'] ?? null;
                        if ($assistId && isset($playerMap[(string)$assistId])) {
                            $assistName = $playerMap[(string)$assistId];
                        }
                    }
                }
                
                // تیم - روش دقیق بر اساس فیلد Nm
                $team = $homeTeamName; // پیش‌فرض
                
                // استفاده از فیلد Nm که مستقیماً تیم رو مشخص می‌کنه
                if (isset($ev['Nm'])) {
                    if ($ev['Nm'] == 1) {
                        $team = $homeTeamName;
                    } elseif ($ev['Nm'] == 2) {
                        $team = $awayTeamName;
                    }
                }
                // برای رویدادهای تودرتو (گل‌ها)
                elseif (isset($ev['Incs']) && is_array($ev['Incs'])) {
                    foreach ($ev['Incs'] as $inc) {
                        if (isset($inc['Nm'])) {
                            if ($inc['Nm'] == 1) {
                                $team = $homeTeamName;
                                break;
                            } elseif ($inc['Nm'] == 2) {
                                $team = $awayTeamName;
                                break;
                            }
                        }
                    }
                }

                ?>
                <div class="card event-card">
                    <?php if ($team): ?>
                        <div class="event-header">
                            <span class="team-name"><?= htmlspecialchars(getTeamName($team)) ?></span>
                        </div>
                    <?php endif; ?>
                    <div class="event-body">
                        <div class="event-left">
                            <span><?= $etype['emoji'] ?></span>
                            <div class="player-cell">
                                <span class="player-name">
                                    <?php if ($etype['tag']): ?>
                                        <span class="tag"><?= htmlspecialchars($etype['tag']) ?></span>
                                    <?php endif; ?>
                                    <?= htmlspecialchars($scorerName) ?>
                                </span>
                                <?php if ($assistName): ?>
                                    <span class="assist-name">↳ پاس: <?= htmlspecialchars($assistName) ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="event-right"><?= htmlspecialchars(convertToPersianNumbers($minStr)) ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
    
    <script>
    // رفرش خودکار هر 30 ثانیه
    setTimeout(function() {
        window.location.reload();
    }, 30000);
    </script>

<?php $active='incidents'; include __DIR__.'/parts/bottom-nav.php'; ?>
</body>
</html>