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

requireLogin();
$currentUser = getConnectedUser($pdo);
if (!$currentUser) { header("Location: index.php"); exit; }
$currentUserId = (int)$currentUser['id'];

$targetId = isset($_GET['id']) && (int)$_GET['id'] > 0 ? (int)$_GET['id'] : $currentUserId;

// ============================================================
// Détecter les colonnes optionnelles
// ============================================================
$colUsers = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
$hasNickname     = in_array('nickname',          $colUsers);
$hasRoleStatus   = in_array('role_status',        $colUsers);
$hasLastActivity = in_array('last_activity',      $colUsers);
$hasInteraction  = in_array('interaction_points', $colUsers);
$hasPhone        = in_array('phone',              $colUsers);
$hasPhonePriv    = in_array('phone_private',      $colUsers);
$hasEmailPriv    = in_array('email_private',      $colUsers);
$hasHiddenBets   = (bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'hidden'")->fetch();

// ============================================================
// Charger le profil
// ============================================================
try {
    $stmt = $pdo->prepare("SELECT u.*, us.total_bets, us.won_bets, us.lost_bets, us.reliability_score
        FROM users u LEFT JOIN user_stats us ON us.user_id = u.id WHERE u.id = ?");
    $stmt->execute([$targetId]);
    $profile = $stmt->fetch();
} catch (Exception $e) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$targetId]);
    $profile = $stmt->fetch();
}
if (!$profile) { header("Location: index.php"); exit; }

$isSelf = ($targetId === $currentUserId);
$isAdm  = isAdmin($currentUser);

// Vérifier si profil privé
$isPrivate = !$isSelf && !$isAdm && (int)($profile['profile_private'] ?? 0) === 1;
// Vérifier si ami (pour accès profil privé)
$isFriend = false;
try {
    $fChk = $pdo->prepare("SELECT id FROM friends WHERE user_id=? AND friend_id=? AND status='active'");
    $fChk->execute([$currentUserId, $targetId]);
    if ($fChk->fetch()) $isFriend = true;
} catch (Exception $e) {}
// Les amis peuvent voir le profil privé
if ($isPrivate && $isFriend) $isPrivate = false;

// Stats
$wonB  = (int)($profile['won_bets']          ?? 0);
$lostB = (int)($profile['lost_bets']         ?? 0);
$totB  = (int)($profile['total_bets']        ?? 0);
$rel   = (int)($profile['reliability_score'] ?? 100);
$ratio = $totB > 0 ? round($wonB / $totB * 100) : 0;

