<?php
session_start();
// Apenas Admin pode acessar
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_status'])) {
    try {
        $id_registro = (int)$_POST['id_registro'];
        
        // Verifica checkboxes (marcado = 'sim', desmarcado = 'nao')
        $online = isset($_POST['StatusOnline']) ? 'sim' : 'nao';
        $desconectado = isset($_POST['StatusDesconectado']) ? 'sim' : 'nao';
        $falhado = isset($_POST['StatusFalhado']) ? 'sim' : 'nao';
        $logs = isset($_POST['StatusLogs']) ? 'sim' : 'nao';
        $reshare = isset($_POST['StatusReshare']) ? 'sim' : 'nao';

        // Atualiza no banco
        $sql = "UPDATE status SET StatusOnline = ?, StatusDesconectado = ?, StatusFalhado = ?, StatusLogs = ?, StatusReshare = ? WHERE id = ?";
        $stmt = $connAcessos->prepare($sql);
        $stmt->execute([$online, $desconectado, $falhado, $logs, $reshare, $id_registro]);
        
        $msg = "Configurações de status atualizadas!";
        $msg_tipo = "success";
    } catch (Exception $e) {
        $msg = "Erro ao salvar: " . $e->getMessage();
        $msg_tipo = "danger";
    }
}

// 2. BUSCAR DADOS DA TABELA STATUS
try {
    $lista_status = $connAcessos->query("SELECT * FROM status ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $lista_status = [];
    $msg = "Erro ao buscar dados: " . $e->getMessage();
    $msg_tipo = "danger";
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gerenciar Status</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: #0dcaf0; border-color: #0dcaf0; } /* Cor Ciano */
        .switch-label { cursor: pointer; display: flex; align-items: center; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #333; }
        .switch-label:last-child { border-bottom: none; }
        .badge-grupo { background: rgba(13, 202, 240, 0.2); color: #0dcaf0; padding: 5px 10px; border-radius: 5px; font-weight: bold; font-size: 0.9rem; }

        @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_status.php" class="btn btn-primary text-start border-0 py-2"><i class="fas fa-signal me-2"></i> Config. Status</a>
    </div>
</nav>

<main class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold">Visualização de Status</h3>
        <span class="text-white-50">Defina quais status cada grupo pode ver</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($lista_status)): ?>
            <div class="col-12"><div class="alert alert-warning">Nenhum registro encontrado na tabela 'status'.</div></div>
        <?php else: ?>
            <?php foreach($lista_status as $s): ?>
            <div class="col-md-6 col-lg-4">
                <form method="POST">
                    <input type="hidden" name="salvar_status" value="1">
                    <input type="hidden" name="id_registro" value="<?= $s['id'] ?>">
                    
                    <div class="card card-custom p-3 border-top border-3 border-info">
                        <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><?= $s['grupo'] ?></span>
                            <button class="btn btn-sm btn-outline-info"><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-success fw-bold" for="on_<?= $s['id'] ?>"><i class="fas fa-circle me-2 small"></i>Online</label>
                                <input class="form-check-input" type="checkbox" name="StatusOnline" id="on_<?= $s['id'] ?>" <?= ($s['StatusOnline'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-secondary fw-bold" for="off_<?= $s['id'] ?>"><i class="fas fa-circle me-2 small"></i>Desconectado</label>
                                <input class="form-check-input" type="checkbox" name="StatusDesconectado" id="off_<?= $s['id'] ?>" <?= ($s['StatusDesconectado'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-danger fw-bold" for="fail_<?= $s['id'] ?>"><i class="fas fa-times-circle me-2 small"></i>Falhado</label>
                                <input class="form-check-input" type="checkbox" name="StatusFalhado" id="fail_<?= $s['id'] ?>" <?= ($s['StatusFalhado'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-warning fw-bold" for="log_<?= $s['id'] ?>"><i class="fas fa-file-alt me-2 small"></i>Logs</label>
                                <input class="form-check-input" type="checkbox" name="StatusLogs" id="log_<?= $s['id'] ?>" <?= ($s['StatusLogs'] == 'sim') ? 'checked' : '' ?>>
                            </div>

                            <div class="form-check form-switch switch-label">
                                <label class="form-check-label text-info fw-bold" for="resh_<?= $s['id'] ?>"><i class="fas fa-share-alt me-2 small"></i>Reshare</label>
                                <input class="form-check-input" type="checkbox" name="StatusReshare" id="resh_<?= $s['id'] ?>" <?= ($s['StatusReshare'] == '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>
