<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireAdmin();

$msg = '';
$msg_type = '';

// ============================================================
// AÇÃO: Criar novo usuário
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create_user') {
    $nome  = trim($_POST['nome'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $senha = $_POST['senha'] ?? '';
    $role  = $_POST['role'] ?? 'user';

    if (!$nome || !$email || !$senha) {
        $msg = 'Preencha todos os campos obrigatórios.';
        $msg_type = 'error';
    } else {
        // Verifica se e-mail já existe
        $stmt = $pdo->prepare("SELECT id FROM usuarios WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            $msg = 'Este e-mail já está cadastrado.';
            $msg_type = 'error';
        } else {
            $hash = password_hash($senha, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO usuarios (nome, email, senha_hash, role) VALUES (?, ?, ?, ?)");
            $stmt->execute([$nome, $email, $hash, $role]);
            $msg = "Usuário \"$nome\" criado com sucesso!";
            $msg_type = 'success';
        }
    }
}

// ============================================================
// AÇÃO: Trocar própria senha
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'change_password') {
    $senha_atual = $_POST['senha_atual'] ?? '';
    $nova_senha  = $_POST['nova_senha'] ?? '';
    $confirmar   = $_POST['confirmar_senha'] ?? '';

    if (!$senha_atual || !$nova_senha || !$confirmar) {
        $msg = 'Preencha todos os campos de senha.';
        $msg_type = 'error';
    } elseif ($nova_senha !== $confirmar) {
        $msg = 'A nova senha e a confirmação não coincidem.';
        $msg_type = 'error';
    } elseif (strlen($nova_senha) < 6) {
        $msg = 'A nova senha deve ter pelo menos 6 caracteres.';
        $msg_type = 'error';
    } else {
        // Verifica senha atual
        $stmt = $pdo->prepare("SELECT senha_hash FROM usuarios WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user = $stmt->fetch();

        if ($user && password_verify($senha_atual, $user['senha_hash'])) {
            $novo_hash = password_hash($nova_senha, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE usuarios SET senha_hash = ? WHERE id = ?");
            $stmt->execute([$novo_hash, $_SESSION['user_id']]);
            $msg = 'Senha alterada com sucesso!';
            $msg_type = 'success';
        } else {
            $msg = 'Senha atual incorreta.';
            $msg_type = 'error';
        }
    }
}

// ============================================================
// AÇÃO: Excluir usuário
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_user') {
    $user_id = (int)($_POST['user_id'] ?? 0);
    
    // Não permite excluir a si mesmo
    if ($user_id === (int)$_SESSION['user_id']) {
        $msg = 'Você não pode excluir sua própria conta.';
        $msg_type = 'error';
    } elseif ($user_id > 0) {
        $stmt = $pdo->prepare("DELETE FROM usuarios WHERE id = ?");
        $stmt->execute([$user_id]);
        $msg = 'Usuário excluído com sucesso.';
        $msg_type = 'success';
    }
}

// ============================================================
// AÇÃO: Resetar senha de outro usuário
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'reset_password') {
    $user_id   = (int)($_POST['user_id'] ?? 0);
    $nova_senha = $_POST['nova_senha_reset'] ?? '';

    if ($user_id > 0 && strlen($nova_senha) >= 6) {
        $hash = password_hash($nova_senha, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE usuarios SET senha_hash = ? WHERE id = ?");
        $stmt->execute([$hash, $user_id]);
        $msg = 'Senha do usuário redefinida com sucesso!';
        $msg_type = 'success';
    } else {
        $msg = 'Senha deve ter pelo menos 6 caracteres.';
        $msg_type = 'error';
    }
}

// Busca todos os usuários
$stmt = $pdo->query("SELECT id, nome, email, role, criado_em FROM usuarios ORDER BY criado_em DESC");
$usuarios = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administração - MEC Command Center</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f8fafc; }
        .tab-active { border-bottom: 3px solid #3b82f6; color: #1e40af; font-weight: 600; }
        .tab-inactive { border-bottom: 3px solid transparent; color: #64748b; }
        .tab-inactive:hover { color: #334155; border-color: #cbd5e1; }
    </style>
</head>
<body class="text-slate-800 min-h-screen">

    <!-- Header -->
    <header class="bg-white/80 backdrop-blur-md sticky top-0 z-30 border-b border-slate-200">
        <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <a href="index.php" class="flex items-center text-slate-400 hover:text-blue-600 transition-colors mr-4">
                        <i data-lucide="arrow-left" class="w-5 h-5"></i>
                    </a>
                    <div class="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center text-white mr-3">
                        <i data-lucide="settings" class="w-5 h-5"></i>
                    </div>
                    <span class="text-lg font-bold text-slate-800">Painel Administrativo</span>
                </div>
                <div class="flex items-center space-x-3">
                    <span class="text-sm font-semibold text-slate-600"><?php echo $_SESSION['user_nome']; ?></span>
                    <a href="logout.php" class="p-2 text-slate-400 hover:text-red-500 transition-colors">
                        <i data-lucide="log-out" class="w-5 h-5"></i>
                    </a>
                </div>
            </div>
        </div>
    </header>

    <main class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

        <!-- Mensagens de feedback -->
        <?php if ($msg): ?>
            <div class="mb-6 p-4 rounded-xl border text-sm flex items-center
                <?php echo $msg_type === 'success' ? 'bg-green-50 text-green-700 border-green-200' : 'bg-red-50 text-red-700 border-red-200'; ?>">
                <i data-lucide="<?php echo $msg_type === 'success' ? 'check-circle' : 'alert-circle'; ?>" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <?php echo htmlspecialchars($msg); ?>
            </div>
        <?php endif; ?>

        <!-- Tabs de navegação -->
        <div class="flex space-x-6 border-b border-slate-200 mb-8">
            <button onclick="showTab('users')" id="tab-users" class="pb-3 px-1 text-sm tab-active transition-all">
                <i data-lucide="users" class="w-4 h-4 inline mr-1"></i> Gerenciar Usuários
            </button>
            <button onclick="showTab('create')" id="tab-create" class="pb-3 px-1 text-sm tab-inactive transition-all">
                <i data-lucide="user-plus" class="w-4 h-4 inline mr-1"></i> Criar Novo Usuário
            </button>
            <button onclick="showTab('password')" id="tab-password" class="pb-3 px-1 text-sm tab-inactive transition-all">
                <i data-lucide="key" class="w-4 h-4 inline mr-1"></i> Minha Senha
            </button>
        </div>

        <!-- ============================================ -->
        <!-- TAB 1: Lista de Usuários -->
        <!-- ============================================ -->
        <div id="panel-users">
            <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                <div class="p-6 border-b border-slate-100">
                    <h2 class="text-lg font-bold text-slate-800">Usuários Cadastrados</h2>
                    <p class="text-sm text-slate-500"><?php echo count($usuarios); ?> usuário(s) no sistema</p>
                </div>
                <div class="divide-y divide-slate-100">
                    <?php foreach ($usuarios as $u): ?>
                    <div class="p-5 flex items-center justify-between hover:bg-slate-50/50 transition-colors">
                        <div class="flex items-center">
                            <div class="w-10 h-10 rounded-full flex items-center justify-center font-bold text-sm mr-4
                                <?php echo $u['role'] === 'admin' ? 'bg-blue-100 text-blue-700' : 'bg-slate-100 text-slate-600'; ?>">
                                <?php echo strtoupper(substr($u['nome'], 0, 2)); ?>
                            </div>
                            <div>
                                <p class="font-semibold text-slate-800"><?php echo htmlspecialchars($u['nome']); ?></p>
                                <p class="text-xs text-slate-500"><?php echo htmlspecialchars($u['email']); ?></p>
                            </div>
                        </div>
                        <div class="flex items-center space-x-3">
                            <span class="px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider
                                <?php echo $u['role'] === 'admin' ? 'bg-blue-50 text-blue-700 border border-blue-200' : 'bg-slate-50 text-slate-500 border border-slate-200'; ?>">
                                <?php echo $u['role']; ?>
                            </span>
                            
                            <!-- Botão Resetar Senha -->
                            <button onclick="openResetModal(<?php echo $u['id']; ?>, '<?php echo htmlspecialchars($u['nome'], ENT_QUOTES); ?>')" 
                                class="p-2 text-slate-400 hover:text-orange-600 hover:bg-orange-50 rounded-lg transition-all" title="Resetar Senha">
                                <i data-lucide="key-round" class="w-4 h-4"></i>
                            </button>

                            <!-- Botão Excluir (não mostra para si mesmo) -->
                            <?php if ($u['id'] !== $_SESSION['user_id']): ?>
                            <form method="POST" onsubmit="return confirm('Tem certeza que deseja excluir este usuário?');" class="inline">
                                <input type="hidden" name="action" value="delete_user">
                                <input type="hidden" name="user_id" value="<?php echo $u['id']; ?>">
                                <button type="submit" class="p-2 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all" title="Excluir">
                                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                                </button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- ============================================ -->
        <!-- TAB 2: Criar Novo Usuário -->
        <!-- ============================================ -->
        <div id="panel-create" class="hidden">
            <div class="bg-white rounded-2xl border border-slate-200 p-8 max-w-lg">
                <h2 class="text-lg font-bold text-slate-800 mb-1">Criar Novo Usuário</h2>
                <p class="text-sm text-slate-500 mb-6">Preencha os dados do novo colaborador</p>

                <form method="POST" class="space-y-5">
                    <input type="hidden" name="action" value="create_user">

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Nome Completo *</label>
                        <input type="text" name="nome" required
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                            placeholder="Ex: Maria Silva">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">E-mail *</label>
                        <input type="email" name="email" required
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                            placeholder="Ex: maria@ceunsp.edu.br">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Senha Inicial *</label>
                        <input type="text" name="senha" required minlength="6"
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all"
                            placeholder="Mínimo 6 caracteres">
                        <p class="text-[10px] text-slate-400 mt-1">O usuário poderá trocar depois no painel.</p>
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Perfil</label>
                        <select name="role"
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 transition-all">
                            <option value="user">Usuário (acesso padrão)</option>
                            <option value="admin">Administrador (acesso total)</option>
                        </select>
                    </div>

                    <button type="submit"
                        class="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-xl shadow-lg shadow-blue-200 transition-all transform active:scale-95">
                        <i data-lucide="user-plus" class="w-4 h-4 inline mr-1"></i> Criar Usuário
                    </button>
                </form>
            </div>
        </div>

        <!-- ============================================ -->
        <!-- TAB 3: Trocar Minha Senha -->
        <!-- ============================================ -->
        <div id="panel-password" class="hidden">
            <div class="bg-white rounded-2xl border border-slate-200 p-8 max-w-lg">
                <h2 class="text-lg font-bold text-slate-800 mb-1">Alterar Minha Senha</h2>
                <p class="text-sm text-slate-500 mb-6">Informe sua senha atual e defina uma nova</p>

                <form method="POST" class="space-y-5">
                    <input type="hidden" name="action" value="change_password">

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Senha Atual *</label>
                        <input type="password" name="senha_atual" required
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                            placeholder="••••••••">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Nova Senha *</label>
                        <input type="password" name="nova_senha" required minlength="6"
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                            placeholder="Mínimo 6 caracteres">
                    </div>

                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Confirmar Nova Senha *</label>
                        <input type="password" name="confirmar_senha" required minlength="6"
                            class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                            placeholder="Repita a nova senha">
                    </div>

                    <button type="submit"
                        class="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-xl shadow-lg shadow-blue-200 transition-all transform active:scale-95">
                        <i data-lucide="key" class="w-4 h-4 inline mr-1"></i> Alterar Senha
                    </button>
                </form>
            </div>
        </div>
    </main>

    <!-- Modal: Resetar Senha de Outro Usuário -->
    <div id="reset-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-sm">
        <div class="bg-white w-full max-w-md rounded-2xl shadow-2xl p-8">
            <h3 class="text-lg font-bold text-slate-800 mb-1">Redefinir Senha</h3>
            <p class="text-sm text-slate-500 mb-6">Definir nova senha para: <strong id="reset-user-name"></strong></p>

            <form method="POST" class="space-y-5">
                <input type="hidden" name="action" value="reset_password">
                <input type="hidden" name="user_id" id="reset-user-id">

                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5">Nova Senha *</label>
                    <input type="text" name="nova_senha_reset" required minlength="6"
                        class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 transition-all"
                        placeholder="Mínimo 6 caracteres">
                </div>

                <div class="flex space-x-3">
                    <button type="button" onclick="closeResetModal()" 
                        class="flex-1 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 font-semibold rounded-xl transition-all">
                        Cancelar
                    </button>
                    <button type="submit"
                        class="flex-1 py-2.5 bg-orange-500 hover:bg-orange-600 text-white font-semibold rounded-xl shadow-lg transition-all">
                        Redefinir
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        lucide.createIcons();

        // Sistema de Tabs
        function showTab(tab) {
            ['users', 'create', 'password'].forEach(t => {
                document.getElementById('panel-' + t).classList.toggle('hidden', t !== tab);
                document.getElementById('tab-' + t).className = t === tab 
                    ? 'pb-3 px-1 text-sm tab-active transition-all' 
                    : 'pb-3 px-1 text-sm tab-inactive transition-all';
            });
        }

        // Modal de Reset de Senha
        function openResetModal(userId, userName) {
            document.getElementById('reset-user-id').value = userId;
            document.getElementById('reset-user-name').textContent = userName;
            document.getElementById('reset-modal').classList.remove('hidden');
        }

        function closeResetModal() {
            document.getElementById('reset-modal').classList.add('hidden');
        }

        // Fechar modal no ESC
        window.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeResetModal();
        });
    </script>
</body>
</html>
