<?php
$pageTitle = 'Player Profile';
include 'includes/header.php';

// --- Get Player ID from URL ---
$player_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$player_id) {
    echo "<p class='error-msg'>Invalid player ID.</p>";
    include 'includes/footer.php';
    exit();
}

// --- Instantiate Models ---
$playerModel = new Player();
$statModel = new Stat(); // Assuming career stats are here
$statsModel = new Stats(); // For specific event stats like offsides
$sponsorModel = new Sponsorship();

// --- Fetch Data ---
$player = $playerModel->getPlayerDetailsById($player_id);

if (!$player) {
    echo "<p class='error-msg'>Player not found.</p>";
    include 'includes/footer.php';
    exit();
}

// For demonstration, we'll fetch career stats. Season/team filtering would require more complex queries.
$career_stats = $statModel->getStatsForPlayer($player_id);
$transfer_history = $playerModel->getTransferHistory($player_id);
$injury_history = [];

// Fetch Offsides Count Manually
$offside_count = $statsModel->getPlayerOffsides($player_id);

try {
    $injury_history = $playerModel->getInjuryHistory($player_id);
} catch (PDOException $e) {
    // Gracefully handle if 'injuries' table doesn't exist yet
}
$suspension_history = [];
try {
    $suspension_history = $playerModel->getSuspensionHistory($player_id);
} catch (PDOException $e) {
    // Gracefully handle if 'suspensions' table doesn't exist yet
}
$performance_data = $statModel->getPerformanceChartData($player_id);
$achievements = $playerModel->getAchievements($player_id);

// --- Set Page Title Dynamically ---
$pageTitle = htmlspecialchars($player->first_name . ' ' . $player->last_name);

// --- AI Attribute Calculation Logic ---
$apps = $career_stats->appearances > 0 ? $career_stats->appearances : 1;
$mins = $career_stats->minutes_played ?? 0;

// Metrics (Normalized)
$metric_goals = ($career_stats->goals ?? 0) / $apps;
$metric_assists = ($career_stats->assists ?? 0) / $apps;
$metric_shots_acc = ($career_stats->shots ?? 0) > 0 ? ($career_stats->shots_on_target / $career_stats->shots) : 0;
$metric_defense = ($performance_data->clean_sheets ?? 0) / $apps;
$metric_discipline = max(0, 1 - ((($career_stats->yellow_cards ?? 0) + ($career_stats->red_cards ?? 0) * 3) / ($apps * 0.5))); 
$metric_stamina = min(1, ($mins / ($apps * 90)));

// Attributes (0-99 Scale)
$attr_attacking = min(99, round(($metric_goals * 150) + ($metric_shots_acc * 40) + 40));
$attr_technical = min(99, round(($metric_assists * 200) + ($metric_shots_acc * 30) + 50));
$attr_defense = min(99, round($metric_defense * 200 + 40));
$attr_physical = min(99, round($metric_stamina * 80 + 20));
$attr_mental = min(99, round($metric_discipline * 90 + 10));

// Overall Rating Calculation based on Position
$overall_rating = 60; // Base
if ($player->position === 'Forward') {
    $overall_rating = ($attr_attacking * 0.45) + ($attr_technical * 0.25) + ($attr_physical * 0.2) + ($attr_mental * 0.1);
} elseif ($player->position === 'Midfielder') {
    $overall_rating = ($attr_technical * 0.4) + ($attr_attacking * 0.2) + ($attr_defense * 0.2) + ($attr_physical * 0.2);
} elseif ($player->position === 'Defender') {
    $overall_rating = ($attr_defense * 0.5) + ($attr_physical * 0.3) + ($attr_mental * 0.2);
} elseif ($player->position === 'Goalkeeper') {
    $overall_rating = ($attr_defense * 0.7) + ($attr_mental * 0.2) + ($attr_physical * 0.1);
}
$overall_rating = min(99, max(45, round($overall_rating)));

// AI Summary Text
$ai_summary = "A balanced player contributing across the pitch.";
if ($overall_rating > 88) $ai_summary = "World-class talent with exceptional performance metrics.";
elseif ($attr_attacking > 80) $ai_summary = "Dangerous attacker with a keen eye for goal.";
elseif ($attr_defense > 80) $ai_summary = "Solid defensive wall, difficult to break down.";
elseif ($attr_technical > 80) $ai_summary = "Technical maestro capable of unlocking defenses.";
elseif ($attr_physical > 85) $ai_summary = "Physically dominant player with a high work rate.";

// Fetch General Product Ads
$productAds = $sponsorModel->getActiveAds(1);

?>

