<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

requireLogin();
$user = getConnectedUser($pdo);
$userId = (int)$user['id'];

// Stats utilisateur
try {
    $us = $pdo->prepare("SELECT * FROM user_stats WHERE user_id=?");
    $us->execute([$userId]);
    $uStats = $us->fetch() ?: [];
} catch (Exception $e) { $uStats = []; }

$wonBets   = (int)($uStats['won_bets']   ?? 0);
$totalBets = (int)($uStats['total_bets'] ?? 0);
$relScore  = (int)($uStats['reliability_score'] ?? 100);
$interPts  = (int)($user['interaction_points'] ?? 0);
$winPct    = $totalBets > 0 ? round($wonBets / $totalBets * 100) : 0;

// Mes trophées débloqués (avec date)
try {
    $myTrophiesStmt = $pdo->prepare("
        SELECT ut.trophy_id, ut.awarded_at FROM user_trophies ut WHERE ut.user_id=?
    ");
    $myTrophiesStmt->execute([$userId]);
    $myTrophyIds = [];
    foreach ($myTrophiesStmt->fetchAll() as $r) {
        $myTrophyIds[$r['trophy_id']] = $r['awarded_at'];
    }
} catch (Exception $e) { $myTrophyIds = []; }

// Tous les niveaux
try {
    $levels = $pdo->query("SELECT * FROM trophy_levels ORDER BY requirement_value ASC")->fetchAll();
} catch (Exception $e) { $levels = []; }

$trophies = [];
foreach ($levels as $lv) {
    $unlocked = isset($myTrophyIds[$lv['id']]);
    if (!$unlocked) {
        // Vérification dynamique aussi
        $unlocked = match($lv['requirement_type'] ?? '') {
            'win_count'   => $wonBets  >= (int)$lv['requirement_value'],
            'win_percent' => $winPct   >= (int)$lv['requirement_value'],
            'interaction' => $interPts >= (int)$lv['requirement_value'],
            'reliability' => $relScore >= (int)$lv['requirement_value'],
            default       => false
        };
    }
    $trophies[] = [
        'data'       => $lv,
        'unlocked'   => $unlocked,
        'awarded_at' => $myTrophyIds[$lv['id']] ?? null,
    ];
}

$unlockedCount = count(array_filter($trophies, fn($t) => $t['unlocked']));
$totalCount    = count($trophies);
$pct = $totalCount > 0 ? round($unlockedCount / $totalCount * 100) : 0;

// Classement trophées (top joueurs)
try {
    $rankStmt = $pdo->query("
        SELECT u.id, u.username, COUNT(ut.trophy_id) as nb
        FROM users u LEFT JOIN user_trophies ut ON ut.user_id=u.id
        GROUP BY u.id ORDER BY nb DESC LIMIT 5
    ");
    $trophyRank = $rankStmt->fetchAll();
} catch (Exception $e) { $trophyRank = []; }

include 'header.php';
?>

<div class="container mt-4 px-4" style="max-width:900px;">
    <div class="d-flex align-items-center gap-3 mb-3">
        <a href="index.php" class="btn btn-outline-secondary btn-sm">&larr; Dashboard</a>
        <h5 class="oracle-text text-primary mb-0">SALLE DES TROPHEES</h5>
        <span class="badge bg-warning text-dark"><?= $unlockedCount ?>/<?= $totalCount ?></span>
    </div>

    <?php if (empty($trophies)): ?>
    <div class="alert alert-secondary small">Aucun trophée configuré. L'admin peut en ajouter.</div>
    <?php else: ?>

    <!-- Progression globale -->
    <div class="card bg-dark border-info p-3 mb-4">
        <div class="d-flex justify-content-between mb-1">
            <small class="text-info text-uppercase fw-bold">Progression globale</small>
            <small class="text-white"><?= $unlockedCount ?>/<?= $totalCount ?> — <?= $pct ?>%</small>
        </div>
        <div class="progress" style="height:10px;background:#1a1a1a;">
            <div class="progress-bar bg-warning progress-bar-striped" style="width:<?= $pct ?>%;"></div>
        </div>
    </div>

    <div class="row g-3">
        <!-- Grille des trophées -->
        <div class="col-md-8">
            <div class="row g-2">
            <?php
            // Trier : débloqués en premier
            usort($trophies, fn($a,$b) => $b['unlocked'] - $a['unlocked']);
            foreach ($trophies as $t):
                $lv = $t['data'];
                $unlocked = $t['unlocked'];
                $ip = $lv['icon_path'] ?? '';
                $awardedAt = $t['awarded_at'];
            ?>
            <div class="col-6 col-md-4">
                <div class="card h-100 text-center p-2 <?= $unlocked ? 'bg-dark border-warning' : 'bg-dark border-secondary' ?>"
                     style="<?= !$unlocked ? 'opacity:0.5;' : '' ?>">
                    <div style="font-size:<?= !empty($ip) && strpos($ip,'emoji:')===0 ? '2rem' : '1.5rem' ?>;">
                        <?php if (!empty($ip) && strpos($ip,'emoji:')===0): ?>
                            <?= htmlspecialchars(substr($ip,6)) ?>
                        <?php elseif (!empty($ip) && @file_exists(__DIR__.'/'.$ip)): ?>
                            <img src="<?= htmlspecialchars($ip) ?>" style="width:40px;height:40px;object-fit:contain;">
                        <?php else: ?>
                            <?= $unlocked ? '&#9733;' : '&#9734;' ?>
                        <?php endif; ?>
                    </div>
                    <div class="<?= $unlocked ? 'text-warning' : 'text-white' ?> fw-bold" style="font-size:0.72rem;margin-top:4px;">
                        <?= htmlspecialchars($lv['title'] ?? '') ?>
                    </div>
                    <div style="font-size:0.6rem;color:#aaa;margin-top:2px;">
                        <?= htmlspecialchars($lv['description'] ?? '') ?>
                    </div>
                    <?php if ($unlocked && $awardedAt): ?>
                    <div class="badge bg-success mt-1" style="font-size:0.5rem;">
                        <?= date('d M Y', strtotime($awardedAt)) ?>
                    </div>
                    <?php elseif (!$unlocked): ?>
                    <div style="font-size:0.58rem;color:#666;margin-top:4px;">
                        <?php
                        $typeLabel = match($lv['requirement_type']??'') {
                            'win_count'   => $wonBets.'/'.(int)$lv['requirement_value'].' victoires',
                            'win_percent' => $winPct.'/'.(int)$lv['requirement_value'].'% victoires',
                            'interaction' => $interPts.'/'.(int)$lv['requirement_value'].' pts int.',
                            'reliability' => $relScore.'/'.(int)$lv['requirement_value'].'% fiabilite',
                            default       => ''
                        };
                        echo $typeLabel;
                        ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            </div>
        </div>

        <!-- Classement trophées -->
        <div class="col-md-4">
            <div class="card bg-dark border-secondary shadow">
                <div class="card-header text-warning fw-bold small py-2">Top collectionneurs</div>
                <table class="table table-dark table-sm small mb-0">
                    <tbody>
                    <?php foreach ($trophyRank as $i => $r):
                        $medals = ['&#127881;','&#129352;','&#129353;'];
                        $icon   = $medals[$i] ?? ($i+1).'.';
                        $isMe   = $r['id'] == $userId;
                    ?>
                    <tr class="<?= $isMe?'table-warning':'' ?>">
                        <td><?= $icon ?></td>
                        <td class="<?= $isMe?'text-dark fw-bold':'text-white' ?>"><?= htmlspecialchars($r['username']) ?></td>
                        <td class="text-end text-warning fw-bold"><?= $r['nb'] ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($trophyRank)): ?>
                    <tr><td colspan="3" class="text-center text-muted py-2">Aucun</td></tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Mes stats pour les trophées -->
            <div class="card bg-dark border-secondary shadow mt-3">
                <div class="card-header text-info fw-bold small py-2">Mes stats</div>
                <div class="card-body py-2">
                    <?php foreach ([
                        ['Victoires',   $wonBets,   'success'],
                        ['Taux victoire', $winPct.'%', 'primary'],
                        ['Pts interaction', $interPts, 'info'],
                        ['% Fiabilite',  $relScore.'%', 'warning'],
                    ] as [$lbl,$val,$col]): ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span style="color:#aaa;"><?= $lbl ?></span>
                        <span class="text-<?= $col ?> fw-bold"><?= $val ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

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