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

// Verifique se está logado como superadmin
if (!isset($_SESSION['superadmin_id'])) {
    header("Location: login.php");
    exit;
}

// Bloquear ou desbloquear usuário via GET (?block=id ou ?unblock=id)
if (isset($_GET['block'])) {
    $id = intval($_GET['block']);
    $stmt = $pdo->prepare("UPDATE users SET active = 0 WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: usuarios.php');
    exit;
}
if (isset($_GET['unblock'])) {
    $id = intval($_GET['unblock']);
    $stmt = $pdo->prepare("UPDATE users SET active = 1 WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: usuarios.php');
    exit;
}

// Busque todos os usuários
$stmt = $pdo->query("SELECT id, name, email, active, created_at FROM users ORDER BY id DESC");
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Gerenciar Usuários</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700;400&display=swap" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {margin:0;font-family:'Montserrat',Arial,sans-serif;background:#F5FAFF;}
        .sidebar { position:fixed;left:0;top:0;bottom:0;width:220px;background:#1876F2;color:#fff;display:flex;flex-direction:column;align-items:center;padding-top:32px;box-shadow:2px 0 12px rgba(24,118,242,0.10);z-index:100;}
        .sidebar .logo { font-size:1.6rem;font-weight:700;margin-bottom:34px;letter-spacing:0.03em;}
        .sidebar nav {width:100%;}
        .sidebar nav a { display:flex;align-items:center;gap:13px;color:#fff;text-decoration:none;font-size:1.08rem;font-weight:600;padding:12px 28px;margin:2px 0;border-radius:8px 0 0 8px;transition:background 0.17s;}
        .sidebar nav a.active, .sidebar nav a:hover {background:#1356b3;}
        .sidebar .bottom {margin-top:auto;margin-bottom:34px;}
        .sidebar .logout-link {color:#eaf4ff;font-weight:700;font-size:1.02rem;text-decoration:underline;background:none;border:none;cursor:pointer;padding:0;}
        .main-content {margin-left:220px;padding:38px 18px;max-width:1100px;}
        .title-row {display:flex;align-items:center;gap:14px;margin-bottom:24px;}
        .title-row .fa-user {font-size:2.1rem;color:#1876F2;}
        .title-row h2 {font-size:1.5rem;font-weight:700;color:#212a3e;margin:0;}
        .usuarios-table {width:100%;border-collapse:collapse;background:#fff;border-radius:10px;box-shadow:0 2px 14px rgba(24,118,242,0.07);overflow:hidden;}
        .usuarios-table th, .usuarios-table td {padding:13px 10px;text-align:left;}
        .usuarios-table th {background:#eef4fd;color:#1876F2;font-size:1.04rem;font-weight:700;}
        .usuarios-table tr:not(:last-child) td { border-bottom:1px solid #f1f4fa; }
        .usuarios-table td { font-size:1.01rem; }
        .badge { padding:4px 13px;border-radius:20px;font-size:0.97rem;font-weight:600;display:inline-block;}
        .badge-liberado { background:#eafff4;color:#1bbf5c; }
        .badge-bloq { background:#ffeaea;color:#d9534f; }
        .action-btn {border:none;background:none;color:#1876F2;cursor:pointer;font-size:1.15rem;margin-right:6px;transition:color 0.15s;}
        .action-btn:hover { color:#1356b3;}
        .action-btn.block {color:#d9534f;}
        .action-btn.block:hover {color:#b80000;}
        .action-btn.unblock {color:#1bbf5c;}
        .action-btn.unblock:hover {color:#048e3c;}
        @media(max-width:900px) {
            .main-content{margin-left:0;padding:15px 3vw;}
            .sidebar{position:relative;width:100%;height:auto;box-shadow:none;padding:14px 0;}
            .sidebar .logo{font-size:1.2rem;}
            .sidebar nav{gap:5px;width:auto;display:flex;}
            .sidebar nav a{font-size:0.99rem;padding:8px 14px;}
            .usuarios-table th, .usuarios-table td{font-size:0.97rem;padding:8px 5px;}
        }
        .usuarios-table-container {overflow-x:auto;border-radius:10px;background:#fff;}
        /* Popup Modal */
        .modal-bg {
            display:none; position:fixed; top:0; left:0; width:100vw; height:100vh;
            background:rgba(24, 118, 242, 0.26); z-index:2000; align-items:center; justify-content:center;
        }
        .modal-bg.active {display:flex;}
        .modal {
            background:#fff; padding:30px 28px 22px 28px; border-radius:11px; box-shadow:0 2px 20px #1876f250;
            min-width:300px; max-width:96vw; text-align:center; position:relative; animation:fadeIn .22s;
        }
        @keyframes fadeIn {from{opacity:0;transform:translateY(20px);}to{opacity:1;transform:none;}}
        .modal h3{margin:0 0 14px 0;color:#222;}
        .modal .modal-msg {font-size:1.08rem;color:#334;}
        .modal .modal-actions {margin-top:26px;display:flex;gap:13px;justify-content:center;}
        .modal .modal-btn {
            min-width:90px;
            padding:9px 0; border-radius:7px; border:none; font-size:1.04rem; font-weight:700; cursor:pointer; transition:background 0.16s;
        }
        .modal .cancel {background:#eee;color:#333;}
        .modal .confirm-block {background:#d9534f;color:#fff;}
        .modal .confirm-unblock {background:#1bbf5c;color:#fff;}
    </style>
</head>
<body>
    <aside class="sidebar">
        <div class="logo">
            <i class="fa-solid fa-shield-halved"></i> Fiado Fácil
        </div>
        <nav>
            <a href="dashboard.php"><i class="fa-solid fa-gauge"></i> Dashboard</a>
            <a href="clientes.php"><i class="fa-solid fa-users"></i> Clientes</a>
            <a href="usuarios.php" class="active"><i class="fa-solid fa-user"></i> Usuários</a>
        </nav>
        <div class="bottom">
            <a href="logout.php" class="logout-link"><i class="fa-solid fa-right-from-bracket"></i> Sair</a>
        </div>
    </aside>
    <div class="main-content">
        <div class="title-row">
            <i class="fa-solid fa-user"></i>
            <h2>Gerenciar Usuários</h2>
        </div>
        <div class="usuarios-table-container">
            <table class="usuarios-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Nome</th>
                        <th>Email</th>
                        <th>Status</th>
                        <th>Criado em</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach($usuarios as $usuario): ?>
                    <tr>
                        <td><?= htmlspecialchars($usuario['id']) ?></td>
                        <td><?= htmlspecialchars($usuario['name']) ?></td>
                        <td><?= htmlspecialchars($usuario['email']) ?></td>
                        <td>
                            <?php if($usuario['active']): ?>
                                <span class="badge badge-liberado">Liberado</span>
                            <?php else: ?>
                                <span class="badge badge-bloq">Bloqueado</span>
                            <?php endif; ?>
                        </td>
                        <td><?= date('d/m/Y H:i', strtotime($usuario['created_at'])) ?></td>
                        <td>
                            <?php if($usuario['active']): ?>
                                <button class="action-btn block" title="Bloquear"
                                    onclick="confirmBlockUser(<?= $usuario['id'] ?>, '<?= htmlspecialchars(addslashes($usuario['name'])) ?>')">
                                    <i class="fa-solid fa-user-lock"></i>
                                </button>
                            <?php else: ?>
                                <button class="action-btn unblock" title="Liberar"
                                    onclick="confirmUnblockUser(<?= $usuario['id'] ?>, '<?= htmlspecialchars(addslashes($usuario['name'])) ?>')">
                                    <i class="fa-solid fa-user-check"></i>
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (count($usuarios) === 0): ?>
                    <tr><td colspan="6" style="text-align:center;color:#888;">Nenhum usuário encontrado.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <!-- Modal de confirmação -->
    <div class="modal-bg" id="modal-bg">
        <div class="modal" id="modal">
            <h3 id="modal-title">Confirmação</h3>
            <div class="modal-msg" id="modal-msg">
                <!-- Mensagem aqui -->
            </div>
            <div class="modal-actions">
                <button class="modal-btn cancel" onclick="closeModal()">Cancelar</button>
                <button class="modal-btn confirm-block" id="modal-confirm-block" style="display:none;">Bloquear</button>
                <button class="modal-btn confirm-unblock" id="modal-confirm-unblock" style="display:none;">Liberar</button>
            </div>
        </div>
    </div>
    <script>
        let modalBg = document.getElementById('modal-bg');
        let modalMsg = document.getElementById('modal-msg');
        let modalTitle = document.getElementById('modal-title');
        let confirmBlockBtn = document.getElementById('modal-confirm-block');
        let confirmUnblockBtn = document.getElementById('modal-confirm-unblock');
        let actionUrl = '';

        function closeModal() {
            modalBg.classList.remove('active');
            confirmBlockBtn.style.display = 'none';
            confirmUnblockBtn.style.display = 'none';
            actionUrl = '';
        }
        // Abrir modal para bloquear
        function confirmBlockUser(id, name) {
            modalTitle.innerText = 'Bloquear Usuário';
            modalMsg.innerHTML = 'Tem certeza que deseja <b>bloquear</b> o usuário <span style="color:#d9534f;">'+name+'</span>?';
            confirmBlockBtn.style.display = 'inline-block';
            confirmUnblockBtn.style.display = 'none';
            actionUrl = '?block=' + id;
            modalBg.classList.add('active');
        }
        // Abrir modal para desbloquear
        function confirmUnblockUser(id, name) {
            modalTitle.innerText = 'Liberar Usuário';
            modalMsg.innerHTML = 'Tem certeza que deseja <b>liberar</b> o usuário <span style="color:#1bbf5c;">'+name+'</span>?';
            confirmBlockBtn.style.display = 'none';
            confirmUnblockBtn.style.display = 'inline-block';
            actionUrl = '?unblock=' + id;
            modalBg.classList.add('active');
        }
        // Ao clicar em bloquear/desbloquear no modal
        confirmBlockBtn.onclick = function() {
            window.location = actionUrl;
        };
        confirmUnblockBtn.onclick = function() {
            window.location = actionUrl;
        };
        // Fechar modal ao clicar fora dele
        modalBg.onclick = function(e) {
            if (e.target === modalBg) closeModal();
        }
        // Fechar com ESC
        document.addEventListener('keydown', function(e){
            if(e.key === "Escape") closeModal();
        });
    </script>
</body>
</html>