<!-- Player Hero Section -->
<div class="player-hero">
    <div class="player-hero-overlay"></div>
    <div class="player-hero-content">
        <div class="player-profile-picture">
            <img src="<?php echo htmlspecialchars($player->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="<?php echo htmlspecialchars($pageTitle); ?>">
        </div>
        <div class="player-hero-info">
            <h1><?php echo $pageTitle; ?></h1>
            <div class="player-current-team">
                <img src="<?php echo htmlspecialchars($player->club_logo); ?>" alt="<?php echo htmlspecialchars($player->club_name); ?>" class="team-logo-sm">
                <span><?php echo htmlspecialchars($player->club_name); ?></span>
            </div>
        </div>
        <div class="player-jersey-number">
            <span><?php echo htmlspecialchars($player->squad_number); ?></span>
        </div>
        <div class="player-overall-rating">
            <span class="rating-value"><?php echo $overall_rating; ?></span>
            <span class="rating-label">OVR</span>
        </div>
        <div class="player-hero-actions" style="position: absolute; bottom: 20px; right: 100px;">
            <a href="compare_players.php?player1=<?php echo $player_id; ?>" class="btn btn-secondary"><i class="fa-solid fa-scale-balanced"></i> Compare</a>
        </div>
    </div>
</div>

<!-- Main View Tabs -->
<div class="main-tabs">
    <a href="#overview" class="tab-link active" data-tab="overview">Overview</a>
    <a href="#attributes" class="tab-link" data-tab="attributes">Attributes</a>
    <a href="#stats" class="tab-link" data-tab="stats">Stats</a>
    <a href="#performance" class="tab-link" data-tab="performance">Performance</a>
    <a href="#transfers" class="tab-link" data-tab="transfers">Transfers</a>
    <a href="#history" class="tab-link" data-tab="history">History</a>
    <a href="#achievements" class="tab-link" data-tab="achievements">Achievements</a>
    <a href="#scout-report" class="tab-link" data-tab="scout-report">Scout Report</a>
</div>

