<?php
session_start();
// Apenas Admin
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_csp'])) {
    try {
        $id_reg = (int)$_POST['id_registro'];
        
        // Mapeia os Checkboxes (Se marcado = 'sim', senão = 'nao')
        $visualizar = isset($_POST['visualizar']) ? 'sim' : 'nao';
        $adicionar  = isset($_POST['adicionar']) ? 'sim' : 'nao';
        $config     = isset($_POST['config']) ? 'sim' : 'nao';
        $info       = isset($_POST['info']) ? 'sim' : 'nao';
        $bloquear   = isset($_POST['bloquear']) ? 'sim' : 'nao';
        $editar     = isset($_POST['editar']) ? 'sim' : 'nao';
        $excluir    = isset($_POST['excluir']) ? 'sim' : 'nao';

        // Atualiza no banco de acessos
        $sql = "UPDATE servidorcsp SET 
                ServidorcspVisualizar = ?, 
                ServidorcspAdicionar = ?, 
                ServidorcspConfig = ?, 
                ServidorcspInfo = ?, 
                ServidorcspBloquear = ?, 
                ServidorcspEditar = ?, 
                ServidorcspExcluir = ? 
                WHERE id = ?";
        
        $stmt = $connAcessos->prepare($sql);
        $stmt->execute([$visualizar, $adicionar, $config, $info, $bloquear, $editar, $excluir, $id_reg]);
        
        $msg = "Permissões CSP atualizadas!";
        $msg_tipo = "success";
    } catch (Exception $e) {
        $msg = "Erro ao salvar: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// 2. BUSCAR DADOS
try {
    $permissoes = $connAcessos->query("SELECT * FROM servidorcsp ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $permissoes = []; }
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Permissões CSP | Painel</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; }
        
        /* Cores dos Switches */
        .form-check-input:checked { background-color: #ff9f43; border-color: #ff9f43; } /* Laranja */
        
        .switch-label { cursor: pointer; display: flex; align-items: center; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #2b2b40; }
        .switch-label:last-child { border-bottom: none; }
        .badge-grupo { background: rgba(255, 159, 67, 0.2); color: #ff9f43; padding: 5px 10px; border-radius: 5px; 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_permissoes.php" class="btn btn-dark text-start border-0 py-2"><i class="fas fa-lock me-2"></i> Permissões Gerais</a>
        <a href="permissoes_server.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-server me-2"></i> Permissões CSP</a>
    </div>
</nav>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Permissões de Servidor (CSP)</h3>
        <span class="text-white-50">Controle o acesso aos servidores</span>
    </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="row">
        <?php if(empty($permissoes)): ?>
            <div class="col-12"><div class="alert alert-warning">Nenhum registro encontrado na tabela 'servidorcsp'.</div></div>
        <?php else: ?>
            <?php foreach($permissoes as $p): ?>
            <div class="col-md-6 col-xl-4">
                <form method="POST">
                    <input type="hidden" name="salvar_csp" value="1">
                    <input type="hidden" name="id_registro" value="<?= $p['id'] ?>">
                    
                    <div class="card card-custom p-3 border-top border-3 border-warning">
                        <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><?= $p['grupo'] ?></span>
                            <button class="btn btn-sm btn-outline-warning"><i class="fas fa-save"></i> Salvar</button>
                        </div>
                        
                        <div class="px-2">
                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-white" for="vis_<?= $p['id'] ?>">👁️ Visualizar</label>
                                <input class="form-check-input" type="checkbox" name="visualizar" id="vis_<?= $p['id'] ?>" <?= ($p['ServidorcspVisualizar'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-white" for="add_<?= $p['id'] ?>">➕ Adicionar</label>
                                <input class="form-check-input" type="checkbox" name="adicionar" id="add_<?= $p['id'] ?>" <?= ($p['ServidorcspAdicionar'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-white" for="conf_<?= $p['id'] ?>">⚙️ Configurar</label>
                                <input class="form-check-input" type="checkbox" name="config" id="conf_<?= $p['id'] ?>" <?= ($p['ServidorcspConfig'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-white" for="info_<?= $p['id'] ?>">ℹ️ Informações</label>
                                <input class="form-check-input" type="checkbox" name="info" id="info_<?= $p['id'] ?>" <?= ($p['ServidorcspInfo'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-danger" for="block_<?= $p['id'] ?>">🚫 Bloquear</label>
                                <input class="form-check-input" type="checkbox" name="bloquear" id="block_<?= $p['id'] ?>" <?= ($p['ServidorcspBloquear'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-info" for="edit_<?= $p['id'] ?>">✏️ Editar</label>
                                <input class="form-check-input" type="checkbox" name="editar" id="edit_<?= $p['id'] ?>" <?= ($p['ServidorcspEditar'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-danger" for="del_<?= $p['id'] ?>">🗑️ Excluir</label>
                                <input class="form-check-input" type="checkbox" name="excluir" id="del_<?= $p['id'] ?>" <?= ($p['ServidorcspExcluir'] == 'sim') ? 'checked' : '' ?>>
                            </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>
