<?php
session_start();

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

// --- CORREÇÃO DO ERRO: DEFININDO AS VARIÁVEIS ANTES DO USO ---
$isAdmin = true;
$usuarioLogado = $_SESSION['usuario'];

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

// --- 1. BUSCA CONFIGURAÇÕES DO SITE (NOME E COR) ---
$nomePainel = "IPTV PANEL"; 
$corPrimaria = "#7367f0"; 
try {
    $conf = $connGeral->query("SELECT NomePainel, TemaPainel FROM site_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($conf) {
        if (!empty($conf['NomePainel'])) $nomePainel = $conf['NomePainel'];
        if (!empty($conf['TemaPainel'])) $corPrimaria = $conf['TemaPainel'];
    }
} catch (Exception $e) { }

// --- 3. CORREÇÃO DO MENU LATERAL (MENSAGENS NÃO LIDAS) ---
$total_msg_nao_lidas = 0;
try {
    $stmtMsg = $connUser->prepare("SELECT COUNT(*) FROM chamados_suporte WHERE destinatario = ? AND lida = 'nao'");
    $stmtMsg->execute([$usuarioLogado]);
    $total_msg_nao_lidas = $stmtMsg->fetchColumn();
} catch (Exception $e) { }

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

        if ($acao === 'criar') {
            $user = trim($_POST['usuario']);
            $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')";
                $connUser->prepare($sql)->execute([$_SESSION['usuario'], $_POST['nome'], $_POST['sobrenome'], $user, $_POST['senha'], $_POST['email'], $_POST['celular']]);
                $msg = "Administrador cadastrado com sucesso!"; $msg_tipo = "success";
            }
        }

        if ($acao === 'editar') {
            $sql = "UPDATE admin SET nome=?, sobrenome=?, usuario=?, senha=?, email=?, celular=? WHERE id=?";
            $connUser->prepare($sql)->execute([$_POST['nome'], $_POST['sobrenome'], $_POST['usuario'], $_POST['senha'], $_POST['email'], $_POST['celular'], $id_adm]);
            $msg = "Dados atualizados com sucesso!"; $msg_tipo = "primary";
        }

        if ($acao === 'bloquear') {
            $status_atual = $_POST['status_atual'];
            $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";
        }

        if ($acao === 'excluir') {
            if ($_SESSION['usuario'] == $_POST['usuario_alvo']) {
                $msg = "Você não pode excluir a si mesmo!"; $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"; }
}

// --- 3. LISTAGEM ---
$admins = $connUser->query("SELECT * FROM admin ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>

<?php include 'tema_global.php'; ?>

    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestão de Admins | <?= htmlspecialchars($nomePainel) ?></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>
        :root { 
            --primary: <?= $corPrimaria ?>; 
            --bg-body: #151521; 
            --bg-card: #1e1e2d; 
            --text-color: #d0d2d6;
            --border-color: #2b2b40;
            --overlay-desk: rgba(0, 0, 0, 0.65); 
            --overlay-mob: rgba(0, 0, 0, 0.85);
        }
        body.light-mode { 
            --bg-body: #f4f5f8; 
            --bg-card: #ffffff; 
            --text-color: #5e5873; 
            --border-color: #ebe9f1; 
            --overlay-desk: rgba(255, 255, 255, 0.1); 
            --overlay-mob: rgba(255, 255, 255, 0);
        }
        body { background-color: var(--bg-body); color: var(--text-color); font-family: 'Segoe UI', sans-serif; overflow-x: hidden; margin: 0; }
        
        /* Sidebar Estilo IPTV */
        .sidebar { width: 260px; height: 100vh; position: fixed; background: var(--bg-card); border-right: 1px solid var(--border-color); z-index: 1050; padding: 20px; overflow-y: auto; transition: 0.3s; }
        .sidebar .nav-link { white-space: nowrap !important; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; color: #a6a6b7; padding: 12px 15px; border-radius: 8px; text-decoration: none; margin-bottom: 5px; font-weight: 500; transition: 0.2s; }
        .sidebar .nav-link:hover, .sidebar .nav-link.active { background: var(--primary); color: #fff; box-shadow: 0 4px 15px rgba(0,0,0,0.2); }
        .sidebar .nav-link i.fa-fw { margin-right: 8px; text-align: center; }
        .nav-group-title { font-size: 0.75rem; text-transform: uppercase; color: #5e5873; font-weight: 700; margin: 25px 0 10px 12px; letter-spacing: 1px; }
        
        /* Layout Flexbox Ajustado para forçar Rodapé no Final */
        .main-content { margin-left: 260px; transition: 0.3s; display: flex; flex-direction: column; min-height: 100vh; }
        .top-header { background: linear-gradient(90deg, var(--bg-card) 0%, var(--overlay-desk) 100%), var(--primary); padding: 15px 30px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 30px;}
        .header-title { font-size: 1.3rem; font-weight: 800; color: #fff; text-transform: uppercase; letter-spacing: 1px; margin: 0;}

        /* Elementos Premium */
        .card-custom { background-color: var(--bg-card) !important; border: 1px solid var(--border-color) !important; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        
        /* Tabela Dinâmica que respeita Tema Claro/Escuro DE VERDADE */
        .table-custom { width: 100%; margin-bottom: 0; border-collapse: separate; border-spacing: 0; background: transparent !important; }
        .table-custom th { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: #a6a6b7 !important; font-size: 0.8rem; text-transform: uppercase; font-weight: 700; padding: 15px; white-space: nowrap; }
        .table-custom td { background-color: var(--bg-card) !important; border-bottom: 1px solid var(--border-color) !important; color: var(--text-color) !important; vertical-align: middle; padding: 15px; font-size: 0.95rem; }
        .table-custom tbody tr:hover td { background-color: rgba(115, 103, 240, 0.08) !important; } /* Efeito sutil ao passar o mouse */

        /* Inputs Customizados Dinâmicos */
        .form-control, .form-select { background-color: rgba(0,0,0,0.1) !important; border: 1px solid var(--border-color) !important; color: var(--text-color) !important; border-radius: 8px; padding: 10px 15px; transition: 0.2s; }
        body.light-mode .form-control, body.light-mode .form-select { background-color: rgba(0,0,0,0.03) !important; }
        .form-control:focus, .form-select:focus { border-color: var(--primary) !important; box-shadow: 0 0 0 0.25rem rgba(115, 103, 240, 0.25) !important; background-color: transparent !important;}

        .avatar-circle { width: 40px; height: 40px; background: var(--primary); color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; }
        
        @media (max-width: 992px) { 
            .sidebar { transform: translateX(-100%); } 
            .sidebar.show { transform: translateX(0); box-shadow: 5px 0 30px rgba(0,0,0,0.9); } 
            .main-content { margin-left: 0; } 
            .mobile-toggle { display: block !important; margin-right: 15px; } 
            .top-header { flex-direction: row; padding: 15px 20px; background: linear-gradient(var(--overlay-mob), var(--overlay-mob)), var(--primary); }
        }
        .mobile-toggle { display: none; background: none; border: none; color: #fff; font-size: 1.5rem; margin-right: 15px; }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 1040; backdrop-filter: blur(3px); }
        .overlay.show { display: block; }
    </style>
</head>
<body>
<?php include 'menu.php'; ?>
<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<!-- O d-flex flex-column min-vh-100 garante que a página tenha a altura máxima e o rodapé fique embaixo -->
<main class="main-content d-flex flex-column min-vh-100">
    <div class="top-header">
        <div class="d-flex align-items-center">
            <button class="mobile-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
            <div class="header-title"><i class="fas fa-user-shield me-2"></i> Gestão de Equipe</div>
        </div>
        <button class="btn btn-light fw-bold px-4 shadow-sm rounded-pill" data-bs-toggle="modal" data-bs-target="#modalCriar" style="letter-spacing: 0.5px;">
            <i class="fas fa-plus me-1"></i> NOVO ADMIN
        </button>
    </div>

    <!-- Container flex-grow-1 estica o meio, empurrando o Rodapé para baixo -->
    <div class="container-fluid p-3 p-md-4 flex-grow-1">
        
        <?php if($msg): ?>
            <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show border-0 shadow-sm fw-bold">
                <?= $msg ?>
                <button class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card card-custom shadow-lg">
            <div class="table-responsive">
                <table class="table table-custom 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));
                            $is_blocked = ($a['bloqueado'] == 'sim');
                        ?>
                        <tr>
                            <td class="ps-4">
                                <div class="d-flex align-items-center">
                                    <div class="avatar-circle me-3 shadow-sm"><?= $iniciais ?></div>
                                    <div>
                                        <div class="fw-bold" style="color: var(--text-color);"><?= htmlspecialchars($a['nome']) ?> <?= htmlspecialchars($a['sobrenome']??'') ?></div>
                                        <div class="small" style="color: var(--text-color); opacity: 0.6;">ID: <?= $a['id'] ?></div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="fw-bold" style="color: var(--text-color);"><?= htmlspecialchars($a['usuario']) ?></div>
                                <div class="small" style="color: var(--text-color); opacity: 0.6;">Senha: <?= htmlspecialchars($a['senha']) ?></div>
                            </td>
                            <td>
                                <div class="small" style="color: var(--text-color);"><i class="fas fa-envelope me-2 text-info opacity-75"></i><?= htmlspecialchars($a['email']) ?></div>
                                <div class="small" style="color: var(--text-color);"><i class="fas fa-phone me-2 text-success opacity-75"></i><?= htmlspecialchars($a['celular']) ?></div>
                            </td>
                            <td>
                                <?= $is_blocked ? '<span class="badge bg-danger bg-opacity-10 text-danger border border-danger px-2 py-1">Bloqueado</span>' : '<span class="badge bg-success bg-opacity-10 text-success border border-success px-2 py-1">Ativo</span>' ?>
                            </td>
                            <td class="text-end pe-4">
                                <div class="d-flex gap-2 justify-content-end">
                                    <form method="POST" class="m-0">
                                        <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-<?= $is_blocked ? 'success' : 'warning' ?> shadow-sm rounded-3" title="<?= $is_blocked?'Desbloquear':'Bloquear' ?>">
                                            <i class="fas <?= $is_blocked?'fa-lock':'fa-lock-open' ?>"></i>
                                        </button>
                                    </form>
                                    <button class="btn btn-sm btn-outline-info shadow-sm rounded-3" onclick='abrirEditar(<?= json_encode($a) ?>)' title="Editar">
                                        <i class="fas fa-pen"></i>
                                    </button>
                                    <form method="POST" class="m-0">
                                        <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-outline-danger shadow-sm rounded-3" onclick="return confirm('Tem certeza que deseja excluir este administrador?')" title="Excluir">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Rodapé fixado no final do Main Content -->
    <div class="mt-auto w-100">
        <?php include 'rodape.php'; ?>
    </div>
    
</main>

<div class="modal fade" id="modalCriar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <div class="modal-header border-secondary">
                <h5 class="modal-title fw-bold" style="color: var(--text-color);"><i class="fas fa-user-plus text-success me-2"></i> Novo Administrador</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></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-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOME</label>
                            <input type="text" name="nome" class="form-control" required placeholder="Ex: João">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SOBRENOME</label>
                            <input type="text" name="sobrenome" class="form-control" placeholder="Ex: Silva">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">USUÁRIO</label>
                            <input type="text" name="usuario" class="form-control" required placeholder="Login de acesso">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SENHA</label>
                            <input type="text" name="senha" class="form-control" required placeholder="Senha de acesso">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">E-MAIL</label>
                            <input type="email" name="email" class="form-control" placeholder="admin@email.com">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">CELULAR / WHATSAPP</label>
                            <input type="text" name="celular" class="form-control" placeholder="Ex: 551199999999">
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-secondary">
                    <button type="submit" class="btn btn-primary fw-bold w-100 py-2 shadow-sm rounded-pill">CADASTRAR ADMINISTRADOR</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-secondary" style="background-color: var(--bg-card);">
            <div class="modal-header border-secondary">
                <h5 class="modal-title fw-bold" style="color: var(--text-color);"><i class="fas fa-pen text-warning me-2"></i> Editar Administrador</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1) grayscale(100%) brightness(200%);"></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-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">NOME</label>
                            <input type="text" name="nome" id="edit_nome" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SOBRENOME</label>
                            <input type="text" name="sobrenome" id="edit_sobrenome" class="form-control">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">USUÁRIO</label>
                            <input type="text" name="usuario" id="edit_user" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">SENHA</label>
                            <input type="text" name="senha" id="edit_pass" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">E-MAIL</label>
                            <input type="email" name="email" id="edit_email" class="form-control">
                        </div>
                        <div class="col-md-6 mb-2">
                            <label class="form-label small fw-bold" style="color: var(--text-color); opacity: 0.7;">CELULAR / WHATSAPP</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 py-2 shadow-sm rounded-pill">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 toggleMenu() { 
        document.getElementById('sidebar').classList.toggle('show'); 
        document.getElementById('overlay').classList.toggle('show'); 
    }
    
    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>
