<?php
// Configuração do caminho do JSON
$json_file = './api/panaci_mensagens_individuais.json';

// Carregar dados
$mensagens = file_exists($json_file) ? json_decode(file_get_contents($json_file), true) : [];

// Lógica de Salvar / Editar
if (isset($_POST['save_mac'])) {
    $mac = strtoupper(trim($_POST['mac']));
    $mensagens[$mac] = [
        'titulo' => $_POST['titulo'],
        'mensagem' => $_POST['mensagem'],
        'cor_titulo' => $_POST['cor_titulo'] ?? '#3b82f6',
        'cor_desc' => $_POST['cor_desc'] ?? '#ffffff',
        'status' => isset($_POST['status']) ? 'on' : 'off'
    ];
    file_put_contents($json_file, json_encode($mensagens, JSON_PRETTY_PRINT));
    header("Location: panaci_gerenciar_notemac.php?success=1");
    exit();
}

// Lógica de Excluir
if (isset($_GET['delete'])) {
    $mac_del = $_GET['delete'];
    unset($mensagens[$mac_del]);
    file_put_contents($json_file, json_encode($mensagens, JSON_PRETTY_PRINT));
    header("Location: panaci_gerenciar_notemac.php?success=3");
    exit();
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Gerenciar MAC | Premium</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <style>
        * { box-sizing: border-box; }
        body { 
            background-color: #020617 !important; 
            color: #e2e8f0 !important; 
            font-family: 'Segoe UI', sans-serif; 
            margin: 0; padding: 15px;
            overflow-x: hidden;
        }
        .container { max-width: 650px; margin: 0 auto; width: 100%; position: relative; }
        
        /* BOTÃO VOLTAR DASHBOARD */
        .btn-back-dashboard {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            background: rgba(30, 41, 59, 0.5);
            color: #fff;
            text-decoration: none;
            padding: 10px 18px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 700;
            border: 1px solid #1e293b;
            transition: 0.3s;
            margin-bottom: 20px;
        }
        .btn-back-dashboard:hover {
            background: #3b82f6;
            border-color: #3b82f6;
            transform: translateX(-5px);
        }

        .header-main-title { text-align: center; margin-bottom: 30px; }
        .header-main-title h1 { font-size: 1.5rem; font-weight: 800; color: #fff; margin-bottom: 5px; }
        .header-main-title p { color: #64748b; font-size: 0.85rem; }

        .premium-card {
            background: #070e1b !important;
            border: 1px solid #1e293b !important;
            border-radius: 20px;
            padding: 25px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
            margin-bottom: 20px;
            animation: slideInUp 0.5s ease-out;
        }
        .card-header-premium { 
            margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.05); 
            padding-bottom: 10px; display: flex; justify-content: space-between; align-items: center;
        }
        .card-header-premium h2 { font-size: 1.1rem; font-weight: 800; color: #3b82f6; margin: 0; text-transform: uppercase; }
        
        label { display: block; color: #3b82f6; font-size: 0.7rem; font-weight: 800; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 1px; }
        .form-input { 
            width: 100%; background: #0f172a !important; border: 1px solid #1e293b !important; 
            color: #fff !important; padding: 12px; border-radius: 12px; font-size: 0.9rem; margin-bottom: 15px; transition: 0.3s;
        }
        .form-input:focus { border-color: #3b82f6 !important; outline: none; }
        
        .color-row { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px; }
        input[type="color"] { height: 45px; padding: 2px; cursor: pointer; }

        .btn-premium-save {
            width: 100%; background: #3b82f6 !important; color: #fff !important; padding: 18px; border-radius: 15px; 
            font-weight: 800; text-transform: uppercase; border: none; cursor: pointer; display: flex; 
            align-items: center; justify-content: center; gap: 10px; transition: 0.3s;
        }
        .btn-premium-save:hover { background: #2563eb !important; transform: translateY(-2px); }

        .msg-list-card {
            background: #0f172a; border: 1px solid #1e293b; border-radius: 15px; padding: 15px; margin-bottom: 15px;
            display: flex; flex-direction: column; gap: 10px; position: relative;
        }
        .info-row { display: flex; align-items: center; gap: 10px; font-size: 0.9rem; color: #94a3b8; }
        .info-row i { color: #3b82f6; width: 20px; text-align: center; }
        .status-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
        .status-on { background: #10b981; box-shadow: 0 0 10px #10b981; }
        .status-off { background: #ef4444; }

        .actions-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; }
        .btn-action { 
            padding: 10px; border-radius: 10px; text-align: center; text-decoration: none; 
            font-weight: bold; font-size: 0.8rem; display: flex; align-items: center; justify-content: center; gap: 5px;
        }
        .btn-edit-pre { background: #fbbf24; color: #000; cursor: pointer; border:none; }
        .btn-del-pre { background: #ef4444; color: #fff; cursor: pointer; border:none; }

        @keyframes slideInUp { from { transform: translate3d(0, 40px, 0); opacity: 0; } to { transform: translate3d(0, 0, 0); opacity: 1; } }
    </style>
</head>
<body>

<div class="container">
    <a href="index.php" class="btn-back-dashboard">
        <i class="fas fa-arrow-left"></i> VOLTAR DASHBOARD
    </a>

    <div class="header-main-title">
        <h1>Gerenciar Notificações</h1>
        <p>Controle de mensagens por endereço MAC</p>
    </div>

    <div class="premium-card">
        <div class="card-header-premium">
            <h2><i class="fas fa-paper-plane animate__animated animate__infinite animate__pulse"></i> Nova Mensagem</h2>
            <i class="fas fa-microchip" style="color: #1e293b;"></i>
        </div>
        <form method="POST" id="mainForm">
            <label>Endereço MAC do Aparelho</label>
            <input type="text" name="mac" id="mac_input" class="form-input" placeholder="00:00:00:00:00:00" required>

            <label>Título da Notificação</label>
            <input type="text" name="titulo" id="titulo_input" class="form-input" placeholder="Ex: Aviso Importante" required>

            <label>Mensagem Detalhada</label>
            <textarea name="mensagem" id="msg_input" class="form-input" rows="3" placeholder="Digite o conteúdo aqui..." required></textarea>

            <div class="color-row">
                <div>
                    <label>Cor do Título</label>
                    <input type="color" name="cor_titulo" id="cor_tit_input" class="form-input" value="#3b82f6">
                </div>
                <div>
                    <label>Cor da Descrição</label>
                    <input type="color" name="cor_desc" id="cor_desc_input" class="form-input" value="#ffffff">
                </div>
            </div>

            <label style="display: flex; align-items: center; gap: 10px; cursor: pointer; margin-bottom: 20px;">
                <input type="checkbox" name="status" id="status_checkbox" checked style="width: 20px; height: 20px;"> 
                <span style="font-size: 0.8rem; font-weight: 800; color: #10b981;">ATIVAR ENVIO AGORA</span>
            </label>

            <button type="submit" name="save_mac" class="btn-premium-save">
                <i class="fas fa-save"></i> SALVAR NO SISTEMA
            </button>
        </form>
    </div>

    <div class="header-main-title" style="margin-top: 40px;">
        <h2><i class="fas fa-list"></i> Mensagens Ativas</h2>
    </div>

    <?php if(empty($mensagens)): ?>
        <p style="text-align:center; color:#64748b;">Nenhum MAC cadastrado.</p>
    <?php endif; ?>

    <?php foreach($mensagens as $mac => $info): ?>
    <div class="msg-list-card animate__animated animate__fadeIn">
        <div style="display: flex; justify-content: space-between; align-items: flex-start;">
            <div class="info-row">
                <i class="fas fa-id-card"></i> 
                <strong style="color: #fff;"><?= $mac ?></strong>
                <span class="status-dot <?= $info['status'] == 'on' ? 'status-on' : 'status-off' ?>"></span>
            </div>
        </div>
        
        <div class="info-row">
            <i class="fas fa-heading"></i>
            <span style="color: <?= $info['cor_titulo'] ?>; font-weight: bold;"><?= $info['titulo'] ?></span>
        </div>

        <div class="info-row">
            <i class="fas fa-align-left"></i>
            <span style="color: <?= $info['cor_desc'] ?>; font-size: 0.85rem;"><?= htmlspecialchars($info['mensagem']) ?></span>
        </div>

        <div class="actions-row">
            <button onclick="confirmEdit('<?= $mac ?>', '<?= addslashes($info['titulo']) ?>', '<?= str_replace(["\r", "\n"], [' ', ' '], addslashes($info['mensagem'])) ?>', '<?= $info['cor_titulo'] ?>', '<?= $info['cor_desc'] ?>', '<?= $info['status'] ?>')" class="btn-action btn-edit-pre">
                <i class="fas fa-edit"></i> EDITAR
            </button>
            <button onclick="confirmDelete('<?= $mac ?>')" class="btn-action btn-del-pre">
                <i class="fas fa-trash"></i> EXCLUIR
            </button>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    const urlParams = new URLSearchParams(window.location.search);
    if(urlParams.has('success')) {
        const type = urlParams.get('success');
        let text = type == "1" ? "Mensagem salva com sucesso!" : "MAC excluído do sistema!";
        
        Swal.fire({
            icon: 'success',
            title: 'Sucesso!',
            text: text,
            background: '#070e1b',
            color: '#fff',
            confirmButtonColor: '#3b82f6'
        });
    }

    function confirmEdit(mac, titulo, msg, corT, corD, status) {
        Swal.fire({
            title: 'Editar este MAC?',
            text: "As informações serão carregadas no formulário acima.",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#fbbf24',
            cancelButtonColor: '#1e293b',
            confirmButtonText: 'Sim, Editar!',
            cancelButtonText: 'Cancelar',
            background: '#070e1b',
            color: '#fff'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('mac_input').value = mac;
                document.getElementById('titulo_input').value = titulo;
                document.getElementById('msg_input').value = msg;
                document.getElementById('cor_tit_input').value = corT;
                document.getElementById('cor_desc_input').value = corD;
                document.getElementById('status_checkbox').checked = (status === 'on');
                
                window.scrollTo({ top: 0, behavior: 'smooth' });
                
                const form = document.querySelector('.premium-card');
                form.classList.add('animate__animated', 'animate__headShake');
                setTimeout(() => form.classList.remove('animate__headShake'), 1000);
            }
        });
    }

    function confirmDelete(mac) {
        Swal.fire({
            title: 'Tem certeza?',
            text: "Esta mensagem será removida permanentemente!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#1e293b',
            confirmButtonText: 'Sim, Excluir!',
            cancelButtonText: 'Cancelar',
            background: '#070e1b',
            color: '#fff'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '?delete=' + mac;
            }
        });
    }
</script>
</body>
</html>