// Cercles
try {
    $cStmt = $pdo->prepare("SELECT c.id, c.name FROM circles c
        JOIN circle_members cm ON cm.circle_id = c.id WHERE cm.user_id = ?");
    $cStmt->execute([$targetId]);
    $cercles = $cStmt->fetchAll();
} catch (Exception $e) { $cercles = []; }

// Trophées
try {
    $allLevels = $pdo->query("SELECT * FROM trophy_levels ORDER BY requirement_value ASC")->fetchAll();
} catch (Exception $e) { $allLevels = []; }

$unlockedTrophies = [];
foreach ($allLevels as $lv) {
    $ok = false;
    switch ($lv['requirement_type']) {
        case 'win_count':   $ok = $wonB  >= (int)$lv['requirement_value']; break;
        case 'win_percent': $ok = $ratio >= (int)$lv['requirement_value']; break;
        case 'interaction': $ok = (int)($profile['interaction_points'] ?? 0) >= (int)$lv['requirement_value']; break;
        case 'reliability': $ok = $rel   >= (int)$lv['requirement_value']; break;
    }
    if ($ok) $unlockedTrophies[] = $lv;
}

// Gages récents
try {
    $whereH = $hasHiddenBets ? 'AND (b.hidden IS NULL OR b.hidden = 0)' : '';
    $bStmt  = $pdo->prepare("SELECT b.*, c.name as circle_name
        FROM bets b LEFT JOIN circles c ON c.id = b.circle_id
        WHERE b.user_id = ? {$whereH} ORDER BY b.id DESC LIMIT 5");
    $bStmt->execute([$targetId]);
    $recentBets = $bStmt->fetchAll();
} catch (Exception $e) { $recentBets = []; }

// Tier badge
$tier = $profile['tier'] ?? 'free';
$tierBadge = match($tier) {
    'premium'      => '<span class="badge badge-gold px-2">PREMIUM</span>',
    'premium_plus' => '<span class="badge badge-silver px-2">PREMIUM+</span>',
    'admin'        => '<span class="badge bg-danger px-2">ADMIN</span>',
    default        => '<span class="badge bg-secondary px-2">FREE</span>',
};

// Dates & statut
$since     = !empty($profile['created_at']) ? date('d M Y', strtotime($profile['created_at'])) : '—';
$lastLogin = '—';
$dotColor  = '#ffc107'; $dotLabel = 'Hors ligne';
if ($hasLastActivity && !empty($profile['last_activity'])) {
    $lastLogin = date('d M Y à H:i', strtotime($profile['last_activity']));
    $lastAct   = strtotime($profile['last_activity']);
    $isOnline  = (time() - $lastAct) < 300;
    $rs = $hasRoleStatus ? ($profile['role_status'] ?? 'offline') : 'offline';
    if ($isOnline && $rs === 'dnd') { $dotColor = '#dc3545'; $dotLabel = 'Ne pas déranger'; }
    elseif ($isOnline)              { $dotColor = '#28a745'; $dotLabel = 'En ligne'; }
}

// Visibilité contact
$showEmail = $isSelf || $isAdm || !($hasEmailPriv ? (int)($profile['email_private'] ?? 1) : 1);
$showPhone = $hasPhone && ($isSelf || $isAdm || !($hasPhonePriv ? (int)($profile['phone_private'] ?? 1) : 1));

include 'header.php';
?>

<style>
.badge-gold   { background:linear-gradient(45deg,#d4af37,#f1d592); color:#000; font-weight:bold; border:1px solid #b8860b; }
.badge-silver { background:linear-gradient(45deg,#a9a9a9,#e0e0e0); color:#000; font-weight:bold; border:1px solid #808080; }
.profile-bg   { background:linear-gradient(180deg,#1a1a2e 0%,#121212 100%); border-radius:8px; }
.stat-card    { background:#1a1a1a; border:1px solid #2a2a2a; border-radius:6px; padding:10px; text-align:center; }
</style>

<div class="container mt-4" style="max-width:900px;">

    <!-- En-tête -->
    <div class="profile-bg p-4 mb-3 d-flex align-items-center gap-4 flex-wrap">

        <div class="rounded-circle bg-primary d-flex align-items-center justify-content-center flex-shrink-0"
             style="width:80px;height:80px;font-size:2rem;font-weight:bold;color:#fff;">
            <?= strtoupper(mb_substr($profile['username'], 0, 1)) ?>
        </div>

        <div class="flex-grow-1">
            <div class="d-flex align-items-center gap-2 flex-wrap mb-1">
                <h4 class="text-white mb-0"><?= htmlspecialchars($profile['username']) ?></h4>
                <?php if ($hasNickname && !empty($profile['nickname'])): ?>
                    <small class="text-muted">(<?= htmlspecialchars(filterBadWords($profile['nickname'], $pdo)) ?>)</small>
                <?php endif; ?>
                <?= $tierBadge ?>
                <?php if ((int)($profile['admin'] ?? 0)): ?>
                    <span class="badge bg-danger">ADMIN</span>
                <?php endif; ?>
                <span style="width:9px;height:9px;border-radius:50%;background:<?= $dotColor ?>;display:inline-block;" title="<?= $dotLabel ?>"></span>
                <small class="text-muted" style="font-size:0.65rem;"><?= $dotLabel ?></small>
            </div>
            <small class="text-muted d-block" style="font-size:0.7rem;">
                Membre depuis <?= $since ?>
                <?php if ($hasLastActivity): ?> &nbsp;·&nbsp; Dernière activité : <?= $lastLogin ?><?php endif; ?>
            </small>
            <?php foreach ($cercles as $c): ?>
                <span class="badge bg-dark border border-info text-info me-1 mt-1" style="font-size:0.6rem;">
                    <?= htmlspecialchars($c['name']) ?>
                </span>
            <?php endforeach; ?>
        </div>

        <div class="d-flex flex-column gap-2">
            <?php if ($isSelf): ?>
                <a href="configuration.php" class="btn btn-outline-secondary btn-sm">
                    <i class="fa-solid fa-gear fa-xs"></i> Modifier mon profil
                </a>
                <a href="wallet.php" class="btn btn-outline-warning btn-sm">
                    <i class="fa-solid fa-coins fa-xs"></i> Mon portefeuille
                </a>
                <a href="user_score.php" class="btn btn-outline-info btn-sm">
                    <i class="fa-solid fa-star fa-xs"></i> Mon score
                </a>
            <?php else: ?>
                <?php if (!$isFriend): ?>
                    <button class="btn btn-outline-info btn-sm" onclick="addFriend(<?= $targetId ?>)">
                        <i class="fa-solid fa-user-plus fa-xs"></i> Ajouter ami
                    </button>
                <?php else: ?>
                    <span class="btn btn-outline-success btn-sm disabled">
                        <i class="fa-solid fa-user-check fa-xs"></i> Ami
                    </span>
                <?php endif; ?>
                <button class="btn btn-outline-secondary btn-sm" onclick="sendPokeProfile(<?= $targetId ?>)">Poke</button>
                <button class="btn btn-outline-warning btn-sm" onclick="openRating(<?= $targetId ?>, '<?= htmlspecialchars(addslashes($profile['username'])) ?>')">
                    Evaluer
                </button>
            <?php endif; ?>
        </div>
    </div>

    <div class="row g-3">

        <?php if ($isPrivate): ?>
        <div class="col-12">
            <div class="alert alert-secondary small py-2">
                Ce profil est privé. Ajoute cet utilisateur comme ami pour voir ses statistiques.
            </div>
        </div>
        <?php else: ?>

        <!-- Gauche : stats + contact -->
        <div class="col-md-4">

            <div class="card bg-dark border-secondary shadow mb-3">
                <div class="card-header bg-secondary text-white py-2 fw-bold small">STATISTIQUES</div>
                <div class="card-body p-3">
                    <div class="row g-2 mb-3">
                        <div class="col-6"><div class="stat-card"><div class="text-success fw-bold" style="font-size:1.3rem;"><?= $wonB ?></div><small style="color:#aaa;">Gagnés</small></div></div>
                        <div class="col-6"><div class="stat-card"><div class="text-danger fw-bold"  style="font-size:1.3rem;"><?= $lostB ?></div><small style="color:#aaa;">Perdus</small></div></div>
                        <div class="col-6"><div class="stat-card"><div class="text-primary fw-bold" style="font-size:1.3rem;"><?= $ratio ?>%</div><small style="color:#aaa;">Victoires</small></div></div>
                        <div class="col-6"><div class="stat-card"><div class="text-warning fw-bold" style="font-size:1.3rem;"><?= $rel ?>%</div><small style="color:#aaa;">Fiabilite</small></div></div>
                    </div>
                    <div class="d-flex justify-content-between small mb-1">
                        <span style="color:#aaa;">Points d'honneur</span>
                        <span class="text-success fw-bold"><?= (int)($profile['points'] ?? 0) ?></span>
                    </div>
                    <?php if ($hasInteraction): ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span style="color:#aaa;">Points interaction</span>
                        <span class="text-info fw-bold"><?= (int)($profile['interaction_points'] ?? 0) ?></span>
                    </div>
                    <?php endif; ?>
                    <?php
                    // Jetons (si visible)
                    $walletPts = (int)($profile['wallet_points'] ?? 0);
                    if ($isSelf || $walletPts > 0):
                    ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span style="color:#aaa;">Jetons</span>
                        <span class="text-warning fw-bold"><?= number_format($walletPts) ?></span>
                    </div>
                    <?php endif; ?>
                    <?php
                    // Notation moyenne reçue
                    try {
                        $rStmt = $pdo->prepare("SELECT AVG(stars) as avg, COUNT(*) as total FROM user_ratings WHERE rated_id=?");
                        $rStmt->execute([$targetId]);
                        $ratingRow = $rStmt->fetch();
                        $avgStars  = round((float)($ratingRow['avg'] ?? 0), 1);
                        $nbRatings = (int)($ratingRow['total'] ?? 0);
                    } catch (Exception $e) { $avgStars = 0; $nbRatings = 0; }
                    if ($nbRatings > 0):
                    ?>
                    <div class="d-flex justify-content-between small mb-1">
                        <span style="color:#aaa;">Reputation</span>
                        <span class="text-warning fw-bold">
                            <?= $avgStars ?>/5
                            <small style="color:#666;font-size:0.6rem;">(<?= $nbRatings ?>)</small>
                        </span>
                    </div>
                    <?php endif; ?>
                    <?php
                    // Gages non honorés
                    try {
                        $nhStmt = $pdo->prepare("SELECT COUNT(*) FROM bets WHERE not_honored=1 AND (user_id=? OR parieur2_id=?)");
                        $nhStmt->execute([$targetId, $targetId]);
                        $nbNH = (int)$nhStmt->fetchColumn();
                    } catch (Exception $e) { $nbNH = 0; }
                    if ($nbNH > 0):
                    ?>
                    <div class="d-flex justify-content-between small">
                        <span style="color:#aaa;">Non honores</span>
                        <span class="text-danger fw-bold"><?= $nbNH ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($showEmail || $showPhone): ?>
            <div class="card bg-dark border-secondary shadow mb-3">
                <div class="card-header bg-secondary text-white py-2 fw-bold small"> CONTACT</div>
                <div class="card-body p-3">
                    <?php if ($showEmail): ?>
                    <div class="d-flex justify-content-between small mb-2">
                        <span class="text-muted">Courriel</span>
                        <span class="text-info" style="word-break:break-all;"><?= htmlspecialchars($profile['email']) ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($showPhone && !empty($profile['phone'])): ?>
                    <div class="d-flex justify-content-between small">
                        <span class="text-muted">Téléphone</span>
                        <span class="text-white"><?= htmlspecialchars($profile['phone']) ?></span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

        </div>

        <!-- Droite : trophées + gages -->
        <div class="col-md-8">

            <div class="card bg-dark border-secondary shadow mb-3">
                <div class="card-header bg-warning text-dark py-2 fw-bold small">
                     TROPHÉES DÉBLOQUÉS (<?= count($unlockedTrophies) ?>)
                </div>
                <div class="card-body p-3">
                    <?php if (empty($unlockedTrophies)): ?>
                        <p class="text-muted small mb-0">Aucun trophée encore. Les exploits arrivent !</p>
                    <?php else: ?>
                    <div class="d-flex flex-wrap gap-2">
                        <?php foreach ($unlockedTrophies as $t): ?>
                        <div class="text-center p-2 border border-warning rounded"
                             style="min-width:80px;max-width:90px;"
                             title="<?= htmlspecialchars($t['description'] ?? '') ?>">
                            <?php if (!empty($t['icon_path']) && file_exists(__DIR__.'/'.$t['icon_path'])): ?>
                                <img src="<?= htmlspecialchars($t['icon_path']) ?>" style="width:30px;height:30px;object-fit:contain;">
                            <?php else: ?>
                                <div style="font-size:1.5rem;"></div>
                            <?php endif; ?>
                            <div class="text-white" style="font-size:0.62rem;font-weight:bold;word-break:break-word;">
                                <?= htmlspecialchars($t['title'] ?? '') ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card bg-dark border-secondary shadow">
                <div class="card-header bg-secondary text-white py-2 fw-bold small"> GAGES RÉCENTS</div>
                <div class="card-body p-0">
                    <?php if (empty($recentBets)): ?>
                        <p class="text-muted small p-3 mb-0">Aucun gage public pour l'instant.</p>
                    <?php else: ?>
                    <table class="table table-dark table-hover table-sm small mb-0">
                        <thead>
                            <tr><th class="ps-3">#</th><th>Defi</th><th>Cercle</th><th class="text-center">Pts</th><th class="text-center">Statut</th></tr>
                        </thead>
                        <tbody>
                        <?php foreach ($recentBets as $b): ?>
                        <tr>
                            <td class="ps-3 text-muted"><?= $b['id'] ?></td>
                            <td>
                                <?= htmlspecialchars(mb_substr($b['description'] ?? '', 0, 40)) ?><?= strlen($b['description'] ?? '') > 40 ? '...' : '' ?>
                                <?php if (!empty($b['wallet_stake']) && (int)$b['wallet_stake'] > 0): ?>
                                <span class="badge bg-warning text-dark ms-1" style="font-size:0.5rem;"><?= (int)$b['wallet_stake'] ?> jetons</span>
                                <?php endif; ?>
                            </td>
                            <td><small class="text-info"><?= htmlspecialchars($b['circle_name'] ?? 'Global') ?></small></td>
                            <td class="text-center text-success"><?= (int)($b['amount'] ?? 0) ?></td>
                            <td class="text-center">
                                <?php
                                $st = $b['status'] ?? 'pending';
                                $badgeClass = match($st) { 'won'=>'bg-success','lost'=>'bg-danger','pending'=>'bg-warning text-dark',default=>'bg-secondary' };
                                $stLabel    = match($st) { 'won'=>'Gagne','lost'=>'Perdu','pending'=>'En cours',default=>$st };
                                echo '<span class="badge '.$badgeClass.'" style="font-size:0.55rem;">'.$stLabel.'</span>';
                                if (!empty($b['not_honored'])) echo '<span class="badge bg-danger ms-1" style="font-size:0.5rem;">Non honore</span>';
                                elseif (!empty($b['honored'])) echo '<span class="badge bg-success ms-1" style="font-size:0.5rem;">Honore</span>';
                                ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>

    <div class="text-center mt-3">
        <a href="index.php" class="text-muted small text-decoration-none">← Retour au Dashboard</a>
    </div>
    <?php endif; // profil privé ?>
</div>

<script>
function addFriend(id) {
    fetch('friend_actions.php?action=request&id=' + id)
        .then(() => { location.reload(); });
}
function sendPokeProfile(id) {
    fetch('friend_actions.php?action=poke&id=' + id)
        .then(() => alert('Poke envoye !'));
}
let currentRatedId = 0, currentRating = 3;
function openRating(id, name) {
    currentRatedId = id; currentRating = 3;
    document.getElementById('ratingTitleP').innerText = 'Evaluer ' + name;
    updateStarsP(3);
    new bootstrap.Modal(document.getElementById('ratingModalP')).show();
}
function setRatingP(val) { currentRating = val; updateStarsP(val); }
function updateStarsP(val) {
    document.getElementById('ratingValueP').innerText = val + '/5';
    document.querySelectorAll('#starSelectorP span').forEach((s,i) => { s.style.opacity = i < val ? '1' : '0.3'; });
}
function submitRatingP() {
    const comment = document.getElementById('ratingCommentP').value;
    const fd = new FormData();
    fd.append('rated_id', currentRatedId);
    fd.append('stars', currentRating);
    fd.append('comment', comment);
    fetch('rate_user.php', { method:'POST', body:fd })
        .then(r => r.json())
        .then(d => {
            bootstrap.Modal.getInstance(document.getElementById('ratingModalP')).hide();
            if (d.success) alert('Note envoyee : ' + currentRating + '/5 !');
        });
}
</script>

<!-- Modale notation -->
<div class="modal fade" id="ratingModalP" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content bg-dark border-warning text-white">
            <div class="modal-header border-secondary py-2">
                <h6 class="modal-title text-warning fw-bold" id="ratingTitleP">Evaluer</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body text-center">
                <div id="starSelectorP" style="font-size:2rem;cursor:pointer;letter-spacing:4px;color:#ffc107;">
                    <span onclick="setRatingP(1)">&#9733;</span><span onclick="setRatingP(2)">&#9733;</span>
                    <span onclick="setRatingP(3)">&#9733;</span><span onclick="setRatingP(4)">&#9733;</span>
                    <span onclick="setRatingP(5)">&#9733;</span>
                </div>
                <div id="ratingValueP" class="text-warning small mb-2">3/5</div>
                <input type="text" id="ratingCommentP" class="form-control form-control-sm bg-dark text-white border-secondary"
                       placeholder="Commentaire (opt.)..." maxlength="200">
            </div>
            <div class="modal-footer border-secondary py-2">
                <button class="btn btn-warning fw-bold w-100" onclick="submitRatingP()">ENVOYER</button>
            </div>
        </div>
    </div>
</div>

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