<div class="page-content" style="padding-top: 0;">

    <!-- == OVERVIEW TAB == -->
    <div id="overview" class="tab-content active">
        <div class="player-section-card">
            <div class="player-bio-grid">
                <div class="bio-item">
                    <span class="bio-label">Full Name</span>
                    <span class="bio-value"><?php echo $pageTitle; ?></span>
                </div>
                <div class="bio-item">
                    <span class="bio-label">Nationality</span>
                    <span class="bio-value"><?php echo htmlspecialchars($player->nationality); ?></span>
                </div>
                <div class="bio-item">
                    <span class="bio-label">Age</span>
                    <span class="bio-value"><?php echo date_diff(date_create($player->date_of_birth), date_create('today'))->y; ?> (<?php echo date('d M Y', strtotime($player->date_of_birth)); ?>)</span>
                </div>
                <div class="bio-item">
                    <span class="bio-label">Height</span>
                    <span class="bio-value"><?php echo htmlspecialchars($player->height_cm); ?> cm</span>
                </div>
                <div class="bio-item">
                    <span class="bio-label">Weight</span>
                    <span class="bio-value"><?php echo htmlspecialchars($player->weight_kg); ?> kg</span>
                </div>
                <div class="bio-item">
                    <span class="bio-label">Preferred Foot</span>
                    <span class="bio-value"><?php echo htmlspecialchars($player->preferred_foot); ?></span>
                </div>
            </div>
        </div>
        <?php if (!empty($productAds)): ?>
            <div class="player-section-card ad-section" style="text-align: center;">
                <small style="display: block; color: #999; font-size: 0.7rem; margin-bottom: 10px; text-transform: uppercase;">Sponsored</small>
                <?php foreach ($productAds as $ad): ?>
                    <?php
                    $tag = !empty($ad->target_url) ? 'a' : 'div';
                    $href = !empty($ad->target_url) ? 'href="' . htmlspecialchars($ad->target_url) . '" target="_blank"' : '';
                    ?>
                    <<?php echo $tag; ?> <?php echo $href; ?> class="sponsor-ad" data-campaign-id="<?php echo $ad->id; ?>" style="display: inline-block; cursor: pointer;">
                        <?php if ($ad->ad_type === 'video'): ?>
                            <video src="<?php echo htmlspecialchars($ad->ad_content); ?>" autoplay muted loop playsinline style="max-width: 100%; border-radius: 8px;"></video>
                        <?php else: ?>
                            <img src="<?php echo htmlspecialchars($ad->ad_content); ?>" alt="Sponsored" style="max-width: 100%; border-radius: 8px;">
                        <?php endif; ?>
                    </<?php echo $tag; ?>>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- == ATTRIBUTES TAB == -->
    <div id="attributes" class="tab-content">
        <div class="player-section-card">
            <div class="attributes-container">
                <div class="attributes-chart-wrapper">
                    <canvas id="attributesRadarChart"></canvas>
                </div>
                <div class="attributes-details">
                    <h3 class="ai-title"><i class="fa-solid fa-robot"></i> AI Analysis</h3>
                    <p class="ai-summary"><?php echo $ai_summary; ?></p>
                    
                    <div class="attribute-bars">
                        <div class="attr-item">
                            <div class="attr-header"><span>Attacking</span><span><?php echo $attr_attacking; ?></span></div>
                            <div class="attr-bar-bg"><div class="attr-bar-fill" style="width: <?php echo $attr_attacking; ?>%; background: #e74c3c;"></div></div>
                        </div>
                        <div class="attr-item">
                            <div class="attr-header"><span>Technical</span><span><?php echo $attr_technical; ?></span></div>
                            <div class="attr-bar-bg"><div class="attr-bar-fill" style="width: <?php echo $attr_technical; ?>%; background: #f1c40f;"></div></div>
                        </div>
                        <div class="attr-item">
                            <div class="attr-header"><span>Physical</span><span><?php echo $attr_physical; ?></span></div>
                            <div class="attr-bar-bg"><div class="attr-bar-fill" style="width: <?php echo $attr_physical; ?>%; background: #3498db;"></div></div>
                        </div>
                        <div class="attr-item">
                            <div class="attr-header"><span>Defense</span><span><?php echo $attr_defense; ?></span></div>
                            <div class="attr-bar-bg"><div class="attr-bar-fill" style="width: <?php echo $attr_defense; ?>%; background: #2ecc71;"></div></div>
                        </div>
                        <div class="attr-item">
                            <div class="attr-header"><span>Mental</span><span><?php echo $attr_mental; ?></span></div>
                            <div class="attr-bar-bg"><div class="attr-bar-fill" style="width: <?php echo $attr_mental; ?>%; background: #9b59b6;"></div></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- == STATS TAB == -->
    <div id="stats" class="tab-content">
        <div class="player-section-card">
            <div class="stats-filters">
                <select id="season-filter">
                    <option value="career">Career Stats</option>
                    <!-- Seasons would be populated dynamically -->
                    <option value="2023/2024">2023/2024</option>
                </select>
                <select id="team-filter">
                    <option value="all">All Teams</option>
                     <!-- Teams would be populated dynamically -->
                </select>
            </div>
            <div class="stats-card-grid">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $career_stats->appearances ?? 0; ?></div>
                    <div class="stat-label">Appearances</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $career_stats->goals ?? 0; ?></div>
                    <div class="stat-label">Goals</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $career_stats->assists ?? 0; ?></div>
                    <div class="stat-label">Assists</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $career_stats->yellow_cards ?? 0; ?></div>
                    <div class="stat-label">Yellow Cards</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $career_stats->red_cards ?? 0; ?></div>
                    <div class="stat-label">Red Cards</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $offside_count; ?></div>
                    <div class="stat-label">Offsides</div>
                </div>
            </div>
        </div>
    </div>

    <!-- == PERFORMANCE TAB == -->
    <div id="performance" class="tab-content">
        <div class="player-section-card">
            <div class="chart-grid">
                <div class="chart-container">
                    <h3>Goal Contribution</h3>
                    <canvas id="goalContributionChart"></canvas>
                </div>
                <div class="chart-container">
                    <h3>Shooting Accuracy</h3>
                    <canvas id="shotAccuracyChart"></canvas>
                </div>
                <?php if (in_array($player->position, ['Goalkeeper', 'Defender'])): ?>
                <div class="chart-container">
                    <h3>Defensive Record (Clean Sheets)</h3>
                    <canvas id="cleanSheetChart"></canvas>
                </div>
                <?php endif; ?>
                <div class="chart-container">
                    <h3>Discipline Record</h3>
                    <canvas id="disciplineChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- == TRANSFERS TAB == -->
    <div id="transfers" class="tab-content">
        <div class="player-section-card">
            <div class="history-section">
                <h4>Transfer History</h4>
                <?php if (!empty($transfer_history)): ?>
                    <div class="table-wrapper">
                        <table class="styled-table">
                            <thead><tr><th>Date</th><th>From</th><th>To</th><th>Fee</th></tr></thead>
                            <tbody>
                                <?php foreach($transfer_history as $transfer): ?>
                                    <tr>
                                        <td><?php echo date('d M Y', strtotime($transfer->transfer_date)); ?></td>
                                        <td><?php echo htmlspecialchars($transfer->from_club ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($transfer->to_club ?? 'N/A'); ?></td>
                                        <td><?php echo $transfer->transfer_fee ? '$' . number_format($transfer->transfer_fee, 2) : 'Free'; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="no-data-msg">No transfer history available for this player.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- == HISTORY TAB == -->
    <div id="history" class="tab-content">
        <div class="player-section-card">
            <div class="history-section">
                <h4>Injury History</h4>
                <?php if (!empty($injury_history)): ?>
                    <div class="table-wrapper">
                        <table class="styled-table">
                            <thead><tr><th>Date Injured</th><th>Injury</th><th>Status</th></tr></thead>
                            <tbody>
                                <?php foreach($injury_history as $injury): ?>
                                    <tr>
                                        <td><?php echo date('d M Y', strtotime($injury->start_date)); ?></td>
                                        <td><?php echo htmlspecialchars($injury->injury_description); ?></td>
                                        <td><span class="status-badge status-<?php echo strtolower($injury->status); ?>"><?php echo htmlspecialchars($injury->status); ?></span></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="no-data-msg">No injury history available for this player.</p>
                <?php endif; ?>
            </div>
            <div class="history-section">
                <h4>Suspension History</h4>
                <?php if (!empty($suspension_history)): ?>
                    <div class="table-wrapper">
                        <table class="styled-table">
                            <thead><tr><th>Date Incurred</th><th>Reason</th><th>Ban Length</th></tr></thead>
                            <tbody>
                                <?php foreach($suspension_history as $suspension): ?>
                                    <tr>
                                        <td><?php echo date('d M Y', strtotime($suspension->date_incurred)); ?></td>
                                        <td><?php echo htmlspecialchars($suspension->reason); ?></td>
                                        <td><?php echo htmlspecialchars($suspension->matches_to_serve); ?> Match(es)</td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="no-data-msg">No suspension history available for this player.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- == ACHIEVEMENTS TAB == -->
    <div id="achievements" class="tab-content">
        <div class="player-section-card">
            <div class="achievements-grid">
                <?php if (!empty($achievements)): ?>
                    <?php foreach($achievements as $achievement): ?>
                        <div class="achievement-card">
                            <div class="achievement-icon">
                                <i class="fa-solid fa-trophy"></i>
                            </div>
                            <div class="achievement-details">
                                <span class="achievement-title"><?php echo htmlspecialchars($achievement->achievement_type); ?></span>
                                <span class="achievement-competition"><?php echo htmlspecialchars($achievement->competition_name); ?></span>
                                <span class="achievement-meta"><?php echo htmlspecialchars($achievement->team_name); ?> - <?php echo htmlspecialchars($achievement->season); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="no-data-msg">No achievements have been recorded for this player yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- == SCOUT REPORT TAB == -->
    <div id="scout-report" class="tab-content">
        <div class="player-section-card">
            <div class="report-actions" style="text-align: right; margin-bottom: 20px;">
                <button id="download-pdf-btn" class="btn"><i class="fa-solid fa-file-pdf"></i> Download PDF Report</button>
            </div>
            
            <div id="scout-report-content" class="scout-report-template">
                <!-- Report Header -->
                <div class="report-header">
                    <div class="report-logo">
                        <img src="<?php echo htmlspecialchars($player->club_logo); ?>" alt="Club Logo">
                    </div>
                    <div class="report-title">
                        <h2>Scouting Report</h2>
                        <p>Generated on <?php echo date('d M Y'); ?></p>
                    </div>
                    <div class="report-confidential">CONFIDENTIAL</div>
                </div>

                <!-- Player Identity -->
                <div class="report-identity">
                    <img src="<?php echo htmlspecialchars($player->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" class="report-avatar">
                    <div class="report-info">
                        <h1><?php echo $pageTitle; ?></h1>
                        <p><strong>Position:</strong> <?php echo htmlspecialchars($player->position); ?> | <strong>Age:</strong> <?php echo date_diff(date_create($player->date_of_birth), date_create('today'))->y; ?></p>
                        <p><strong>Club:</strong> <?php echo htmlspecialchars($player->club_name); ?> | <strong>Nationality:</strong> <?php echo htmlspecialchars($player->nationality); ?></p>
                    </div>
                    <div class="report-rating">
                        <span>OVR</span>
                        <strong><?php echo $overall_rating; ?></strong>
                    </div>
                </div>

                <!-- Attributes & Stats Grid -->
                <div class="report-grid">
                    <div class="report-col">
                        <h3>Attribute Profile</h3>
                        <div style="width: 100%; max-width: 300px; margin: 0 auto;">
                            <canvas id="reportRadarChart"></canvas>
                        </div>
                    </div>
                    <div class="report-col">
                        <h3>Key Attributes</h3>
                        <ul class="report-list">
                            <li><span>Attacking</span> <strong><?php echo $attr_attacking; ?></strong></li>
                            <li><span>Technical</span> <strong><?php echo $attr_technical; ?></strong></li>
                            <li><span>Physical</span> <strong><?php echo $attr_physical; ?></strong></li>
                            <li><span>Defense</span> <strong><?php echo $attr_defense; ?></strong></li>
                            <li><span>Mental</span> <strong><?php echo $attr_mental; ?></strong></li>
                        </ul>
                        <h3 style="margin-top: 20px;">Season Statistics</h3>
                        <ul class="report-list">
                            <li><span>Appearances</span> <strong><?php echo $career_stats->appearances ?? 0; ?></strong></li>
                            <li><span>Goals</span> <strong><?php echo $career_stats->goals ?? 0; ?></strong></li>
                            <li><span>Assists</span> <strong><?php echo $career_stats->assists ?? 0; ?></strong></li>
                            <li><span>Mins Played</span> <strong><?php echo $career_stats->minutes_played ?? 0; ?></strong></li>
                        </ul>
                    </div>
                </div>

                <!-- Transfer History -->
                <?php if (!empty($transfer_history)): ?>
                <div class="report-section">
                    <h3>Transfer History</h3>
                    <table class="report-table">
                        <thead><tr><th>Date</th><th>From</th><th>To</th><th>Fee</th></tr></thead>
                        <tbody>
                            <?php foreach($transfer_history as $transfer): ?>
                                <tr>
                                    <td><?php echo date('d M Y', strtotime($transfer->transfer_date)); ?></td>
                                    <td><?php echo htmlspecialchars($transfer->from_club ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($transfer->to_club ?? 'N/A'); ?></td>
                                    <td><?php echo $transfer->transfer_fee ? '$' . number_format($transfer->transfer_fee, 2) : 'Free'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <!-- Injury History -->
                <?php if (!empty($injury_history)): ?>
                <div class="report-section">
                    <h3>Injury History</h3>
                    <table class="report-table">
                        <thead><tr><th>Date Injured</th><th>Injury</th><th>Status</th></tr></thead>
                        <tbody>
                            <?php foreach($injury_history as $injury): ?>
                                <tr>
                                    <td><?php echo date('d M Y', strtotime($injury->start_date)); ?></td>
                                    <td><?php echo htmlspecialchars($injury->injury_description); ?></td>
                                    <td><span class="status-badge status-<?php echo strtolower($injury->status); ?>"><?php echo htmlspecialchars($injury->status); ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <!-- Achievements -->
                <?php if (!empty($achievements)): ?>
                <div class="report-section">
                    <h3>Achievements</h3>
                    <ul class="report-list">
                        <?php foreach($achievements as $achievement): ?>
                            <li><span><?php echo htmlspecialchars($achievement->achievement_type); ?> (<?php echo htmlspecialchars($achievement->season); ?>)</span> <strong><?php echo htmlspecialchars($achievement->competition_name); ?></strong></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>

                <!-- Analysis -->
                <div class="report-section">
                    <h3>Scout's Analysis</h3>
                    <div class="report-analysis-box">
                        <p><?php echo $ai_summary; ?></p>
                        <p><strong>Strengths:</strong> <?php echo ($attr_technical > 80 ? 'Technical Ability, ' : '') . ($attr_physical > 80 ? 'Physicality, ' : '') . ($attr_attacking > 80 ? 'Finishing' : 'Work Rate'); ?></p>
                    </div>
                </div>
                
                <div class="report-footer">
                    Smart Football Scouting System
                </div>
            </div>
        </div>
    </div>

</div>

<!-- Include Chart.js for performance charts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Tab switching logic
    const tabLinks = document.querySelectorAll('.tab-link');
    const tabContents = document.querySelectorAll('.tab-content');

    tabLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const tabId = this.dataset.tab;

            // Handle URL hash
            if(history.pushState) {
                history.pushState(null, null, '#' + tabId);
            } else {
                location.hash = '#' + tabId;
            }

            tabLinks.forEach(l => l.classList.remove('active'));
            tabContents.forEach(c => c.classList.remove('active'));

            this.classList.add('active');
            document.getElementById(tabId).classList.add('active');
        });
    });

    // On page load, check for a hash and activate the correct tab
    const currentHash = window.location.hash.substring(1);
    if (currentHash) {
        const activeLink = document.querySelector(`.tab-link[data-tab="${currentHash}"]`);
        if (activeLink) {
            activeLink.click();
        }
    }

    // --- Stats Filtering Logic ---
    const seasonFilter = document.getElementById('season-filter');
    const teamFilter = document.getElementById('team-filter');
    const statsGrid = document.querySelector('.stats-card-grid');

    function updateStats() {
        const season = seasonFilter.value;
        const teamId = teamFilter.value;
        const playerId = <?php echo $player_id; ?>;

        statsGrid.style.opacity = '0.5'; // Visual feedback for loading

        fetch(`/smart_football/app/api/get_player_stats.php?player_id=${playerId}&season=${season}&team_id=${teamId}`)
            .then(response => response.json())
            .then(data => {
                statsGrid.querySelector('.stat-value:nth-of-type(1)').textContent = data.appearances ?? 0;
                statsGrid.querySelectorAll('.stat-value')[1].textContent = data.goals ?? 0;
                statsGrid.querySelectorAll('.stat-value')[2].textContent = data.assists ?? 0;
                statsGrid.querySelectorAll('.stat-value')[3].textContent = data.yellow_cards ?? 0;
                statsGrid.querySelectorAll('.stat-value')[4].textContent = data.red_cards ?? 0;
                statsGrid.style.opacity = '1';
            })
            .catch(error => {
                console.error('Error fetching stats:', error);
                statsGrid.style.opacity = '1';
            });
    }

    seasonFilter.addEventListener('change', updateStats);
    teamFilter.addEventListener('change', updateStats);

    // --- Attributes Radar Chart ---
    const attrCtx = document.getElementById('attributesRadarChart').getContext('2d');
    new Chart(attrCtx, {
        type: 'radar',
        data: {
            labels: ['Attacking', 'Technical', 'Physical', 'Defense', 'Mental'],
            datasets: [{
                label: 'Player Attributes',
                data: [<?php echo "$attr_attacking, $attr_technical, $attr_physical, $attr_defense, $attr_mental"; ?>],
                backgroundColor: 'rgba(52, 152, 219, 0.2)',
                borderColor: 'rgba(52, 152, 219, 1)',
                pointBackgroundColor: 'rgba(52, 152, 219, 1)',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: 'rgba(52, 152, 219, 1)'
            }]
        },
        options: {
            scales: {
                r: {
                    angleLines: { display: true },
                    suggestedMin: 0,
                    suggestedMax: 100,
                    ticks: { display: false } // Hide numbers on axis
                }
            },
            plugins: { legend: { display: false } }
        }
    });

    // --- Report Radar Chart (Duplicate for PDF) ---
    const reportAttrCtx = document.getElementById('reportRadarChart').getContext('2d');
    new Chart(reportAttrCtx, {
        type: 'radar',
        data: {
            labels: ['Attacking', 'Technical', 'Physical', 'Defense', 'Mental'],
            datasets: [{
                label: 'Attributes',
                data: [<?php echo "$attr_attacking, $attr_technical, $attr_physical, $attr_defense, $attr_mental"; ?>],
                backgroundColor: 'rgba(52, 152, 219, 0.2)',
                borderColor: 'rgba(52, 152, 219, 1)',
                pointBackgroundColor: 'rgba(52, 152, 219, 1)',
                pointBorderColor: '#fff',
                pointRadius: 3
            }]
        },
        options: {
            scales: {
                r: {
                    angleLines: { display: true },
                    suggestedMin: 0,
                    suggestedMax: 100,
                    ticks: { display: false, stepSize: 20 }
                }
            },
            plugins: { legend: { display: false } },
            animation: false // Disable animation for PDF rendering reliability
        }
    });

    // --- Chart.js Implementation ---
    // Example data - this should be fetched dynamically based on filters as well
    const shotsOnTarget = <?php echo $career_stats->shots_on_target ?? 0; ?>;
    const shotsOffTarget = <?php echo ($career_stats->shots ?? 0) - ($career_stats->shots_on_target ?? 0); ?>;
    const shotAccuracy = shotsOnTarget + shotsOffTarget > 0 ? (shotsOnTarget / (shotsOnTarget + shotsOffTarget)) * 100 : 0;

    const shotCtx = document.getElementById('shotAccuracyChart').getContext('2d');
    new Chart(shotCtx, {
        type: 'doughnut',
        data: {
            labels: ['On Target', 'Off Target'],
            datasets: [{
                label: 'Shots',
                data: [shotsOnTarget, shotsOffTarget],
                backgroundColor: ['#2ecc71', '#e74c3c'],
            }]
        },
        options: {
            responsive: true,
            plugins: {
                legend: { position: 'bottom' },
                title: { display: true, text: `Shot Accuracy: ${shotAccuracy.toFixed(1)}%` }
            }
        }
    });

    const goalCtx = document.getElementById('goalContributionChart').getContext('2d');
    new Chart(goalCtx, {
        type: 'bar',
        data: {
            labels: ['Goals', 'Assists'],
            datasets: [{
                label: 'Total',
                data: [<?php echo $career_stats->goals ?? 0; ?>, <?php echo $career_stats->assists ?? 0; ?>],
                backgroundColor: ['#3498db', '#9b59b6'],
                borderRadius: 5
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true } }
        }
    });

    const disciplineCtx = document.getElementById('disciplineChart').getContext('2d');
    new Chart(disciplineCtx, {
        type: 'bar',
        data: {
            labels: ['Yellow Cards', 'Red Cards'],
            datasets: [{
                label: 'Cards',
                data: [<?php echo $career_stats->yellow_cards ?? 0; ?>, <?php echo $career_stats->red_cards ?? 0; ?>],
                backgroundColor: ['#f1c40f', '#e74c3c'],
                borderRadius: 5
            }]
        },
        options: {
            responsive: true,
            plugins: { legend: { display: false } },
            scales: { y: { beginAtZero: true } }
        }
    });

    // --- PDF Download Logic ---
    document.getElementById('download-pdf-btn').addEventListener('click', function() {
        const element = document.getElementById('scout-report-content');
        const opt = {
            margin: 10,
            filename: 'Scout_Report_<?php echo str_replace(' ', '_', $pageTitle); ?>.pdf',
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: { scale: 2, useCORS: true, scrollY: 0 },
            jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
        };
        html2pdf().set(opt).from(element).save();
    });
});
</script>

