<?php
$pageTitle = 'News Feed';
include 'includes/header.php';

$type = $_GET['type'] ?? '';
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if (!$type || !$id) {
    header('Location: index.php');
    exit();
}

// --- Instantiate Models ---
$fixtureModel = new Fixture();
$lineupModel = new Lineup();
$playerModel = new Player();
$statsModel = new Stats();
$teamModel = new Team();
$clubModel = new Club();

// --- Content Generation Logic ---
$title = '';
$content = '';
$image = '';
$date = '';

if (in_array($type, ['match_preview', 'match_report', 'lineups_announced'])) {
    $fixture = $fixtureModel->findById($id);
    if (!$fixture) {
        echo "<div class='page-content'><p>Content not found.</p></div>";
        include 'includes/footer.php';
        exit();
    }

    // --- Override Team Names with Club Names ---
    $home_team = $teamModel->findById($fixture->home_team_id);
    $away_team = $teamModel->findById($fixture->away_team_id);
    if ($home_team && $home_team->club_id) {
        $club = $clubModel->findById($home_team->club_id);
        if ($club) $fixture->home_team_name = $club->name;
    }
    if ($away_team && $away_team->club_id) {
        $club = $clubModel->findById($away_team->club_id);
        if ($club) $fixture->away_team_name = $club->name;
    }

    $home_lineup = $lineupModel->getLineupForFixture($id, $fixture->home_team_id);
    $away_lineup = $lineupModel->getLineupForFixture($id, $fixture->away_team_id);
    $player_names = $playerModel->getPlayerNamesForFixture($id);
    
    // Fetch unavailable players for context
    $home_injured = $playerModel->getInjuredPlayersByTeamId($fixture->home_team_id);
    $away_injured = $playerModel->getInjuredPlayersByTeamId($fixture->away_team_id);

    $date = date('d F Y', strtotime($fixture->match_datetime));
    $image = '/smart_football/public/assets/images/stadium_bg.jpg'; // Placeholder or dynamic stadium image

    if ($type === 'match_preview') {
        $title = "Match Preview: {$fixture->home_team_name} vs {$fixture->away_team_name}";
        
        // AI Generation Simulation for Preview - Randomized Templates
        $intros = [
            "The stage is set at {$fixture->venue} as {$fixture->home_team_name} prepare to host {$fixture->away_team_name} in what promises to be a captivating encounter in Gameweek {$fixture->gameweek}.",
            "Anticipation is building at {$fixture->venue} for a crucial Gameweek {$fixture->gameweek} clash between {$fixture->home_team_name} and {$fixture->away_team_name}.",
            "{$fixture->home_team_name} welcome {$fixture->away_team_name} to {$fixture->venue} this weekend, with both sides looking to secure vital points.",
            "It's a massive showdown at {$fixture->venue} as {$fixture->home_team_name} take on {$fixture->away_team_name}. The atmosphere is expected to be electric.",
            "Fans are gathering at {$fixture->venue} for a pivotal match-up. {$fixture->home_team_name} will look to leverage their home advantage against a resilient {$fixture->away_team_name}.",
            "A tactical battle awaits at {$fixture->venue}. {$fixture->home_team_name} face off against {$fixture->away_team_name} with league positions on the line.",
            "Gameweek {$fixture->gameweek} brings us a fascinating tie at {$fixture->venue}, where {$fixture->home_team_name} lock horns with {$fixture->away_team_name}."
        ];
        $content .= "<p class='lead'>" . $intros[array_rand($intros)] . "</p>";
        
        $content .= "<h3>Team News & Tactics</h3>";
        if ($home_lineup && !empty($home_lineup->formation)) {
            $tactics_text = [
                "<strong>{$fixture->home_team_name}</strong> are expected to line up in a <strong>{$home_lineup->formation}</strong> formation. The manager is looking to control the midfield and utilize the width of the pitch.",
                "The hosts are likely to deploy a <strong>{$home_lineup->formation}</strong> system, focusing on defensive stability and quick counter-attacks.",
                "Tactically, <strong>{$fixture->home_team_name}</strong> seem set on a <strong>{$home_lineup->formation}</strong>, aiming to dominate possession in the center of the park.",
                "Expect a <strong>{$home_lineup->formation}</strong> from <strong>{$fixture->home_team_name}</strong>, with an emphasis on high pressing and rapid transitions.",
                "The manager of <strong>{$fixture->home_team_name}</strong> is likely to trust the <strong>{$home_lineup->formation}</strong> setup to break down the opposition defense."
            ];
            $content .= "<p>" . $tactics_text[array_rand($tactics_text)] . "</p>";
        } else {
            $content .= "<p><strong>{$fixture->home_team_name}</strong> have yet to confirm their tactical setup, but fans will be hoping for an attacking display.</p>";
        }

        if (!empty($home_injured)) {
            $names = array_map(fn($p) => $p->last_name, $home_injured);
            $injury_text = [
                "Injury concerns remain for the hosts, with " . implode(', ', $names) . " currently on the treatment table.",
                "The medical team has been busy, as " . implode(', ', $names) . " are ruled out for this fixture.",
                "Squad depth will be tested with " . implode(', ', $names) . " unavailable due to injury.",
                "The manager will have to shuffle the pack as " . implode(', ', $names) . " miss out through injury.",
                "Fitness tests have ruled out " . implode(', ', $names) . ", forcing changes to the starting lineup."
            ];
            $content .= "<p>" . $injury_text[array_rand($injury_text)] . "</p>";
        }

        $content .= "<h3>Key Battle</h3>";
        $battles = [
            "All eyes will be on the attacking threats. Can the {$fixture->away_team_name} defense withstand the pressure? The tactical battle between the two managers will be crucial in deciding the outcome of this match.",
            "The midfield engine room will be where this game is won or lost. Whichever side controls the tempo will likely come out on top.",
            "Defensive organization will be key. {$fixture->away_team_name} will need to be disciplined to break down the {$fixture->home_team_name} backline.",
            "Set-pieces could play a major role. Both teams have threats in the air, and discipline in the box will be paramount.",
            "The duel on the wings will be fascinating. If {$fixture->home_team_name} can isolate the full-backs, they might find joy."
        ];
        $content .= "<p>" . $battles[array_rand($battles)] . "</p>";
        
        $content .= "<h3>Prediction</h3>";
        $predictions = [
            "Based on recent form and squad availability, this match is too close to call, but goals are expected.",
            "Home advantage could prove decisive here. We expect a narrow victory for {$fixture->home_team_name}.",
            "{$fixture->away_team_name} have the quality to cause an upset, but a draw seems the most likely outcome.",
            "It's going to be a tight affair, but the hosts might just edge it in the final stages.",
            "An open game is anticipated, with plenty of chances at both ends. A high-scoring draw wouldn't be a surprise.",
            "{$fixture->home_team_name} will look to make a statement here. A comfortable win for the home side is on the cards."
        ];
        $content .= "<p>" . $predictions[array_rand($predictions)] . "</p>";

    } elseif ($type === 'lineups_announced') {
        $title = "Lineups Announced: {$fixture->home_team_name} vs {$fixture->away_team_name}";
        
        $intros = [
            "The team sheets have been submitted at {$fixture->venue}. Here is how the two sides line up for this encounter.",
            "Breaking: Starting XIs confirmed for {$fixture->home_team_name} vs {$fixture->away_team_name}.",
            "The managers have made their decisions. Check out the confirmed lineups for the upcoming match.",
            "Team news is in! See who starts and who settles for a place on the bench at {$fixture->venue}.",
            "The wait is over. The starting lineups for {$fixture->home_team_name} vs {$fixture->away_team_name} have been revealed."
        ];
        $content .= "<p class='lead'>" . $intros[array_rand($intros)] . "</p>";

        $render_lineup = function($team_name, $lineup, $names) {
            $html = "<h3>{$team_name}</h3>";
            if ($lineup && !empty($lineup->starters)) {
                $starters = [];
                foreach (array_keys($lineup->starters) as $pid) {
                    $starters[] = $names[$pid] ?? 'Unknown';
                }
                $html .= "<p><strong>Starting XI:</strong> " . implode(', ', $starters) . "</p>";
                $html .= "<p><strong>Formation:</strong> " . ($lineup->formation ?? 'N/A') . "</p>";
            } else {
                $html .= "<p>Lineup details not yet available.</p>";
            }
            return $html;
        };

        $content .= $render_lineup($fixture->home_team_name, $home_lineup, $player_names);
        $content .= $render_lineup($fixture->away_team_name, $away_lineup, $player_names);

    } elseif ($type === 'match_report') {
        $title = "Match Report: {$fixture->home_team_name} {$fixture->home_team_score}-{$fixture->away_team_score} {$fixture->away_team_name}";
        
        // AI Generation Simulation for Report - Randomized Templates
        $winner = 'draw';
        if ($fixture->home_team_score > $fixture->away_team_score) $winner = $fixture->home_team_name;
        elseif ($fixture->away_team_score > $fixture->home_team_score) $winner = $fixture->away_team_name;

        $intros = [];
        if ($winner === 'draw') {
            $intros = [
                "Points were shared at {$fixture->venue} after a hard-fought contest ended in a stalemate.",
                "Neither side could find a winner as {$fixture->home_team_name} and {$fixture->away_team_name} played out a draw at {$fixture->venue}.",
                "It was honors even at {$fixture->venue}, with both teams taking a point from a tightly contested match.",
                "A deadlock at {$fixture->venue} saw both teams settle for a point in a game of few clear-cut chances.",
                "Nothing to separate the sides as the final whistle blew on a draw between {$fixture->home_team_name} and {$fixture->away_team_name}."
            ];
        } else {
            $intros = [
                "{$winner} claimed a vital victory in a dramatic clash at {$fixture->venue}.",
                "A spirited performance saw {$winner} take all three points at {$fixture->venue}.",
                "{$winner} emerged victorious after an intense battle against their rivals.",
                "Celebrations for {$winner} as they secured a well-deserved win at {$fixture->venue}.",
                "A clinical display from {$winner} ensured they took maximum points from this encounter."
            ];
        }
        
        $content .= "<p class='lead'>" . $intros[array_rand($intros)] . "</p>";
        
        $content .= "<h3>Match Summary</h3>";
        $summaries = [
            "The match ended <strong>{$fixture->home_team_score} - {$fixture->away_team_score}</strong>. Both teams had their moments, but it was " . ($winner === 'draw' ? "a stalemate" : "{$winner} who capitalized on their chances") . ".",
            "With a final score of <strong>{$fixture->home_team_score} - {$fixture->away_team_score}</strong>, the fans witnessed some entertaining football.",
            "The scoreboard read <strong>{$fixture->home_team_score} - {$fixture->away_team_score}</strong> at the final whistle.",
            "After 90 minutes of action, it finished <strong>{$fixture->home_team_score} - {$fixture->away_team_score}</strong>.",
            "Goals were the story of the day, ending <strong>{$fixture->home_team_score} - {$fixture->away_team_score}</strong>."
        ];
        $content .= "<p>" . $summaries[array_rand($summaries)] . "</p>";
        
        if (!empty($fixture->man_of_the_match_player_id)) {
            $motm_name = $player_names[$fixture->man_of_the_match_player_id] ?? 'the player';
            $motm_texts = [
                "The <strong>Man of the Match</strong> award went to <strong>{$motm_name}</strong> for an outstanding individual performance.",
                "<strong>{$motm_name}</strong> was the standout performer, earning the Man of the Match accolade.",
                "A masterclass from <strong>{$motm_name}</strong> secured them the Man of the Match award.",
                "<strong>{$motm_name}</strong> was voted Man of the Match after influencing the game significantly.",
                "An exceptional display by <strong>{$motm_name}</strong> saw them take home the Man of the Match honors."
            ];
            $content .= "<p>" . $motm_texts[array_rand($motm_texts)] . "</p>";
        }

        $content .= "<h3>Post-Match Analysis</h3>";
        $analysis = [
            "This result leaves {$fixture->home_team_name} looking to the next fixture to build momentum, while {$fixture->away_team_name} will analyze their performance to improve.",
            "Both managers will have plenty to ponder after this result. The season is long, and consistency will be key.",
            "A significant result in the context of the season. Fans will be eager to see how the teams respond in the next gameweek.",
            "The tactical approach paid off for " . ($winner === 'draw' ? "neither side fully" : "{$winner}") . ", and lessons will be learned ahead of the next round.",
            "Momentum is crucial in this league, and this result will certainly impact the morale in both dressing rooms."
        ];
        $content .= "<p>" . $analysis[array_rand($analysis)] . "</p>";
        
        $content .= "<div style='margin-top: 20px;'><a href='match_report.php?id={$id}' class='btn'>View Full Stats & Timeline</a></div>";
    }
} elseif ($type === 'suspension') {
        $db = new Database();
        $db->query("SELECT ps.*, u.first_name, u.last_name, u.profile_picture, t.name as team_name, c.name as club_name
                  FROM player_suspensions ps
                  JOIN players p ON ps.player_id = p.user_id
                  JOIN users u ON p.user_id = u.id
                  JOIN teams t ON p.team_id = t.id
                  JOIN clubs c ON t.club_id = c.id
                  WHERE ps.id = :id");
        $db->bind(':id', $id);
        $suspension = $db->single();

        if ($suspension) {
            $title = "Suspension Notice: {$suspension->first_name} {$suspension->last_name}";
            $date = date('d F Y', strtotime($suspension->created_at));
            
            if (!empty($suspension->profile_picture)) {
                $image = $suspension->profile_picture;
            }
            
            $suspension_intros = [
                "{$suspension->first_name} {$suspension->last_name} of {$suspension->club_name} will serve a suspension following a disciplinary incident.",
                "Bad news for {$suspension->club_name} as {$suspension->first_name} {$suspension->last_name} is ruled out due to suspension.",
                "Disciplinary action has been confirmed for {$suspension->first_name} {$suspension->last_name}, who faces a spell on the sidelines.",
                "{$suspension->club_name} will be without {$suspension->first_name} {$suspension->last_name} for upcoming matches after a suspension was issued."
            ];
            $content .= "<p class='lead'>" . $suspension_intros[array_rand($suspension_intros)] . "</p>";
            
            $content .= "<h3>Details of Suspension</h3>";
            $content .= "<p><strong>Reason:</strong> " . htmlspecialchars($suspension->reason) . "</p>";
            $content .= "<p><strong>Ban Length:</strong> " . htmlspecialchars($suspension->matches_to_serve) . " match(es)</p>";
            
            $suspension_outros = [
                "The club will be without the player for the upcoming fixtures. This action follows the league's disciplinary code to maintain fair play.",
                "The manager will need to find a replacement in the squad as the player serves their ban.",
                "This suspension comes at a crucial time for the club, testing their squad depth.",
                "The player is expected to return to action once the ban has been fully served."
            ];
            $content .= "<p>" . $suspension_outros[array_rand($suspension_outros)] . "</p>";
        } else {
            $title = "Suspension Details Not Found";
            $content = "<p>The requested suspension record could not be found.</p>";
    }
} elseif ($type === 'injury_recovery') {
    $db = new Database();
    $db->query("SELECT i.*, u.first_name, u.last_name, u.profile_picture, t.name as team_name, c.name as club_name
              FROM injuries i
              JOIN players p ON i.player_id = p.user_id
              JOIN users u ON p.user_id = u.id
              JOIN teams t ON p.team_id = t.id
              JOIN clubs c ON t.club_id = c.id
              WHERE i.id = :id");
    $db->bind(':id', $id);
    $injury = $db->single();

    if ($injury) {
        $title = "Injury Update: {$injury->first_name} {$injury->last_name} Returns";
        $date = date('d F Y', strtotime($injury->expected_return_date));
        
        if (!empty($injury->profile_picture)) {
            $image = $injury->profile_picture;
        }
        
        $recovery_intros = [
            "Great news for {$injury->club_name} fans as {$injury->first_name} {$injury->last_name} has been declared fit to play.",
            "{$injury->first_name} {$injury->last_name} has completed their recovery and is back in contention for {$injury->club_name}.",
            "After a spell on the sidelines, {$injury->first_name} {$injury->last_name} has returned to full training.",
            "The medical team at {$injury->club_name} has cleared {$injury->first_name} {$injury->last_name} for a return to action."
        ];
        $content .= "<p class='lead'>" . $recovery_intros[array_rand($recovery_intros)] . "</p>";
        
        $content .= "<h3>Recovery Details</h3>";
        $content .= "<p><strong>Previous Injury:</strong> " . htmlspecialchars($injury->injury_description) . "</p>";
        $content .= "<p>The player has successfully rehabilitated and is expected to be available for the upcoming fixtures. Their return will be a significant boost to the squad's depth and quality.</p>";
    } else {
        $title = "Injury Details Not Found";
        $content = "<p>The requested injury record could not be found.</p>";
    }
}
?>

<div class="page-content">
    <div class="blog-post-container">
        <div class="blog-header">
            <span class="blog-tag"><?php echo ucwords(str_replace('_', ' ', $type)); ?></span>
            <h1><?php echo htmlspecialchars($title); ?></h1>
            <p class="blog-date"><i class="fa-regular fa-clock"></i> <?php echo $date; ?></p>
        </div>
        
        <div class="blog-image">
            <?php if (!empty($image) && $image !== '/smart_football/public/assets/images/stadium_bg.jpg'): ?>
                <img src="<?php echo htmlspecialchars($image); ?>" alt="Featured Image" style="width: 100%; height: 300px; object-fit: cover;">
            <?php else: ?>
                <div class="placeholder-img" style="background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)); height: 300px; width: 100%; display: flex; align-items: center; justify-content: center; color: white; font-size: 3rem;"><i class="fa-solid fa-futbol"></i></div>
            <?php endif; ?>
        </div>

        <div class="blog-content">
            <?php echo $content; ?>
        </div>
        
        <div class="blog-footer">
            <a href="index.php" class="btn btn-secondary"><i class="fa-solid fa-arrow-left"></i> Back to Feed</a>
        </div>
    </div>
</div>

<style>
.blog-post-container {
    max-width: 800px;
    margin: 0 auto;
    background: #fff;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0,0,0,0.05);
}

.blog-header {
    padding: 40px 40px 20px 40px;
}

.blog-tag {
    display: inline-block;
    background: #e90052;
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 700;
    text-transform: uppercase;
    margin-bottom: 15px;
}

.blog-header h1 {
    font-size: 2.5rem;
    margin: 0 0 10px 0;
    color: #37003c;
    line-height: 1.2;
}

.blog-date {
    color: #777;
    font-size: 0.9rem;
}

.blog-image {
    width: 100%;
    height: auto;
}

.blog-content {
    padding: 40px;
    font-size: 1.1rem;
    line-height: 1.8;
    color: #333;
}

.blog-content p {
    margin-bottom: 20px;
}

.blog-content .lead {
    font-size: 1.3rem;
    font-weight: 600;
    color: #37003c;
}

.blog-footer {
    padding: 20px 40px;
    background: #f9f9f9;
    border-top: 1px solid #eee;
}

#scrollToTopBtn {
    display: none;
    position: fixed;
    bottom: 30px;
    right: 30px;
    z-index: 99;
    font-size: 1.2rem;
    border: none;
    outline: none;
    background-color: var(--primary-color);
    color: white;
    cursor: pointer;
    padding: 15px;
    border-radius: 50%;
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    transition: all 0.3s ease;
    width: 50px;
    height: 50px;
    align-items: center;
    justify-content: center;
}

#scrollToTopBtn:hover {
    background-color: var(--secondary-color);
    transform: translateY(-3px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.3);
}
</style>

<button id="scrollToTopBtn" title="Go to top"><i class="fa-solid fa-arrow-up"></i></button>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const mybutton = document.getElementById("scrollToTopBtn");

    window.onscroll = function() {
        if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
            mybutton.style.display = "flex";
        } else {
            mybutton.style.display = "none";
        }
    };

    mybutton.addEventListener('click', function() {
        window.scrollTo({top: 0, behavior: 'smooth'});
    });
});
</script>

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