<?php
// admin/verified_manage.php
require_once '../config/db.php';


// 1. SEGURIDAD: Solo administradores pueden entrar aquí
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header("Location: ../index.php");
    exit;
}

// 2. LÓGICA DE ACTUALIZACIÓN DE MEDALLAS
if (isset($_GET['toggle']) && isset($_GET['u_id'])) {
    $u_id = (int)$_GET['u_id'];
    $badge = $_GET['toggle']; // puede ser 'is_verified', 'is_fast_seller' o 'is_trusted'
    
    // Validamos que el nombre de la columna sea uno de los permitidos
    $allowed = ['is_verified', 'is_fast_seller', 'is_trusted'];
    
    if (in_array($badge, $allowed)) {
        // Buscamos si el usuario ya tiene registro en la tabla de medallas
        $check = $pdo->prepare("SELECT $badge FROM user_verifications WHERE user_id = ?");
        $check->execute([$u_id]);
        $exists = $check->fetch();

        if ($exists) {
            // Si ya existe la fila, invertimos el valor (1 -> 0 o 0 -> 1)
            $new_val = ($exists[$badge] == 1) ? 0 : 1;
            $update = $pdo->prepare("UPDATE user_verifications SET $badge = ? WHERE user_id = ?");
            $update->execute([$new_val, $u_id]);
        } else {
            // Si no existe la fila para este usuario, la creamos activando la medalla clicada
            $insert = $pdo->prepare("INSERT INTO user_verifications (user_id, $badge) VALUES (?, 1)");
            $insert->execute([$u_id]);
        }
    }
    // Redirigimos para limpiar la URL y mostrar mensaje de éxito
    header("Location: verified_manage.php?success=1");
    exit;
}

// 3. OBTENER LISTADO DE USUARIOS Y SUS MEDALLAS (COALESCE para evitar nulos)
$users = $pdo->query("
    SELECT u.id, u.username, u.email, 
           COALESCE(v.is_verified, 0) as is_verified, 
           COALESCE(v.is_fast_seller, 0) as is_fast_seller, 
           COALESCE(v.is_trusted, 0) as is_trusted 
    FROM users u 
    LEFT JOIN user_verifications v ON u.id = v.user_id 
    ORDER BY u.id DESC
")->fetchAll(PDO::FETCH_ASSOC);

include '../includes/header.php';
?>

<div style="max-width: 1000px; margin: 40px auto; padding: 0 20px;">
    
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
        <div>
            <h2 style="color: white; margin: 0; font-size: 24px;">🎖️ Gestión de Medallas</h2>
            <p style="color: var(--primary); margin: 5px 0 0 0; font-size: 14px;">Activa o desactiva los rangos especiales para los vendedores de VVault.</p>
        </div>
        <a href="addons.php" style="color: var(--text-gray); text-decoration: none; border: 1px solid var(--border); padding: 8px 16px; border-radius: 8px; font-size: 13px;">
            <i class="fa-solid fa-arrow-left"></i> Volver
        </a>
    </div>

    <?php if(isset($_GET['success'])): ?>
        <div style="background: rgba(0, 255, 136, 0.1); color: #00ff88; padding: 12px; border-radius: 8px; margin-bottom: 20px; text-align: center; font-size: 14px; border: 1px solid rgba(0, 255, 136, 0.2);">
            <i class="fa-solid fa-check-circle"></i> Los cambios se han guardado correctamente.
        </div>
    <?php endif; ?>

    <div style="background: var(--nav-bg); border: 1px solid var(--border); border-radius: 15px; overflow: hidden;">
        <table style="width: 100%; border-collapse: collapse; color: white;">
            <thead style="background: rgba(255,255,255,0.03); text-align: left; font-size: 11px; color: var(--text-gray); text-transform: uppercase;">
                <tr>
                    <th style="padding: 20px;">Usuario / Email</th>
                    <th style="padding: 20px; text-align: center;">Verificado</th>
                    <th style="padding: 20px; text-align: center;">Rayo</th>
                    <th style="padding: 20px; text-align: center;">Escudo</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($users as $u): ?>
                <tr style="border-bottom: 1px solid var(--border);">
                    <td style="padding: 20px;">
                        <div style="font-weight: bold; font-size: 15px; color: #fff;">@<?php echo htmlspecialchars($u['username']); ?></div>
                        <div style="font-size: 12px; color: var(--text-gray);"><?php echo $u['email']; ?></div>
                    </td>
                    
                    <td style="padding: 20px; text-align: center;">
                        <a href="?toggle=is_verified&u_id=<?php echo $u['id']; ?>" 
                           style="color: <?php echo $u['is_verified'] ? '#3897f0' : '#222'; ?>; font-size: 24px; text-decoration: none;">
                            <i class="fa-solid <?php echo $u['is_verified'] ? 'fa-circle-check' : 'fa-circle-dot'; ?>"></i>
                        </a>
                    </td>

                    <td style="padding: 20px; text-align: center;">
                        <a href="?toggle=is_fast_seller&u_id=<?php echo $u['id']; ?>" 
                           style="color: <?php echo $u['is_fast_seller'] ? '#ffcc00' : '#222'; ?>; font-size: 24px; text-decoration: none;">
                            <i class="fa-solid fa-bolt"></i>
                        </a>
                    </td>

                    <td style="padding: 20px; text-align: center;">
                        <a href="?toggle=is_trusted&u_id=<?php echo $u['id']; ?>" 
                           style="color: <?php echo $u['is_trusted'] ? '#00ff88' : '#222'; ?>; font-size: 24px; text-decoration: none;">
                            <i class="fa-solid fa-shield-halved"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

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