<?php 
/**
 * games.php — MLB GAME BOXSCORE
 */

ini_set('display_errors', 1);
error_reporting(E_ALL); 

require_once '../connection.php';
require_once 'navbar.php';
$currentSeason = $season ?? date('Y');
$mysqli = get_mysql_connection();
$mysqli->set_charset('utf8mb4');

/* ---------------- INPUT ---------------- */
$gameId  = (int)($_GET['gameid'] ?? 0);
$gamePk  = (int)($_GET['gamepk'] ?? 0);

if ($gameId <= 0) {
    die("❌ Invalid game ID");
}

 
/* ---------------- GAME HEADER ---------------- */
$stmt = $mysqli->prepare("
    SELECT 
        GamePk, Season, GameDate,
        HomeTeam, AwayTeam,
        HomeScore, AwayScore, Venue,
        WinningPitcher, LosingPitcher, SavePitcher, BlownSavePitcher,
        HomeTeamFranchise, AwayTeamFranchise   -- ✅ ADD THIS
    FROM MLB_Games
    WHERE GameID = ?
    LIMIT 1
");

$stmt->bind_param("i", $gameId);   // ✅ GameID used here
$stmt->execute();
$game = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$game) {
    die("<h3>❌ Game not found</h3>");
}
$season = (int)$game['Season'];


// ✅ NOW we can safely read GamePk
$gamePk = (int)$game['GamePk'];

/* =====================================================
   MLB API — BATTING / BASERUNNING / FIELDING SUMMARY
   (NON-DESTRUCTIVE ADDITION)
===================================================== */

$mlbSummary = [
    'home' => [
        '2B'=>[], '3B'=>[], 'HR'=>[],
        'RBI'=>0, 'RBI2'=>0,
        'SB'=>[], 'GIDP'=>[], 'SF'=>[],
        'Errors'=>[],
        'RISP_AB'=>0, 'RISP_H'=>0,
        'LOB'=>0
    ],
    'away' => [
        '2B'=>[], '3B'=>[], 'HR'=>[],
        'RBI'=>0, 'RBI2'=>0,
        'SB'=>[], 'GIDP'=>[], 'SF'=>[],
        'Errors'=>[],
        'RISP_AB'=>0, 'RISP_H'=>0,
        'LOB'=>0
    ]
];

function hasRISP_API($runners) {
    foreach ($runners as $r) {
        if (in_array($r['movement']['start'] ?? '', ['2B','3B'])) {
            return true;
        }
    }
    return false;
}

$feedUrl = "https://statsapi.mlb.com/api/v1.1/game/$gamePk/feed/live";
$feed = @json_decode(file_get_contents($feedUrl), true);
$attendance = $feed['gameData']['gameInfo']['attendance'] ?? null;
$plays = $feed['liveData']['plays']['allPlays'] ?? [];

/* =====================================================
   OFFICIAL MLB BOXSCORE DISPLAY ORDER
   Use the MLB live-feed boxscore only for display order.
   Database tables remain the source for all statistics.
===================================================== */
$officialBatterOrder = ['home'=>[], 'away'=>[]];
$officialPitcherOrder = ['home'=>[], 'away'=>[]];

foreach (['away', 'home'] as $side) {
    $boxTeam = $feed['liveData']['boxscore']['teams'][$side] ?? [];

    // MLB supplies batters in official boxscore order, including substitutes.
    foreach (($boxTeam['batters'] ?? []) as $idx => $playerId) {
        $officialBatterOrder[$side][(int)$playerId] = $idx;
    }

    // MLB supplies pitchers in the order they appeared in the game.
    foreach (($boxTeam['pitchers'] ?? []) as $idx => $playerId) {
        $officialPitcherOrder[$side][(int)$playerId] = $idx;
    }
}

$lastRunners = ['home'=>[], 'away'=>[]];
$prevRunners = ['home'=>[], 'away'=>[]];
$prevOuts    = ['home'=>0,  'away'=>0];


