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

$pageTitle = 'Compare Players';
include 'includes/header.php';

// --- Instantiate Models ---
$playerModel = new Player();
$statModel = new Stat();

// --- Get Player IDs from URL ---
$player1_id = filter_input(INPUT_GET, 'player1', FILTER_VALIDATE_INT);
$player2_id = filter_input(INPUT_GET, 'player2', FILTER_VALIDATE_INT);

$p1 = null;
$p2 = null;
$s1 = null; // Stats 1
$s2 = null; // Stats 2
$a1 = null; // Attributes 1
$a2 = null; // Attributes 2

// Helper to calculate attributes (Simplified version of player.php logic)
function getPlayerAttributes($statModel, $player_id) {
    $stats = $statModel->getStatsForPlayer($player_id);
    $perf = $statModel->getPerformanceChartData($player_id);
    
    $apps = ($stats->appearances ?? 0) > 0 ? $stats->appearances : 1;
    $mins = $stats->minutes_played ?? 0;

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

    return [
        'Attacking' => min(99, round(($metric_goals * 150) + ($metric_shots_acc * 40) + 40)),
        'Technical' => min(99, round(($metric_assists * 200) + ($metric_shots_acc * 30) + 50)),
        'Defense' => min(99, round($metric_defense * 200 + 40)),
        'Physical' => min(99, round($metric_stamina * 80 + 20)),
        'Mental' => min(99, round($metric_discipline * 90 + 10))
    ];
}

if ($player1_id) {
    $p1 = $playerModel->getPlayerDetailsById($player1_id);
    if ($p1) {
        $s1 = $statModel->getStatsForPlayer($player1_id);
        $a1 = getPlayerAttributes($statModel, $player1_id);
    }
}

if ($player2_id) {
    $p2 = $playerModel->getPlayerDetailsById($player2_id);
    if ($p2) {
        $s2 = $statModel->getStatsForPlayer($player2_id);
        $a2 = getPlayerAttributes($statModel, $player2_id);
    }
}

// Helper to generate URL for removing a player
function getRemoveUrl($removeSlot) {
    global $player1_id, $player2_id;
    $params = [];
    if ($removeSlot == 1 && $player2_id) $params['player2'] = $player2_id;
    if ($removeSlot == 2 && $player1_id) $params['player1'] = $player1_id;
    return 'compare_players.php' . (!empty($params) ? '?' . http_build_query($params) : '');
}

// Helper to generate URL for adding a player (used by JS)
function getAddUrlBase($currentSlot) {
    global $player1_id, $player2_id;
    $params = [];
    if ($currentSlot == 1 && $player2_id) $params['player2'] = $player2_id;
    if ($currentSlot == 2 && $player1_id) $params['player1'] = $player1_id;
    return 'compare_players.php?' . http_build_query($params) . ($params ? '&' : '') . ($currentSlot == 1 ? 'player1=' : 'player2=');
}

?>

<div class="team-dashboard-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="team-identity">
                <div class="hero-team-logo"><i class="fa-solid fa-scale-balanced" style="font-size: 2rem; color: var(--primary-color);"></i></div>
                <div class="team-details">
                    <h1>Player Comparison</h1>
                    <span class="manager-badge">Select two players to see a head-to-head analysis.</span>
                </div>
            </div>
            <div class="hero-actions">
                 <a href="matches.php?view=stats" class="btn btn-hero-secondary"><i class="fa-solid fa-arrow-left"></i> Back to Stats</a>
            </div>
        </div>
    </div>
