<?php
require_once '../config/database.php';
require_once '../config/auth.php';
requireLogin('admin', 'index.php');

$db = Database::getInstance()->getConnection();
$sucesso = '';
$erro = '';

// Ações de bloqueio/desbloqueio
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = intval($_POST['user_id'] ?? 0);
    
    if (isset($_POST['bloquear'])) {
        $motivo = trim($_POST['motivo'] ?? '');
        $stmt = $db->prepare("UPDATE usuarios SET bloqueado = 1, motivo_bloqueio = ? WHERE id = ?");
        $stmt->execute([$motivo, $userId]);
        $sucesso = 'Cliente bloqueado com sucesso!';
    }
    
    if (isset($_POST['desbloquear'])) {
        $stmt = $db->prepare("UPDATE usuarios SET bloqueado = 0, motivo_bloqueio = NULL WHERE id = ?");
        $stmt->execute([$userId]);
        $sucesso = 'Cliente desbloqueado com sucesso!';
    }
}

// Buscar usuários com estatísticas
$stmt = $db->query("
    SELECT u.*, 
           (SELECT COUNT(*) FROM entregas WHERE usuario_id = u.id) as total_entregas,
           (SELECT COALESCE(SUM(valor), 0) FROM entregas WHERE usuario_id = u.id) as total_gasto
    FROM usuarios u
    ORDER BY u.created_at DESC
");
$usuarios = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Usuários - Admin</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/admin.css">
    <script src="../assets/js/admin-theme.js"></script>
    <style>
        .status-bloqueado {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: #ffebee;
            color: #c62828;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }
        [data-theme="dark"] .status-bloqueado {
            background: rgba(198, 40, 40, 0.2);
        }
        .status-ativo {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: #e8f5e9;
            color: #2e7d32;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }
        [data-theme="dark"] .status-ativo {
            background: rgba(46, 125, 50, 0.2);
        }
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }
        .modal.show { display: flex; }
        .modal-content {
            background: var(--bg-secondary);
            padding: 24px;
            border-radius: 12px;
            width: 100%;
            max-width: 450px;
            color: var(--text-primary);
        }
        .modal-content h3 {
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
    </style>
</head>
<body class="admin-panel">
    <header class="header">
        <h1>⚙️ Já EntreGo Admin</h1>
        <nav>
            <a href="dashboard.php">Dashboard</a>
            <a href="entregas.php">Entregas</a>
            <a href="entregadores.php">Entregadores</a>
            <a href="usuarios.php">Usuários</a>
            <a href="parceiros.php">Parceiros</a>
            <a href="configuracoes.php">Configurações</a>
            <a href="perfil.php">Perfil</a>
            <a href="logout.php">Sair</a>
            <div class="theme-toggle">
                <button type="button" id="theme-toggle-btn" class="theme-toggle-btn" onclick="toggleTheme()" title="Alternar tema">🌙</button>
            </div>
        </nav>
    </header>
    
    <div class="container">
        <h2 style="margin-bottom: 20px;">👥 Clientes Cadastrados</h2>
        
        <?php if ($sucesso): ?>
            <div class="alert alert-success"><?= htmlspecialchars($sucesso) ?></div>
        <?php endif; ?>
        
        <?php if ($erro): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($erro) ?></div>
        <?php endif; ?>
        
        <div class="card">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Nome</th>
                        <th>Email</th>
                        <th>Telefone</th>
                        <th>Status</th>
                        <th>Entregas</th>
                        <th>Total Gasto</th>
                        <th>Cadastro</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($usuarios as $u): ?>
                    <tr>
                        <td>#<?= $u['id'] ?></td>
                        <td><?= htmlspecialchars($u['nome']) ?></td>
                        <td><?= htmlspecialchars($u['email']) ?></td>
                        <td><?= $u['telefone'] ? htmlspecialchars($u['telefone']) : '-' ?></td>
                        <td>
                            <?php if (!empty($u['bloqueado'])): ?>
                                <span class="status-bloqueado">🔒 Bloqueado</span>
                            <?php else: ?>
                                <span class="status-ativo">✅ Ativo</span>
                            <?php endif; ?>
                        </td>
                        <td><?= $u['total_entregas'] ?></td>
                        <td>R$ <?= number_format($u['total_gasto'], 2, ',', '.') ?></td>
                        <td><?= date('d/m/Y', strtotime($u['created_at'])) ?></td>
                        <td>
                            <?php if (!empty($u['bloqueado'])): ?>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                    <button type="submit" name="desbloquear" class="btn btn-success btn-sm">
                                        🔓 Desbloquear
                                    </button>
                                </form>
                            <?php else: ?>
                                <button type="button" class="btn btn-danger btn-sm" onclick="abrirModalBloquear(<?= $u['id'] ?>, '<?= htmlspecialchars($u['nome'], ENT_QUOTES) ?>')">
                                    🔒 Bloquear
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            
            <?php if (empty($usuarios)): ?>
                <p style="text-align: center; padding: 40px; color: var(--text-muted);">Nenhum usuário cadastrado</p>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Modal Bloquear -->
    <div class="modal" id="modal-bloquear">
        <div class="modal-content">
            <h3>🔒 Bloquear Cliente</h3>
            <p style="margin-bottom: 16px; color: var(--text-secondary);">
                Tem certeza que deseja bloquear <strong id="nome-usuario"></strong>?
            </p>
            <form method="POST">
                <input type="hidden" name="user_id" id="bloquear-user-id">
                <div class="form-group">
                    <label>Motivo do bloqueio (opcional)</label>
                    <textarea name="motivo" class="form-control" rows="3" placeholder="Informe o motivo..."></textarea>
                </div>
                <div style="display: flex; gap: 10px;">
                    <button type="submit" name="bloquear" class="btn btn-danger">🔒 Confirmar Bloqueio</button>
                    <button type="button" class="btn" style="background: var(--border-color);" onclick="fecharModal()">Cancelar</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
    function abrirModalBloquear(id, nome) {
        document.getElementById('bloquear-user-id').value = id;
        document.getElementById('nome-usuario').textContent = nome;
        document.getElementById('modal-bloquear').classList.add('show');
    }
    
    function fecharModal() {
        document.getElementById('modal-bloquear').classList.remove('show');
    }
    </script>
</body>
</html>
