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

if (!isset($_SESSION['user_id'])) { exit; }
$userId = (int)$_SESSION['user_id'];

try {
    // Demandes en attente
    $pendingStmt = $pdo->prepare("
        SELECT u.id, u.username
        FROM friends f
        JOIN users u ON u.id = f.user_id
        WHERE f.friend_id = ? AND f.status = 'pending'
        ORDER BY f.created_at DESC
    ");
    $pendingStmt->execute([$userId]);
    $pending = $pendingStmt->fetchAll();

    if (!empty($pending)):
?>
<div style="background:#110e00;border:1px solid rgba(255,193,7,0.3);border-radius:8px;padding:8px 10px;margin-bottom:8px;">
    <div style="font-size:0.58rem;color:#ffc107;font-weight:bold;letter-spacing:1.5px;margin-bottom:6px;display:flex;align-items:center;gap:5px;">
        <span style="width:6px;height:6px;border-radius:50%;background:#ffc107;box-shadow:0 0 6px #ffc107;display:inline-block;"></span>
        DEMANDES EN ATTENTE (<?= count($pending) ?>)
    </div>
    <?php foreach ($pending as $p):
        $pName = htmlspecialchars($p['username']);
        $pId   = (int)$p['id'];
    ?>
    <div style="display:flex;align-items:center;gap:8px;padding:6px 0;border-bottom:1px solid #1a1400;" id="pending-row-<?= $pId ?>">
        <div style="width:28px;height:28px;border-radius:50%;background:#0d6efd;display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0;">
            <?= strtoupper(mb_substr($p['username'],0,1)) ?>
        </div>
        <span style="flex:1;font-size:0.72rem;color:#ddd;font-weight:600;"><?= $pName ?></span>
        <span style="display:flex;gap:4px;">
            <button onclick="panelAcceptFriend(<?= $pId ?>)"
                    style="background:rgba(40,167,69,0.2);border:1px solid #28a745;color:#777;border-radius:5px;padding:3px 10px;font-size:0.65rem;font-weight:700;cursor:pointer;">
                ✓ Accepter
            </button>
            <button onclick="panelDeclineFriend(<?= $pId ?>)"
                    style="background:rgba(220,53,69,0.12);border:1px solid #dc3545;color:#dc3545;border-radius:5px;padding:3px 10px;font-size:0.65rem;font-weight:700;cursor:pointer;">
                ✗ Refuser
            </button>
        </span>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php
    // Liste des amis actifs
    $stmt = $pdo->prepare("
        SELECT u.id, u.username, u.nickname, u.role_status, u.last_activity, f.is_favorite
        FROM friends f
        JOIN users u ON u.id = f.friend_id
        WHERE f.user_id = ? AND f.status = 'active'
        ORDER BY f.is_favorite DESC, u.username ASC
    ");
    $stmt->execute([$userId]);
    $friends = $stmt->fetchAll();

    if (empty($friends) && empty($pending)):
?>
<div style="text-align:center;padding:20px 0;color:#888;font-size:0.72rem;">
    Aucun ami pour l'instant<br>
    <span style="font-size:0.6rem;">Recherchez un membre ci-dessus</span>
</div>
<?php endif; ?>

<?php if (!empty($friends)): ?>
<div style="font-size:0.6rem;color:#888;letter-spacing:1px;margin-bottom:4px;">
    AMIS (<?= count($friends) ?>)
</div>
<?php foreach ($friends as $f):
    $lastAct  = strtotime($f['last_activity'] ?? '2000-01-01');
    $minAgo   = (time() - $lastAct) / 60;
    $daysAgo  = (time() - $lastAct) / 86400;
    $status   = $f['role_status'] ?? 'offline';

    if      ($status === 'dnd')   { $dot = '#dc3545'; $shadow = ''; $tip = 'Ne pas déranger'; }
    elseif  ($minAgo <= 15)       { $dot = '#28a745'; $shadow = 'box-shadow:0 0 6px #28a745;'; $tip = 'En ligne'; }
    elseif  ($daysAgo <= 7)       { $dot = '#ffc107'; $shadow = ''; $tip = 'Actif cette semaine'; }
    else                          { $dot = '#444';    $shadow = ''; $tip = 'Inactif'; }

    $name   = htmlspecialchars($f['username']);
    $nameJs = htmlspecialchars(addslashes($f['username']), ENT_QUOTES);
    $isFav  = (int)$f['is_favorite'];
    $surnom = !empty($f['nickname'])
        ? '<div style="color:#888;font-size:0.6rem;line-height:1.1;margin-top:1px;">'.htmlspecialchars($f['nickname']).'</div>'
        : '';
    $favIcon = $isFav ? '<span style="color:#ffc107;font-size:0.65rem;margin-right:3px;">⭐</span>' : '';
?>
<div onclick="panelOpenFriendMenu(<?= $f['id'] ?>, '<?= $nameJs ?>', <?= $isFav ?>)"
     style="display:flex;align-items:center;gap:8px;padding:6px 8px;border-radius:5px;cursor:pointer;border-bottom:1px solid #111;transition:background 0.15s;"
     onmouseover="this.style.background='#0d0d1a'"
     onmouseout="this.style.background='transparent'">
    <span style="width:8px;height:8px;border-radius:50%;display:inline-block;flex-shrink:0;background:<?= $dot ?>;<?= $shadow ?>"
          title="<?= $tip ?>"></span>
    <div style="flex:1;min-width:0;">
        <?= $favIcon ?>
        <span style="font-size:0.72rem;color:#ddd;"><?= $name ?></span>
        <?= $surnom ?>
    </div>
    <span style="font-size:0.6rem;color:#888;flex-shrink:0;">›</span>
</div>
<?php endforeach; ?>
<?php endif; ?>

<?php
} catch (Exception $e) {
    echo '<div style="color:#dc3545;font-size:0.7rem;padding:8px;text-align:center;">Erreur de chargement</div>';
}
?>