</div>
<div class="page-content">
    <div class="comparison-wrapper">
        <!-- Player 1 Card -->
        <div class="comparison-slot">
            <?php if ($p1): ?>
                <div class="player-compare-card">
                    <a href="<?php echo getRemoveUrl(1); ?>" class="remove-player-btn" title="Remove Player">&times;</a>
                    <img src="<?php echo htmlspecialchars($p1->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="Player 1" class="compare-avatar">
                    <h3><?php echo htmlspecialchars($p1->first_name . ' ' . $p1->last_name); ?></h3>
                    <div class="compare-meta">
                        <img src="<?php echo htmlspecialchars($p1->club_logo); ?>" alt="Club" class="compare-club-logo">
                        <span><?php echo htmlspecialchars($p1->club_name); ?></span>
                    </div>
                    <span class="compare-pos"><?php echo htmlspecialchars($p1->position); ?></span>
                </div>
            <?php else: ?>
                <div class="empty-slot-container">
                    <div class="empty-icon"><i class="fa-solid fa-user-plus"></i></div>
                    <h4>Select Player 1</h4>
                    <div class="search-box">
                        <input type="text" placeholder="Search player..." oninput="searchPlayers(this, 1)">
                        <div class="search-results" id="results-1"></div>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- VS Badge -->
        <div class="vs-badge">VS</div>

        <!-- Player 2 Card -->
        <div class="comparison-slot">
            <?php if ($p2): ?>
                <div class="player-compare-card">
                    <a href="<?php echo getRemoveUrl(2); ?>" class="remove-player-btn" title="Remove Player">&times;</a>
                    <img src="<?php echo htmlspecialchars($p2->profile_picture ?? '/smart_football/public/assets/images/default_avatar.png'); ?>" alt="Player 2" class="compare-avatar">
                    <h3><?php echo htmlspecialchars($p2->first_name . ' ' . $p2->last_name); ?></h3>
                    <div class="compare-meta">
                        <img src="<?php echo htmlspecialchars($p2->club_logo); ?>" alt="Club" class="compare-club-logo">
                        <span><?php echo htmlspecialchars($p2->club_name); ?></span>
                    </div>
                    <span class="compare-pos"><?php echo htmlspecialchars($p2->position); ?></span>
                </div>
            <?php else: ?>
                <div class="empty-slot-container">
                    <div class="empty-icon"><i class="fa-solid fa-user-plus"></i></div>
                    <h4>Select Player 2</h4>
                    <div class="search-box">
                        <input type="text" placeholder="Search player..." oninput="searchPlayers(this, 2)">
                        <div class="search-results" id="results-2"></div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <?php if ($p1 && $p2): ?>
        <div class="dashboard-section">
            <h2 class="dashboard-title">Head to Head Stats</h2>
            <div class="table-wrapper">
                <table class="styled-table comparison-table">
                    <thead>
                        <tr>
                            <th style="text-align: left;"><?php echo htmlspecialchars($p1->first_name . ' ' . $p1->last_name); ?></th>
                            <th style="text-align: center;">Stat</th>
                            <th style="text-align: right;"><?php echo htmlspecialchars($p2->first_name . ' ' . $p2->last_name); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $metrics = [
                            'Appearances' => 'appearances',
                            'Goals' => 'goals',
                            'Assists' => 'assists',
                            'Shots' => 'shots',
                            'On Target' => 'shots_on_target',
                            'Yellow Cards' => 'yellow_cards',
                            'Red Cards' => 'red_cards',
                            'Minutes' => 'minutes_played'
                        ];
                        foreach ($metrics as $label => $key): 
                            $val1 = $s1->$key ?? 0;
                            $val2 = $s2->$key ?? 0;
                            $total = $val1 + $val2;
                            if ($total == 0) {
                                $perc1 = 50; $perc2 = 50;
                            } else {
                                $perc1 = ($val1 / $total) * 100;
                                $perc2 = ($val2 / $total) * 100;
                            }
                            $winner1 = ($val1 > $val2);
                            $winner2 = ($val2 > $val1);
                            // Invert logic for cards (less is better)
                            if (in_array($key, ['yellow_cards', 'red_cards'])) {
                                $winner1 = ($val1 < $val2);
                                $winner2 = ($val2 < $val1);
                            }
                        ?>
                        <tr>
                            <td class="text-left <?php echo $winner1 ? 'winner' : ''; ?>"><?php echo $val1; ?></td>
                            <td class="text-center">
                                <div class="stat-label-with-bar">
                                    <span><?php echo $label; ?></span>
                                    <div class="stat-comparison-bar">
                                        <div class="bar bar-p1" style="width: <?php echo $perc1; ?>%;"></div>
                                        <div class="bar bar-p2" style="width: <?php echo $perc2; ?>%;"></div>
                                    </div>
                                </div>
                            </td>
                            <td class="text-right <?php echo $winner2 ? 'winner' : ''; ?>"><?php echo $val2; ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="dashboard-section">
            <h2 class="dashboard-title">Attribute Breakdown</h2>
            <div class="table-wrapper">
                <table class="styled-table comparison-table">
                    <thead>
                        <tr>
                            <th style="text-align: left;"><?php echo htmlspecialchars($p1->first_name . ' ' . $p1->last_name); ?></th>
                            <th style="text-align: center;">Attribute</th>
                            <th style="text-align: right;"><?php echo htmlspecialchars($p2->first_name . ' ' . $p2->last_name); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $attributes_list = ['Attacking', 'Technical', 'Physical', 'Defense', 'Mental'];
                        foreach ($attributes_list as $attr): 
                            $val1 = $a1[$attr] ?? 0;
                            $val2 = $a2[$attr] ?? 0;
                            $total = $val1 + $val2;
                            if ($total == 0) {
                                $perc1 = 50; $perc2 = 50;
                            } else {
                                $perc1 = ($val1 / $total) * 100;
                                $perc2 = ($val2 / $total) * 100;
                            }
                            $winner1 = ($val1 > $val2);
                            $winner2 = ($val2 > $val1);
                        ?>
                        <tr>
                            <td class="text-left <?php echo $winner1 ? 'winner' : ''; ?>"><?php echo $val1; ?></td>
                            <td class="text-center">
                                <div class="stat-label-with-bar">
                                    <span><?php echo $attr; ?></span>
                                    <div class="stat-comparison-bar">
                                        <div class="bar bar-p1" style="width: <?php echo $perc1; ?>%;"></div>
                                        <div class="bar bar-p2" style="width: <?php echo $perc2; ?>%;"></div>
                                    </div>
                                </div>
                            </td>
                            <td class="text-right <?php echo $winner2 ? 'winner' : ''; ?>"><?php echo $val2; ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="dashboard-section">
            <h2 class="dashboard-title">Attribute Comparison</h2>
            <div class="chart-container" style="max-width: 600px; margin: 0 auto;">
                <canvas id="comparisonRadarChart"></canvas>
            </div>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    function searchPlayers(input, slot) {
        const query = input.value;
        const resultsContainer = document.getElementById(`results-${slot}`);
        
        if (query.length < 2) {
            resultsContainer.style.display = 'none';
            return;
        }

        fetch(`api/search_players.php?q=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(data => {
                resultsContainer.innerHTML = '';
                if (data.length > 0) {
                    resultsContainer.style.display = 'block';
                    data.forEach(player => {
                        const div = document.createElement('div');
                        div.className = 'search-result-item';
                        div.innerHTML = `
                            <img src="${player.image || '/smart_football/public/assets/images/default_avatar.png'}" alt="">
                            <div>
                                <div class="name">${player.first_name} ${player.last_name}</div>
                                <div class="meta">${player.position} - ${player.club_name}</div>
                            </div>
                        `;
                        div.onclick = () => {
                            const baseUrl = '<?php echo getAddUrlBase($player1_id ? 2 : 1); ?>';
                            // Logic to construct URL properly depending on which slot is being filled
                            let url = 'compare_players.php?';
                            const p1 = <?php echo json_encode($player1_id); ?>;
                            const p2 = <?php echo json_encode($player2_id); ?>;
                            
                            if (slot === 1) {
                                url += `player1=${player.id}`;
                                if (p2) url += `&player2=${p2}`;
                            } else {
                                if (p1) url += `player1=${p1}&`;
                                url += `player2=${player.id}`;
                            }
                            window.location.href = url;
                        };
                        resultsContainer.appendChild(div);
                    });
                } else {
                    resultsContainer.style.display = 'none';
                }
            });
    }

    // Close search results when clicking outside
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.search-box')) {
            document.querySelectorAll('.search-results').forEach(el => el.style.display = 'none');
        }
    });

    <?php if ($p1 && $p2): ?>
    document.addEventListener('DOMContentLoaded', function() {
        const ctx = document.getElementById('comparisonRadarChart').getContext('2d');
        new Chart(ctx, {
            type: 'radar',
            data: {
                labels: ['Attacking', 'Technical', 'Physical', 'Defense', 'Mental'],
                datasets: [{
                    label: '<?php echo addslashes($p1->last_name); ?>',
                    data: [<?php echo implode(',', array_values($a1)); ?>],
                    backgroundColor: 'rgba(52, 152, 219, 0.2)',
                    borderColor: 'rgba(52, 152, 219, 1)',
                    pointBackgroundColor: 'rgba(52, 152, 219, 1)',
                }, {
                    label: '<?php echo addslashes($p2->last_name); ?>',
                    data: [<?php echo implode(',', array_values($a2)); ?>],
                    backgroundColor: 'rgba(231, 76, 60, 0.2)',
                    borderColor: 'rgba(231, 76, 60, 1)',
                    pointBackgroundColor: 'rgba(231, 76, 60, 1)',
                }]
            },
            options: {
                scales: {
                    r: {
                        angleLines: { display: true },
                        suggestedMin: 0,
                        suggestedMax: 100
                    }
                }
            }
        });
    });
    <?php endif; ?>
</script>

<style>
/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute !important;
    width: 100%;
    top: 0;
    z-index: 1000;
}

.team-dashboard-hero {
    background: var(--hero-gradient);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-top: 0;
}

.hero-content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
}

.hero-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.team-identity {
    display: flex;
    align-items: center;
    gap: 1.5rem;
}

.hero-team-logo {
    width: 80px;
    height: 80px;
    object-fit: contain;
    background: white;
    border-radius: 50%;
    padding: 5px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    justify-content: center;
}

.team-details h1 {
    margin: 0 0 5px 0;
    font-size: 2rem;
    font-weight: 700;
}

.manager-badge {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    backdrop-filter: blur(5px);
}

.hero-actions {
    display: flex;
    gap: 10px;
}

.btn-hero-secondary {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
}
.btn-hero-secondary:hover { background: rgba(255,255,255,0.3); }

.comparison-wrapper {
    display: flex;
    justify-content: center;
    align-items: stretch; /* Make slots equal height */
    gap: 20px;
    margin-bottom: 30px;
    position: relative;
}
.comparison-slot {
    flex: 1;
    max-width: 400px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    min-height: 300px;
    display: flex;
    flex-direction: column;
    position: relative;
    border: 1px solid #f1f5f9;
}
.vs-badge {
    background: #333;
    color: #fff;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 800;
    font-style: italic;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
    border: 4px solid #f4f6f9;
}
.empty-slot-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
    text-align: center;
    border: 2px dashed #e0e6ed;
    border-radius: 12px;
    transition: all 0.2s;
}
.empty-slot-container:hover {
    border-color: var(--primary-color);
    background: #fcfdff;
}
.empty-icon {
    font-size: 3.5rem;
    color: #e0e6ed;
    margin-bottom: 15px;
    transition: color 0.2s;
}
.empty-slot-container:hover .empty-icon {
    color: var(--primary-color);
}
.search-box {
    width: 100%;
    position: relative;
    margin-top: 15px;
}
.search-box input {
    width: 100%;
    padding: 10px 15px;
    border: 1px solid #ddd;
    border-radius: 20px;
    outline: none;
}
.search-results {
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    background: #fff;
    border: 1px solid #eee;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    z-index: 100;
    max-height: 250px;
    overflow-y: auto;
    display: none;
    margin-top: 5px;
}
.search-result-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px;
    cursor: pointer;
    border-bottom: 1px solid #f9f9f9;
    text-align: left;
}
.search-result-item:hover { background: #f0f4f8; }
.search-result-item img { width: 30px; height: 30px; border-radius: 50%; object-fit: cover; }
.search-result-item .name { font-weight: 600; font-size: 0.9rem; }
.search-result-item .meta { font-size: 0.75rem; color: #777; }

.player-compare-card {
    padding: 30px 20px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
    background: linear-gradient(180deg, #f9f9f9 0%, #fff 50%);
}
.compare-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 4px solid #fff;
    box-shadow: 0 4px 15px rgba(0,0,0,0.15);
    margin-bottom: 15px;
}
.compare-meta {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 5px 0;
    color: #555;
    font-size: 0.9rem;
}
.compare-club-logo { width: 20px; height: 20px; object-fit: contain; }
.compare-pos {
    background: #f0f4f8;
    color: #333;
    padding: 4px 12px;
    border-radius: 15px;
    font-size: 0.8rem;
    font-weight: 600;
    margin-top: 10px;
}
.remove-player-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #f1f1f1;
    color: #999;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    font-weight: bold;
    transition: all 0.2s;
}
.remove-player-btn:hover { background: #e74c3c; color: #fff; }

.comparison-table td { font-size: 1rem; padding: 15px; }
.comparison-table th { text-transform: uppercase; font-size: 0.8rem; color: #777; }
.comparison-table .winner { color: #27ae60; font-weight: 700; }
.text-right { text-align: right; }
.text-center { text-align: center; }
.text-left { text-align: left; }

.stat-label-with-bar {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
}
.stat-label-with-bar span {
    font-weight: 600;
    color: #777;
    text-transform: uppercase;
    font-size: 0.8rem;
}
.stat-comparison-bar {
    display: flex;
    height: 6px;
    width: 100%;
    max-width: 150px;
    border-radius: 3px;
    overflow: hidden;
    background: #eee;
}
.bar-p1 { background: var(--primary-color, #3498db); }
.bar-p2 { background: var(--secondary-color, #2c3e50); }

@media (max-width: 768px) {
    .hero-header-row { flex-direction: column; text-align: center; gap: 1.5rem; }
    .team-identity { flex-direction: column; }
    .comparison-wrapper { flex-direction: column; align-items: center; }
    .comparison-slot { width: 100%; }
    .vs-badge { position: static; transform: none; margin: -10px 0; }
}
</style>

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