<style>
/* === Player Profile === */
/* Tab Logic */
.tab-content {
    display: none;
    animation: fadeIn 0.3s ease;
}
.tab-content.active {
    display: block;
}

.player-hero {
    height: 320px;
    background-size: cover;
    background-position: center;
    background: var(--hero-gradient);
    position: relative;
    display: flex;
    align-items: flex-end;
    padding: 20px;
    color: white;
    border-radius: 0 0 25px 25px;
    margin-bottom: 0;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.player-hero-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.4) 50%, rgba(0,0,0,0.8) 100%);
    border-radius: 0 0 25px 25px;
    z-index: 1;
}

.player-hero-content {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: flex-end;
    gap: 20px;
    width: 100%;
}

.player-profile-picture img {
    width: 140px;
    height: 140px;
    border-radius: 50%;
    border: 4px solid white;
    object-fit: cover;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.player-hero-info h1 {
    margin: 0 0 5px 0;
    font-size: 2.2rem;
    font-weight: 800;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.player-current-team {
    display: flex;
    align-items: center;
    gap: 8px;
    background: rgba(255, 255, 255, 0.2);
    padding: 5px 12px;
    border-radius: 20px;
    backdrop-filter: blur(5px);
    width: fit-content;
}

.team-logo-sm {
    width: 24px;
    height: 24px;
}

.player-jersey-number {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 4rem;
    font-weight: 900;
    opacity: 0.2;
    color: white;
}

.player-overall-rating {
    background: #fff;
    color: var(--primary-color);
    padding: 10px;
    border-radius: 8px;
    text-align: center;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    min-width: 60px;
}

.rating-value {
    display: block;
    font-size: 1.8rem;
    font-weight: 800;
    line-height: 1;
}

.rating-label {
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
    color: #888;
}

/* Tabs Styling */
.main-tabs {
    display: flex;
    overflow-x: auto;
    background: #fff;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    padding: 0 10px;
    margin-bottom: 20px;
    scrollbar-width: none; /* Firefox */
}
.main-tabs::-webkit-scrollbar { display: none; }
.tab-link {
    flex: 0 0 auto;
    padding: 15px 20px;
    color: #64748b;
    font-weight: 600;
    text-decoration: none;
    border-bottom: 3px solid transparent;
    transition: all 0.2s;
}
.tab-link.active { color: var(--secondary-color); border-bottom-color: var(--secondary-color); }

.attributes-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 2rem;
    align-items: center;
}

.attributes-chart-wrapper {
    max-width: 400px;
    margin: 0 auto;
    width: 100%;
}

.ai-title {
    color: var(--primary-color);
    margin-top: 0;
}

.ai-summary {
    font-style: italic;
    color: #555;
    background: #f8f9fa;
    padding: 10px;
    border-radius: 6px;
    border-left: 4px solid var(--secondary-color);
}

.attribute-bars {
    margin-top: 1.5rem;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.attr-header {
    display: flex;
    justify-content: space-between;
    font-size: 0.9rem;
    font-weight: 600;
    margin-bottom: 4px;
}

.attr-bar-bg {
    background: #eee;
    height: 8px;
    border-radius: 4px;
    overflow: hidden;
}

.attr-bar-fill {
    height: 100%;
    border-radius: 4px;
}

.player-section-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    margin-bottom: 20px;
    border: 1px solid #f1f5f9;
}

.player-bio-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
    padding: 0;
}