foreach ($plays as $play) {
    $currentOuts = $play['count']['outs'] ?? 0;
    $half = $play['about']['halfInning'] ?? '';
    if (!in_array($half, ['top','bottom'])) continue;
    $side = ($half === 'top') ? 'away' : 'home';

    $event   = $play['result']['eventType'] ?? '';
    $outs    = $play['count']['outs'] ?? 0;
    $rbi     = $play['result']['rbi'] ?? 0;
    $runners = $play['runners'] ?? [];

    /* ---------- AT-BAT EVENTS ---------- */
    if (($play['result']['type'] ?? '') === 'atBat') {

        $batter = $play['matchup']['batter']['fullName'] ?? '';

        $isRISP = hasRISP_API($runners);
        if ($isRISP) $mlbSummary[$side]['RISP_AB']++;

        switch ($event) {
            case 'double':
                $mlbSummary[$side]['2B'][] = $batter;
                if ($isRISP) $mlbSummary[$side]['RISP_H']++;
                break;

            case 'triple':
                $mlbSummary[$side]['3B'][] = $batter;
                if ($isRISP) $mlbSummary[$side]['RISP_H']++;
                break;

            case 'home_run':
                $mlbSummary[$side]['HR'][] = $batter;
                if ($isRISP) $mlbSummary[$side]['RISP_H']++;
                break;

            case 'double_play':
                $mlbSummary[$side]['GIDP'][] = $batter;
                break;

            case 'sac_fly':
                $mlbSummary[$side]['SF'][] = $batter;
                break;
        }

        $mlbSummary[$side]['RBI'] += $rbi;
        if ($outs === 2) $mlbSummary[$side]['RBI2'] += $rbi;
    }

    /* ---------- STOLEN BASE ---------- */
    if ($event === 'stolen_base') {
        $runner = $play['runners'][0]['details']['runner']['fullName'] ?? '';
        if ($runner) {
            $runnerTeam = ($play['about']['halfInning'] === 'top') ? 'away' : 'home';
            $mlbSummary[$runnerTeam]['SB'][] = $runner;
        }
    }


    /* ---------- ERROR ---------- */
    if ($event === 'error') {
        $fielder = $play['matchup']['batter']['fullName'] ?? '';
        if ($fielder) $mlbSummary[$side]['Errors'][] = $fielder;
    }

    /* ---------- END OF INNING LOB ---------- */
    // Track runners before inning ends
// ✅ LOB: count runners from the PREVIOUS play when 3rd out is recorded
    if ($prevOuts[$side] < 3 && $currentOuts === 3) {
        foreach ($prevRunners[$side] as $r) {
            if (!($r['movement']['isOut'] ?? true)) {
                $mlbSummary[$side]['LOB']++;
            }
        }
    }

// Save state for next iteration
$prevRunners[$side] = $play['runners'] ?? [];
$prevOuts[$side]    = $currentOuts;


}



 
/* ---------------- BATTER BOXSCORES ---------------- */
$stmt = $mysqli->prepare("
SELECT
    b.GameID,
    b.Team,
    b.TeamFranchise,   -- ✅ ADD THIS
    b.PlayerID,
    b.PlayerName,
    COALESCE(l.position, b.Position) AS Position,
    COALESCE(CAST(l.batting_order AS UNSIGNED), 99) AS LineupOrder,
    b.AtBats, b.Runs, b.Hits,
    b.Doubles, b.Triples, b.HomeRuns,
    b.RBIs, b.Walks, b.StrikeOuts

    FROM MLB_BatterBoxscores b
    LEFT JOIN MLB_Lineups l
      ON l.game_id = b.GameID
     AND l.player_id = b.PlayerID
     AND l.TeamNameFranchise = b.Team

    WHERE b.GameID = ?
  

    ORDER BY
        b.Team,
        LineupOrder,
        b.PlayerName
");
$stmt->bind_param("i", $gamePk);
$stmt->execute();
$res = $stmt->get_result();



$batting = ['home'=>[], 'away'=>[]];

 
while ($r = $res->fetch_assoc()) {
    if (
        ($r['TeamFranchise'] ?? '') === ($game['HomeTeamFranchise'] ?? '')
    ) {
        $batting['home'][] = $r;
    } elseif (
        ($r['TeamFranchise'] ?? '') === ($game['AwayTeamFranchise'] ?? '')
    ) {
        $batting['away'][] = $r;
    } else {
        // fallback (safety)
        if (trim($r['Team']) === trim($game['HomeTeam'])) {
            $batting['home'][] = $r;
        } else {
            $batting['away'][] = $r;
        }
    }
}    
$stmt->close();

// Re-sort batters to match the official MLB boxscore appearance order.
foreach (['away', 'home'] as $side) {
    usort($batting[$side], function ($a, $b) use ($officialBatterOrder, $side) {
        $aId = (int)($a['PlayerID'] ?? 0);
        $bId = (int)($b['PlayerID'] ?? 0);
        $aOrder = $officialBatterOrder[$side][$aId] ?? PHP_INT_MAX;
        $bOrder = $officialBatterOrder[$side][$bId] ?? PHP_INT_MAX;

        if ($aOrder !== $bOrder) {
            return $aOrder <=> $bOrder;
        }

        // Fallback if a player is missing from the live feed.
        $aLineup = (int)($a['LineupOrder'] ?? 9999);
        $bLineup = (int)($b['LineupOrder'] ?? 9999);
        if ($aLineup !== $bLineup) {
            return $aLineup <=> $bLineup;
        }

        return strcmp((string)($a['PlayerName'] ?? ''), (string)($b['PlayerName'] ?? ''));
    });
}


/* ---------------- PITCHER BOXSCORES ---------------- */
$stmt = $mysqli->prepare("
    SELECT *
    FROM MLB_PitcherBoxscores
    WHERE GameID = ?
   
    ORDER BY TeamName, PlayerName
");
$stmt->bind_param("i", $gameId);
$stmt->execute();
$res = $stmt->get_result();

$pitching = ['home'=>[], 'away'=>[]];
while ($r = $res->fetch_assoc()) {
   if (trim($r['TeamName']) == trim($game['HomeTeam'])) {
        $pitching['home'][] = $r;
    } else {
        $pitching['away'][] = $r;
    }
}
$stmt->close();

// Re-sort pitchers to match the exact order they entered the game.
foreach (['away', 'home'] as $side) {
    usort($pitching[$side], function ($a, $b) use ($officialPitcherOrder, $side) {
        $aId = (int)($a['PlayerID'] ?? 0);
        $bId = (int)($b['PlayerID'] ?? 0);
        $aOrder = $officialPitcherOrder[$side][$aId] ?? PHP_INT_MAX;
        $bOrder = $officialPitcherOrder[$side][$bId] ?? PHP_INT_MAX;

        if ($aOrder !== $bOrder) {
            return $aOrder <=> $bOrder;
        }

        return strcmp((string)($a['PlayerName'] ?? ''), (string)($b['PlayerName'] ?? ''));
    });
}

/* ---------------- OFFICIAL LINE SCORE (INNINGS) ---------------- */

$lineScore = ['away' => [], 'home' => []];
$innings = [];

$stmt = $mysqli->prepare("
    SELECT Inning, Half, Runs
    FROM MLB_GamesLineScore
    WHERE GamePk = ?
      AND Season = ?
    ORDER BY Inning, Half
");

$stmt->bind_param("ii", $gamePk, $season);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $inning = (int)$row['Inning'];
    $half   = $row['Half']; // 'top' or 'bottom'
    $runs   = (int)$row['Runs'];

    $innings[$inning] = true;

    if ($half === 'top') {
        $lineScore['away'][$inning] = $runs;
    } else {
        $lineScore['home'][$inning] = $runs;
    }
}
$stmt->close();


// Ensure both teams have values for all innings
foreach (array_keys($innings) as $inning) {
  if (!array_key_exists($inning, $lineScore['away'])) {
        $lineScore['away'][$inning] = 'x';
    }
    if (!array_key_exists($inning, $lineScore['home'])) {
        $lineScore['home'][$inning] = 'x';
    }
}  

// 🧠 Baseball rule: home team does not bat bottom 9 if leading
if (
    isset($lineScore['away'][9]) &&
    $game['HomeScore'] > $game['AwayScore']
) {
    $lineScore['home'][9] = 'x';
}


ksort($lineScore['away']);
ksort($lineScore['home']);




/* ---------------- OFFICIAL LINE SCORE TOTALS ---------------- */

$awayTotals = ['Runs'=>0,'Hits'=>0,'Errors'=>0];
$homeTotals = ['Runs'=>0,'Hits'=>0,'Errors'=>0];

$stmt = $mysqli->prepare("
    SELECT IsHome, Runs, Hits, Errors
    FROM MLB_GamesLineScoreTotals
    WHERE GamePk = ?
      AND Season = ?
");
$stmt->bind_param("ii", $gamePk, $season);
$stmt->execute();

$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    if ((int)$row['IsHome'] === 1) {
        $homeTotals = $row;
    } else {
        $awayTotals = $row;
    }
}
$stmt->close();


 

 
 




/* =====================================================
   RENDER HELPERS
===================================================== */
function formatBatterName($r) {
    $playerId = (int)$r['PlayerID'];
    $name = htmlspecialchars($r['PlayerName'], ENT_QUOTES);
    $pos  = $r['Position'] ? ' ' . htmlspecialchars($r['Position']) : '';

    // Starters: 100,200,...900
    // Subs:     101,201,301,...
    if ((int)$r['LineupOrder'] % 100 == 1) {
        $name = 'a-' . $name;
    }

    return "<a href='player.php?playerid={$playerId}'>{$name}</a>{$pos}";
}




function gameAVG($h, $ab) {
    return $ab > 0 ? number_format($h / $ab, 3) : '.000';
}

function gameOPS($h, $bb, $ab, $d, $t, $hr) {
    if ($ab <= 0) return '.000';

    $tb  = ($h - $d - $t - $hr) + (2 * $d) + (3 * $t) + (4 * $hr);
    $obp = ($h + $bb) / ($ab + $bb);
    $slg = $tb / $ab;

    return number_format($obp + $slg, 3);
}
function renderMLBSummary($teamName, $s) {
    echo "<h5 class='mt-4'>$teamName — Game Summary</h5><pre>";

    if ($s['2B']) echo "2B " . implode('; ', $s['2B']) . "\n";
    if ($s['3B']) echo "3B " . implode('; ', $s['3B']) . "\n";
    if ($s['HR']) echo "HR " . implode('; ', $s['HR']) . "\n";

    echo "RBI {$s['RBI']} (2-out {$s['RBI2']})\n";

    if ($s['SB']) echo "SB " . implode('; ', $s['SB']) . "\n";
    if ($s['GIDP']) echo "GIDP " . implode('; ', $s['GIDP']) . "\n";
    if ($s['SF']) echo "SF " . implode('; ', $s['SF']) . "\n";
    if ($s['Errors']) echo "E " . implode('; ', $s['Errors']) . "\n";

    echo "Team RISP {$s['RISP_H']}-for-{$s['RISP_AB']}\n";
    echo "Team LOB {$s['LOB']}\n";
    echo "</pre>";
}

 


function renderBatting($team, $rows) {
    if (!$rows) return;

    $tot = ['AB'=>0,'R'=>0,'H'=>0,'RBI'=>0,'BB'=>0,'K'=>0];

    echo "<h4 class='mt-4'>$team — Batting</h4>";
    echo "<div class='table-responsive'>";
    echo "<table class='table table-bordered stat-table'>";
    echo "<thead>
        <tr>
        <th>Batter</th><th>AB</th><th>R</th><th>H</th>
        <th>RBI</th><th>BB</th><th>K</th>
        <th>AVG</th><th>OPS</th>
        </tr>
    </thead><tbody>";
     
    foreach ($rows as $r) {
            if (
        (int)$r['AtBats'] === 0 &&
        (int)$r['Walks'] === 0 &&
        (int)$r['Hits'] === 0 &&
        (int)$r['RBIs'] === 0
    ) {
        continue;

    }
 
        echo "<tr>
            <td>" . formatBatterName($r) . "</td>
            <td>{$r["AtBats"]}</td>
            <td>{$r["Runs"]}</td>
            <td>{$r["Hits"]}</td>
            <td>{$r["RBIs"]}</td>
            <td>{$r["Walks"]}</td>
            <td>{$r["StrikeOuts"]}</td>
            <td>" . gameAVG($r['Hits'], $r['AtBats']) . "</td>
            <td>" . gameOPS(
        $r['Hits'],
        $r['Walks'],
        $r['AtBats'],
        $r['Doubles'],
        $r['Triples'],
        $r['HomeRuns']
    ) . "</td>
        </tr>";

        $tot['AB']  += $r['AtBats'];
        $tot['R']   += $r['Runs'];
        $tot['H']   += $r['Hits'];
        $tot['RBI'] += $r['RBIs'];
        $tot['BB']  += $r['Walks'];
        $tot['K']   += $r['StrikeOuts'];
    }

    echo "<tr class='table-dark'>
        <td><b>Totals</b></td>
        <td>{$tot['AB']}</td>
        <td>{$tot['R']}</td>
        <td>{$tot['H']}</td>
        <td>{$tot['RBI']}</td>
        <td>{$tot['BB']}</td>
        <td>{$tot['K']}</td>
        <td></td><td></td>
    </tr>";

    echo "</tbody></table></div>";
}


function renderPitching($team, $rows) {
    if (!$rows) return;

    echo "<h4 class='mt-3'>$team — Pitching</h4>";
    echo "<div class='table-responsive'>";
    echo "<table class='table table-bordered stat-table'>";
    echo "<thead>
        <tr>
        <th>Pitcher</th><th>IP</th><th>H</th><th>R</th>
        <th>ER</th><th>BB</th><th>K</th><th>HR</th><th>P</th>
        </tr>
    </thead><tbody>";

    foreach ($rows as $r) {
    

    // Skip pitchers with no recorded stats

        $playerId = (int)$r['PlayerID'];
        $name = htmlspecialchars($r['PlayerName'], ENT_QUOTES);
            if (
        (float)$r['InningsPitched'] == 0 &&
        (int)$r['Pitches'] == 0
    ) {
        continue;
    }
    
        echo "<tr>
            <td>
                <a href='player.php?playerid={$playerId}'>{$name}</a>
            </td>
            <td>{$r['InningsPitched']}</td>
            <td>{$r['Hits']}</td>
            <td>{$r['Runs']}</td>
            <td>{$r['EarnedRuns']}</td>
            <td>{$r['Walks']}</td>
            <td>{$r['StrikeOuts']}</td>
            <td>{$r['HomeRuns']}</td>
            <td>{$r['Pitches']}</td>
        </tr>";
    }


    echo "</tbody></table></div>";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= htmlspecialchars($game['AwayTeam']) ?> @ <?= htmlspecialchars($game['HomeTeam']) ?></title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
.stat-table th {
    position: sticky;
    top: 0;
    background: #212529;
    color: #fff;
}
.stat-table td {
    text-align: center;
    white-space: nowrap;
}
/* Line score totals (R / H / E) */
.line-score-totals {
    color: #198754; /* Bootstrap green */
    font-weight: bold;
}

</style>
</head>
<body>

<div class="container-fluid">

<h2>
<?= htmlspecialchars($game['AwayTeam']) ?> @ <?= htmlspecialchars($game['HomeTeam']) ?>
</h2>

<h3 class="mb-4">
    <span><?= (int)$game['AwayScore'] ?> – <?= (int)$game['HomeScore'] ?></span>
</h3> 
<h3 class="mb-4">
    <span class="pitcher">wp: <?= htmlspecialchars($game['WinningPitcher'] ?? '') ?></span>
    <span class="pitcher">lp: <?= htmlspecialchars($game['LosingPitcher'] ?? '') ?></span>

    <?php if (!empty($game['SavePitcher'] ?? '')): ?>
        <span class="pitcher">save: <?= htmlspecialchars($game['SavePitcher']) ?></span>
    <?php endif; ?>

    <?php if (!empty($game['BlownSavePitcher'] ?? '')): ?>
        <span class="pitcher">bs: <?= htmlspecialchars($game['BlownSavePitcher']) ?></span>
    <?php endif; ?>
</h3>




<div class="mb-2 text-success">
    <?= htmlspecialchars($game['GameDate']) ?> • <?= htmlspecialchars($game['Venue']) ?>
    <?php if ($attendance): ?>
        • Attendance: <?= number_format($attendance) ?>
    <?php endif; ?>
</div>

 
<div>
    
</div>

<table class="table table-bordered text-center mb-4">
    <thead class="table-dark">
        <tr>
            <th>Team</th>
            <?php foreach (array_keys($lineScore['away']) as $inning): ?>
                <th><?= $inning ?></th>
            <?php endforeach; ?>
            <th>R</th>
            <th>H</th>
            <th>E</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><strong><?= htmlspecialchars($game['AwayTeam']) ?></strong></td>
            <?php foreach ($lineScore['away'] as $runs): ?>
                <td><?= $runs ?></td>
            <?php endforeach; ?>
            <td class="line-score-totals"><?= $awayTotals['Runs'] ?></td>
            <td class="line-score-totals"><?= $awayTotals['Hits'] ?></td>
            <td class="line-score-totals"><?= $awayTotals['Errors'] ?></td>


        </tr>
        <tr>
            <td><strong><?= htmlspecialchars($game['HomeTeam']) ?></strong></td>
            <?php foreach ($lineScore['home'] as $runs): ?>
                <td><?= $runs ?></td>
            <?php endforeach; ?>
            <td class="line-score-totals"><?= $homeTotals['Runs'] ?></td>
            <td class="line-score-totals"><?= $homeTotals['Hits'] ?></td>
            <td class="line-score-totals"><?= $homeTotals['Errors'] ?></td>


        </tr>
    </tbody>
</table>
 

<?php
// ✅ MLB-style game summary FIRST
renderMLBSummary($game['AwayTeam'], $mlbSummary['away']);
renderMLBSummary($game['HomeTeam'], $mlbSummary['home']);

// ✅ Then your existing tables (unchanged)
renderBatting($game['AwayTeam'], $batting['away']);
renderPitching($game['AwayTeam'], $pitching['away']);

renderBatting($game['HomeTeam'], $batting['home']);
renderPitching($game['HomeTeam'], $pitching['home']);
?>



</div>
</body>
</html>

<?php $mysqli->close(); ?>
