<?php
require_once '../core/bootstrap.php';

$fixture_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$fixture_id) {
    header('Location: matches.php');
    exit();
}

$fixtureModel = new Fixture();
$eventModel = new MatchEvent();
$playerModel = new Player();
$lineupModel = new Lineup();
$statsModel = new Stats();
$settingModel = new Setting();

$fixture = $fixtureModel->findById($fixture_id);

if (!$fixture) {
    header('Location: matches.php');
    exit();
}

$pageTitle = "Match Report: " . $fixture->home_team_name . " vs " . $fixture->away_team_name;
include 'includes/header.php';

$events = $eventModel->getEventsForFixture($fixture_id);
$player_names = $playerModel->getPlayerNamesForFixture($fixture_id);
$stats = $statsModel->getStatsForFixture($fixture_id);
$home_lineup = $lineupModel->getLineupForFixture($fixture_id, $fixture->home_team_id);
$away_lineup = $lineupModel->getLineupForFixture($fixture_id, $fixture->away_team_id);
$settings = $settingModel->getAll();

function getPlayerName($id, $names) {
    return htmlspecialchars($names[$id] ?? 'Unknown');
}
?>

<div class="match-report-container">
    <!-- Report Header -->
    <div class="report-header">
        <div class="league-info"><?php echo htmlspecialchars($fixture->league_name ?? 'League Match'); ?> - Gameweek <?php echo $fixture->gameweek; ?></div>
        <div class="score-board">
            <div class="team home">
                <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" alt="">
                <h2><?php echo htmlspecialchars($fixture->home_team_name); ?></h2>
            </div>
            <div class="score-display">
                <span class="score"><?php echo $fixture->home_team_score; ?> - <?php echo $fixture->away_team_score; ?></span>
                <span class="status">Full Time</span>
            </div>
            <div class="team away">
                <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" alt="">
                <h2><?php echo htmlspecialchars($fixture->away_team_name); ?></h2>
            </div>
        </div>
        <div class="match-meta">
            <span><i class="fa-regular fa-calendar"></i> <?php echo date('d M Y', strtotime($fixture->match_datetime)); ?></span>
            <span><i class="fa-solid fa-location-dot"></i> <?php echo htmlspecialchars($fixture->venue); ?></span>
            <span><i class="fa-solid fa-whistle"></i> <?php echo htmlspecialchars($fixture->referee_name ?? 'N/A'); ?></span>
        </div>
    </div>

    <div class="report-content">
        <!-- Man of the Match -->
        <?php if (!empty($fixture->man_of_the_match_player_id)): ?>
        <div class="motm-card">
            <div class="motm-icon"><i class="fa-solid fa-star"></i></div>
            <div class="motm-details">
                <span class="motm-label">Man of the Match</span>
                <span class="motm-name"><?php echo htmlspecialchars($fixture->motm_first_name . ' ' . $fixture->motm_last_name); ?></span>
            </div>
        </div>
        <?php endif; ?>

        <div class="report-grid">
            <!-- Left Column: Stats & Events -->
            <div class="report-col">
                <!-- Match Stats -->
                <div class="report-section">
                    <h3>Match Stats</h3>
                    <?php if ($stats): ?>
                        <div class="stats-list">
                            <?php
                            $stat_keys = [
                                'possession' => 'Possession %',
                                'shots' => 'Shots',
                                'shots_on_target' => 'Shots on Target',
                                'corners' => 'Corners',
                                'fouls' => 'Fouls',
                                'yellow_cards' => 'Yellow Cards',
                                'red_cards' => 'Red Cards'
                            ];
                            foreach ($stat_keys as $key => $label):
                                $h = $stats->home->$key ?? 0;
                                $a = $stats->away->$key ?? 0;
                                $total = $h + $a;
                                $h_pct = $total > 0 ? ($h / $total) * 100 : 50;
                            ?>
                            <div class="stat-item">
                                <div class="stat-values">
                                    <span><?php echo $h; ?></span>
                                    <span class="stat-label"><?php echo $label; ?></span>
                                    <span><?php echo $a; ?></span>
                                </div>
                                <div class="stat-bar-container">
                                    <div class="stat-bar home" style="width: <?php echo $h_pct; ?>%"></div>
                                    <div class="stat-bar away" style="width: <?php echo 100 - $h_pct; ?>%"></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="no-data">No statistics available.</p>
                    <?php endif; ?>
                </div>

                <!-- Match Events -->
                <div class="report-section">
                    <h3>Timeline</h3>
                    <div class="timeline">
                        <?php foreach ($events as $event): 
                            $is_home = $event->team_id == $fixture->home_team_id;
                            $side = $is_home ? 'left' : 'right';
                            $icon = 'fa-circle';
                            $color = '#ccc';
                            
                            switch($event->event_type) {
                                case 'goal': $icon = 'fa-futbol'; $color = '#2ecc71'; break;
                                case 'penalty_scored': $icon = 'fa-futbol'; $color = '#2ecc71'; break;
                                case 'own_goal': $icon = 'fa-futbol'; $color = '#e74c3c'; break;
                                case 'yellow_card': $icon = 'fa-square'; $color = '#f1c40f'; break;
                                case 'red_card': $icon = 'fa-square'; $color = '#e74c3c'; break;
                                case 'substitution': $icon = 'fa-right-left'; $color = '#3498db'; break;
                            }
                        ?>
                        <div class="timeline-item <?php echo $side; ?>">
                            <div class="time"><?php echo $event->minute; ?>'</div>
                            <div class="marker" style="color: <?php echo $color; ?>"><i class="fa-solid <?php echo $icon; ?>"></i></div>
                            <div class="content">
                                <strong><?php echo getPlayerName($event->player_id, $player_names); ?></strong>
                                <small><?php echo ucwords(str_replace('_', ' ', $event->event_type)); ?></small>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Right Column: Lineups -->
            <div class="report-col">
                <div class="report-section">
                    <h3>Lineups</h3>
                    <div class="lineups-grid">
                        <div class="team-lineup">
                            <h4><?php echo htmlspecialchars($fixture->home_team_name); ?></h4>
                            <ul class="lineup-list">
                                <?php if ($home_lineup && !empty($home_lineup->starters)): ?>
                                    <?php foreach ($home_lineup->starters as $pid => $pos): ?>
                                        <li><span class="pos"><?php echo substr($pos, 0, 3); ?></span> <?php echo getPlayerName($pid, $player_names); ?></li>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <li>No lineup available</li>
                                <?php endif; ?>
                            </ul>
                            <h5>Substitutes</h5>
                            <ul class="lineup-list subs">
                                <?php if ($home_lineup && !empty($home_lineup->substitutes)): ?>
                                    <?php foreach ($home_lineup->substitutes as $pid): ?>
                                        <li><?php echo getPlayerName($pid, $player_names); ?></li>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                        </div>
                        <div class="team-lineup">
                            <h4><?php echo htmlspecialchars($fixture->away_team_name); ?></h4>
                            <ul class="lineup-list">
                                <?php if ($away_lineup && !empty($away_lineup->starters)): ?>
                                    <?php foreach ($away_lineup->starters as $pid => $pos): ?>
                                        <li><span class="pos"><?php echo substr($pos, 0, 3); ?></span> <?php echo getPlayerName($pid, $player_names); ?></li>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <li>No lineup available</li>
                                <?php endif; ?>
                            </ul>
                            <h5>Substitutes</h5>
                            <ul class="lineup-list subs">
                                <?php if ($away_lineup && !empty($away_lineup->substitutes)): ?>
                                    <?php foreach ($away_lineup->substitutes as $pid): ?>
                                        <li><?php echo getPlayerName($pid, $player_names); ?></li>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.match-report-container { max-width: 1000px; margin: 0 auto; padding-bottom: 40px; }
