<?php
session_start();
// Apenas Admin Logado
if (!isset($_SESSION['logado']) || $_SESSION['nivel'] !== 'admin') { 
    header("Location: index.php"); exit; 
}
require_once 'conexao.php'; // Usa $connUser

$msg = ""; 
$msg_tipo = "";

// --- PROCESSAMENTO (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id_adm = $_POST['id_adm'] ?? 0;

        // CRIAR NOVO ADMIN
        if ($acao === 'criar') {
            $nome = trim($_POST['nome']);
            $sobrenome = trim($_POST['sobrenome']);
            $user = trim($_POST['usuario']);
            $pass = trim($_POST['senha']);
            $email = trim($_POST['email']);
            $cel = trim($_POST['celular']);

            // Verifica duplicidade
            $check = $connUser->prepare("SELECT id FROM admin WHERE usuario = ?");
            $check->execute([$user]);
            
            if ($check->rowCount() > 0) {
                $msg = "Este usuário já existe!"; $msg_tipo = "warning";
            } else {
                $sql = "INSERT INTO admin (CadUser, nome, sobrenome, usuario, senha, email, celular, data_cadastro, bloqueado, inativo) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), 'nao', 'nao')";
                $stmt = $connUser->prepare($sql);
                $stmt->execute([$_SESSION['usuario'], $nome, $sobrenome, $user, $pass, $email, $cel]);
                
                $msg = "Administrador cadastrado com sucesso!"; $msg_tipo = "success";
            }
        }

        // EDITAR ADMIN
        if ($acao === 'editar') {
            $nome = trim($_POST['nome']);
            $sobrenome = trim($_POST['sobrenome']);
            $user = trim($_POST['usuario']);
            $pass = trim($_POST['senha']);
            $email = trim($_POST['email']);
            $cel = trim($_POST['celular']);

            $sql = "UPDATE admin SET nome=?, sobrenome=?, usuario=?, senha=?, email=?, celular=? WHERE id=?";
            $connUser->prepare($sql)->execute([$nome, $sobrenome, $user, $pass, $email, $cel, $id_adm]);
            
            $msg = "Dados atualizados!"; $msg_tipo = "primary";
        }

        // BLOQUEAR / DESBLOQUEAR
        if ($acao === 'bloquear') {
            $status_atual = $_POST['status_atual']; // vem 'sim' ou 'nao'
            $novo_status = ($status_atual == 'sim') ? 'nao' : 'sim';
            
            $connUser->prepare("UPDATE admin SET bloqueado = ? WHERE id = ?")->execute([$novo_status, $id_adm]);
            $msg = ($novo_status == 'sim') ? "Usuário Bloqueado!" : "Usuário Desbloqueado!";
            $msg_tipo = "info";
        }

        // EXCLUIR
        if ($acao === 'excluir') {
            // Evita excluir a si mesmo
            if ($_SESSION['usuario'] == $_POST['usuario_alvo']) {
                $msg = "Você não pode excluir seu próprio usuário!"; $msg_tipo = "warning";
            } else {
                $connUser->prepare("DELETE FROM admin WHERE id = ?")->execute([$id_adm]);
                $msg = "Administrador removido!"; $msg_tipo = "danger";
            }
        }

    } catch (Exception $e) {
        $msg = "Erro: " . $e->getMessage(); $msg_tipo = "danger";
    }
}