.bio-item {
    display: flex;
    flex-direction: column;
    background: #f8fafc;
    padding: 15px;
    border-radius: 8px;
}

.bio-label {
    font-size: 0.8rem;
    color: #777;
    margin-bottom: 5px;
}

.bio-value {
    font-weight: bold;
    font-size: 1.1rem;
}

.stats-filters {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.stats-card-grid {
    transition: opacity 0.3s ease-in-out;
}

.chart-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 2rem;
}

.chart-container {
    width: 100%;
    margin: 0 auto;
}

.history-section {
    margin-bottom: 2rem;
}

.history-section h4 {
    border-bottom: 2px solid #eee;
    padding-bottom: 10px;
    margin-bottom: 10px;
}

.achievements-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 1.5rem;
    padding: 0;
}

.achievement-card {
    display: flex;
    align-items: center;
    gap: 15px;
    background: #f8fafc;
    padding: 20px;
    border-radius: 8px;
    border-left: 5px solid #f1c40f;
}

.achievement-icon .fa-trophy {
    font-size: 2.5rem;
    color: #f1c40f;
}

.achievement-details {
    display: flex;
    flex-direction: column;
}

.achievement-title {
    font-weight: bold;
    font-size: 1.1rem;
}

.achievement-competition {
    font-size: 0.9rem;
}