.report-header { background: linear-gradient(135deg, #37003c 0%, #580a66 100%); color: white; padding: 40px 20px; border-radius: 0 0 20px 20px; text-align: center; margin-bottom: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }
.league-info { text-transform: uppercase; font-size: 0.9rem; opacity: 0.8; margin-bottom: 20px; letter-spacing: 1px; }
.score-board { display: flex; justify-content: center; align-items: center; gap: 40px; margin-bottom: 20px; }
.team { display: flex; flex-direction: column; align-items: center; width: 150px; }
.team img { width: 80px; height: 80px; object-fit: contain; background: white; border-radius: 50%; padding: 5px; margin-bottom: 10px; }
.team h2 { font-size: 1.1rem; margin: 0; }
.score-display { text-align: center; }
.score-display .score { font-size: 3.5rem; font-weight: 800; display: block; line-height: 1; }
.score-display .status { font-size: 1rem; text-transform: uppercase; background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 15px; }
.match-meta { display: flex; justify-content: center; gap: 20px; font-size: 0.9rem; opacity: 0.9; }
.match-meta span i { margin-right: 5px; }

.report-content { padding: 0 20px; }
.motm-card { background: #fff; border: 1px solid #f1c40f; border-left: 5px solid #f1c40f; padding: 15px 20px; border-radius: 8px; display: flex; align-items: center; gap: 15px; margin-bottom: 30px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
.motm-icon { font-size: 1.5rem; color: #f1c40f; }
.motm-details { display: flex; flex-direction: column; }
.motm-label { font-size: 0.8rem; text-transform: uppercase; color: #7f8c8d; }
.motm-name { font-size: 1.2rem; font-weight: bold; color: #2c3e50; }

.report-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 30px; }
@media (max-width: 768px) { .report-grid { grid-template-columns: 1fr; } .score-board { gap: 10px; } .team img { width: 50px; height: 50px; } .score-display .score { font-size: 2.5rem; } }

.report-section { background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px; }
.report-section h3 { margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 15px; color: #37003c; }

.stat-item { margin-bottom: 15px; }
.stat-values { display: flex; justify-content: space-between; font-size: 0.9rem; font-weight: bold; margin-bottom: 5px; }
.stat-label { color: #7f8c8d; font-weight: normal; }
.stat-bar-container { display: flex; height: 8px; background: #eee; border-radius: 4px; overflow: hidden; }
.stat-bar.home { background: #37003c; }
.stat-bar.away { background: #95a5a6; }

.timeline { position: relative; padding-left: 20px; border-left: 2px solid #eee; }
.timeline-item { position: relative; margin-bottom: 20px; padding-left: 20px; }
.timeline-item .marker { position: absolute; left: -29px; top: 0; background: #fff; width: 16px; height: 16px; text-align: center; font-size: 16px; }
.timeline-item .time { font-weight: bold; color: #37003c; font-size: 0.9rem; }
.timeline-item .content { font-size: 0.9rem; }
.timeline-item .content strong { display: block; }
.timeline-item .content small { color: #7f8c8d; }

.lineups-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.team-lineup h4 { margin-top: 0; color: #37003c; border-bottom: 2px solid #eee; padding-bottom: 5px; }
.team-lineup h5 { margin: 15px 0 5px 0; font-size: 0.9rem; color: #7f8c8d; text-transform: uppercase; }
.lineup-list { list-style: none; padding: 0; margin: 0; font-size: 0.9rem; }
.lineup-list li { padding: 5px 0; border-bottom: 1px solid #f9f9f9; }
.lineup-list .pos { display: inline-block; width: 30px; font-weight: bold; color: #ccc; font-size: 0.8rem; }
</style>

<?php include 'includes/footer.php'; ?>