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

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

// 1. PROCESSAR SALVAMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['salvar_permissoes'])) {
    try {
        $id_grupo = (int)$_POST['id_grupo'];
        
        // Verifica checkbox (se marcado = 'sim', se não = 'nao')
        $email_teste = isset($_POST['OpcoesEmailTeste']) ? 'sim' : 'nao';
        // Adicione outros campos aqui conforme sua tabela crescer
        $exportar = isset($_POST['OpcoesExportar']) ? 'sim' : 'nao';
        $vencimento = isset($_POST['OpcoesVencimento']) ? 'sim' : 'nao';

        // Atualiza no banco
        $sql = "UPDATE opcoes SET OpcoesEmailTeste = ?, OpcoesExportar = ?, OpcoesVencimento = ? WHERE id = ?";
        $stmt = $connAcessos->prepare($sql);
        $stmt->execute([$email_teste, $exportar, $vencimento, $id_grupo]);
        
        $msg = "Permissões atualizadas com sucesso!";
        $msg_tipo = "success";
    } catch (Exception $e) {
        $msg = "Erro ao salvar: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// 2. BUSCAR GRUPOS
try {
    $grupos = $connAcessos->query("SELECT * FROM opcoes ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $grupos = [];
    $msg = "Erro ao buscar grupos (Verifique a conexão com banco 'acessos'): " . $e->getMessage();
    $msg_tipo = "danger";
}
?>

<!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>Gerenciar Permissões</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; margin-bottom: 20px; }
        .form-check-input:checked { background-color: #7367f0; border-color: #7367f0; }
        .table-dark { background: #1e1e2d; --bs-table-bg: #1e1e2d; color: #fff; }
        .table-dark td, .table-dark th { border-color: #333; vertical-align: middle; }
        
        /* Switch Customizado */
        .switch-label { cursor: pointer; display: flex; align-items: center; justify-content: space-between; }
        .badge-grupo { background: rgba(115, 103, 240, 0.2); color: #7367f0; padding: 5px 10px; border-radius: 5px; font-weight: bold; }

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


<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Gerenciar Permissões</h3>
        <span class="text-white-50">Controle o que cada grupo pode acessar</span>
    </div>

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

    <div class="row">
        <?php if(empty($grupos)): ?>
            <div class="col-12"><div class="alert alert-warning">Nenhum grupo encontrado na tabela 'opcoes'.</div></div>
        <?php else: ?>
            <?php foreach($grupos as $g): ?>
            <div class="col-md-6 col-lg-4">
                <form method="POST">
                    <input type="hidden" name="salvar_permissoes" value="1">
                    <input type="hidden" name="id_grupo" value="<?= $g['id'] ?>">
                    
                    <div class="card card-custom p-3 border-top border-3 border-primary">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="badge-grupo text-uppercase"><i class="fas fa-users me-2"></i><?= $g['grupo'] ?></span>
                            <button class="btn btn-sm btn-outline-success"><i class="fas fa-save"></i></button>
                        </div>
                        
                        <div class="list-group list-group-flush bg-transparent">
                            
                            <div class="list-group-item bg-transparent text-white border-secondary px-0">
                                <div class="form-check form-switch switch-label">
                                    <label class="form-check-label" for="chk_email_<?= $g['id'] ?>">Link de Teste Auto.</label>
                                    <input class="form-check-input" type="checkbox" name="OpcoesEmailTeste" id="chk_email_<?= $g['id'] ?>" <?= ($g['OpcoesEmailTeste'] == 'sim' || $g['OpcoesEmailTeste'] == '1') ? 'checked' : '' ?>>
                                </div>
                            </div>

                            <div class="list-group-item bg-transparent text-white border-secondary px-0">
                                <div class="form-check form-switch switch-label">
                                    <label class="form-check-label" for="chk_exp_<?= $g['id'] ?>">Exportar Listas</label>
                                    <input class="form-check-input" type="checkbox" name="OpcoesExportar" id="chk_exp_<?= $g['id'] ?>" <?= ($g['OpcoesExportar'] == 'sim' || $g['OpcoesExportar'] == '1') ? 'checked' : '' ?>>
                                </div>
                            </div>

                            <div class="list-group-item bg-transparent text-white border-secondary px-0">
                                <div class="form-check form-switch switch-label">
                                    <label class="form-check-label" for="chk_venc_<?= $g['id'] ?>">Alterar Vencimento</label>
                                    <input class="form-check-input" type="checkbox" name="OpcoesVencimento" id="chk_venc_<?= $g['id'] ?>" <?= ($g['OpcoesVencimento'] == 'sim' || $g['OpcoesVencimento'] == '1') ? 'checked' : '' ?>>
                                </div>
                            </div>

                        </div>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