// --- LISTAGEM ---
$admins = $connUser->query("SELECT * FROM admin ORDER BY id DESC")->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>Gerenciar Admins</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #151521; color: #fff; font-family: 'Segoe UI', sans-serif; }
        .sidebar { width: 260px; height: 100vh; position: fixed; background: #1e1e2d; padding: 20px; border-right: 1px solid #333; z-index: 1000; }
        .main-content { margin-left: 260px; padding: 30px; }
        .card-custom { background: #1e1e2d; border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; }
        
        /* Tabela */
        .table-dark { background: #1e1e2d; --bs-table-bg: #1e1e2d; color: #fff; }
        .table-dark td { border-color: #333; vertical-align: middle; }
        .table-dark th { color: #fff; border-color: #444; text-transform: uppercase; font-size: 0.8rem; }
        
        .form-control { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .form-control:focus { background: #32324a; border-color: #7367f0; color: #fff; }
        
        .avatar-circle { width: 40px; height: 40px; background: #7367f0; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; }

        @media (max-width: 768px) { .sidebar{display:none;} .main-content{margin-left:0;} }
    </style>
</head>
<body>

<nav class="sidebar">
    <h4 class="mb-4 fw-bold text-white"><i class="fas fa-tv text-primary"></i> Painel</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="gerenciar_admins.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-user-shield me-2"></i> Administradores</a>
        </div>
</nav>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Equipe Administrativa</h3>
        <button class="btn btn-primary fw-bold" data-bs-toggle="modal" data-bs-target="#modalCriar">
            <i class="fas fa-plus me-2"></i> Novo Admin
        </button>
    </div>

    <?php if($msg): ?><div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close btn-close-white" data-bs-dismiss="alert"></button></div><?php endif; ?>

    <div class="card card-custom">
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead>
                    <tr>
                        <th class="ps-4">Nome</th>
                        <th>Usuário / Senha</th>
                        <th>Contato</th>
                        <th>Status</th>
                        <th class="text-end pe-4">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($admins as $a): 
                        $iniciais = strtoupper(substr($a['nome'], 0, 1) . substr($a['sobrenome'], 0, 1));
                        $status_badge = ($a['bloqueado'] == 'sim') ? '<span class="badge bg-danger">Bloqueado</span>' : '<span class="badge bg-success">Ativo</span>';
                    ?>
                    <tr>
                        <td class="ps-4">
                            <div class="d-flex align-items-center">
                                <div class="avatar-circle me-3"><?= $iniciais ?></div>
                                <div>
                                    <div class="fw-bold text-white"><?= $a['nome'] ?> <?= $a['sobrenome'] ?></div>
                                    <div class="small text-muted">ID: <?= $a['id'] ?></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="text-white"><?= $a['usuario'] ?></div>
                            <div class="text-white-50 small"><?= $a['senha'] ?></div>
                        </td>
                        <td>
                            <div class="small"><i class="fas fa-envelope me-2 text-secondary"></i><?= $a['email'] ?></div>
                            <div class="small"><i class="fas fa-phone me-2 text-secondary"></i><?= $a['celular'] ?></div>
                        </td>
                        <td><?= $status_badge ?></td>
                        <td class="text-end pe-4">
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="acao" value="bloquear">
                                <input type="hidden" name="id_adm" value="<?= $a['id'] ?>">
                                <input type="hidden" name="status_atual" value="<?= $a['bloqueado'] ?>">
                                <button class="btn btn-sm btn-outline-light rounded-circle me-1" title="<?= ($a['bloqueado']=='sim')?'Desbloquear':'Bloquear' ?>">
                                    <i class="fas fa-<?= ($a['bloqueado']=='sim')?'lock':'lock-open' ?>"></i>
                                </button>
                            </form>

                            <button class="btn btn-sm btn-info rounded-circle me-1" onclick='abrirEditar(<?= json_encode($a) ?>)' title="Editar">
                                <i class="fas fa-pen text-white"></i>
                            </button>

                            <form method="POST" class="d-inline">
                                <input type="hidden" name="acao" value="excluir">
                                <input type="hidden" name="id_adm" value="<?= $a['id'] ?>">
                                <input type="hidden" name="usuario_alvo" value="<?= $a['usuario'] ?>">
                                <button class="btn btn-sm btn-danger rounded-circle" onclick="return confirm('Tem certeza que deseja excluir este administrador?')" title="Excluir">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary">
            <div class="modal-header border-secondary"><h5 class="modal-title text-white">Novo Administrador</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <form method="POST">
                <input type="hidden" name="acao" value="criar">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-6"><label class="form-label text-white-50">Nome</label><input type="text" name="nome" class="form-control" required></div>
                        <div class="col-6"><label class="form-label text-white-50">Sobrenome</label><input type="text" name="sobrenome" class="form-control"></div>
                        <div class="col-6"><label class="form-label text-white-50">Usuário (Login)</label><input type="text" name="usuario" class="form-control" required></div>
                        <div class="col-6"><label class="form-label text-white-50">Senha</label><input type="text" name="senha" class="form-control" required></div>
                        <div class="col-12"><label class="form-label text-white-50">E-mail</label><input type="email" name="email" class="form-control"></div>
                        <div class="col-12"><label class="form-label text-white-50">Celular</label><input type="text" name="celular" class="form-control"></div>
                    </div>
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary fw-bold w-100">Cadastrar</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary">
            <div class="modal-header border-secondary"><h5 class="modal-title text-white">Editar Administrador</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <form method="POST">
                <input type="hidden" name="acao" value="editar">
                <input type="hidden" name="id_adm" id="edit_id">
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-6"><label class="form-label text-white-50">Nome</label><input type="text" name="nome" id="edit_nome" class="form-control" required></div>
                        <div class="col-6"><label class="form-label text-white-50">Sobrenome</label><input type="text" name="sobrenome" id="edit_sobrenome" class="form-control"></div>
                        <div class="col-6"><label class="form-label text-white-50">Usuário</label><input type="text" name="usuario" id="edit_user" class="form-control" required></div>
                        <div class="col-6"><label class="form-label text-white-50">Senha</label><input type="text" name="senha" id="edit_pass" class="form-control" required></div>
                        <div class="col-12"><label class="form-label text-white-50">E-mail</label><input type="email" name="email" id="edit_email" class="form-control"></div>
                        <div class="col-12"><label class="form-label text-white-50">Celular</label><input type="text" name="celular" id="edit_cel" class="form-control"></div>
                    </div>
                </div>
                <div class="modal-footer border-secondary"><button type="submit" class="btn btn-primary fw-bold w-100">Salvar Alterações</button></div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function abrirEditar(a) {
        document.getElementById('edit_id').value = a.id;
        document.getElementById('edit_nome').value = a.nome;
        document.getElementById('edit_sobrenome').value = a.sobrenome;
        document.getElementById('edit_user').value = a.usuario;
        document.getElementById('edit_pass').value = a.senha;
        document.getElementById('edit_email').value = a.email;
        document.getElementById('edit_cel').value = a.celular;
        new bootstrap.Modal(document.getElementById('modalEditar')).show();
    }
</script>
</body>
</html>