.achievement-meta {
    font-size: 0.8rem;
    color: #777;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
    .attributes-container {
        grid-template-columns: 1fr;
    }

    .player-hero {
        height: auto;
        flex-direction: column;
        align-items: center;
        text-align: center;
        padding-top: 40px;
    }

    .player-hero-content {
        flex-direction: column;
        align-items: center;
    }

    .player-overall-rating {
        position: absolute;
        top: 0;
        right: 0;
    }
}

/* Scout Report Styles */
.scout-report-template {
    background: #fff;
    padding: 40px;
    border: 1px solid #eee;
    max-width: 800px;
    margin: 0 auto;
}
.report-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 2px solid #333;
    padding-bottom: 20px;
    margin-bottom: 30px;
}
.report-logo img { height: 60px; }
.report-title h2 { margin: 0; text-transform: uppercase; font-size: 1.5rem; }
.report-title p { margin: 0; color: #777; font-size: 0.9rem; }
.report-confidential {
    color: #e74c3c;
    font-weight: bold;
    border: 2px solid #e74c3c;
    padding: 5px 10px;
    transform: rotate(-5deg);
    font-size: 0.9rem;
}
.report-identity {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 30px;
    background: #f9f9f9;
    padding: 20px;
    border-radius: 8px;
}
.report-avatar { width: 80px; height: 80px; border-radius: 50%; object-fit: cover; border: 3px solid #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
.report-info h1 { margin: 0 0 5px 0; font-size: 1.8rem; }
.report-info p { margin: 2px 0; color: #555; }
.report-rating { margin-left: auto; text-align: center; background: #333; color: #fff; padding: 10px; border-radius: 8px; min-width: 60px; }
.report-rating span { display: block; font-size: 0.7rem; }
.report-rating strong { font-size: 1.5rem; }
.report-grid { display: flex; gap: 30px; margin-bottom: 30px; }
.report-col { flex: 1; }
.report-col h3 { border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 15px; font-size: 1.1rem; }
.report-list { list-style: none; padding: 0; margin: 0; }
.report-list li { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #f5f5f5; }
.report-section h3 { border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 15px; font-size: 1.1rem; }
.report-analysis-box { background: #f0f4f8; padding: 20px; border-radius: 8px; border-left: 4px solid #3498db; }
.report-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; margin-top: 10px; }
.report-table th, .report-table td { padding: 8px; border: 1px solid #ddd; text-align: left; }
.report-table th { background-color: #f2f2f2; }
.report-table tr:nth-child(even) { background-color: #f9f9f9; }

.report-footer { text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; color: #999; font-size: 0.8rem; }
</style>

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