<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


$file_path = 'a/note.json';
include 'includes/header.php';

// GARANTE QUE O ARQUIVO EXISTE
if (!file_exists($file_path)) {
    file_put_contents($file_path, json_encode([
        'title' => '',
        'content' => '',
        'enabled' => true // adiciona a flag
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

// LÊ O JSON
$file_content = file_get_contents($file_path);
$data_array = json_decode($file_content, true);

// FLAG DO JSON
$enabled = $data_array['enabled'] ?? true;

// SALVAR POST
if (isset($_POST['text'])) {

    $new_data = [
        'title'   => $_POST['title'] ?? '',
        'content' => $_POST['content'] ?? '',
        'enabled' => isset($_POST['enabled']) ? (bool)$_POST['enabled'] : true
    ];

    file_put_contents(
        $file_path,
        json_encode($new_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)
    );

    $file_content = file_get_contents($file_path);
    $data_array = json_decode($file_content, true);
    $enabled = $data_array['enabled'] ?? true;

    echo "<script>
        Swal.fire({
            icon: 'success',
            title: 'Sucesso!',
            text: 'Notificação atualizada com sucesso!',
            timer: 2000,
            showConfirmButton: false
        });
    </script>";
}

// BOTÃO DE ATIVAR/DESATIVAR
if (isset($_POST['toggle'])) {
    $enabled = !$enabled; // alterna
    $data_array['enabled'] = $enabled;
    file_put_contents($file_path, json_encode($data_array, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

    echo "<script>
        Swal.fire({
            icon: 'info',
            title: 'Status alterado!',
            text: 'Notificação " . ($enabled ? "ativada" : "desativada") . "',
            timer: 2000,
            showConfirmButton: false
        });
    </script>";
}

// DADOS ATUALIZADOS
$title   = $data_array['title']   ?? '';
$content = $data_array['content'] ?? '';


?>

<style>
/* Estilos futuristas para Notificações */
:root {
    --primary: #00D4FF;
    --primary-dark: #0099CC;
    --secondary: #FF6B9D;
    --accent: #00FF88;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(0, 212, 255, 0.3);
    --glow-accent: 0 0 20px rgba(0, 255, 136, 0.3);
    --error: #FF4757;
    --success: #00D084;
}

.futuristic-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
    animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.futuristic-title {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 32px;
    font-weight: 700;
    margin-bottom: 10px;
    text-align: center;
    text-shadow: 0 0 10px rgba(0, 212, 255, 0.3);
    letter-spacing: 1px;
}

.futuristic-subtitle {
    color: var(--text-secondary);
    font-size: 16px;
    text-align: center;
    margin-bottom: 30px;
    font-weight: 400;
}

.futuristic-card {
    background: rgba(26, 31, 44, 0.9);
    backdrop-filter: blur(20px);
    border-radius: 20px;
    border: 1px solid var(--border);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    margin-bottom: 30px;
    transition: all 0.3s ease;
}

.futuristic-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 40px rgba(0, 212, 255, 0.2);
    border-color: var(--primary);
}

.futuristic-card-header {
    background: linear-gradient(135deg, rgba(26, 31, 44, 0.9), rgba(42, 47, 60, 0.9));
    padding: 25px 30px;
    border-bottom: 1px solid var(--border);
    position: relative;
    overflow: hidden;
}

.futuristic-card-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, var(--primary), transparent);
}

.futuristic-card-title {
    color: var(--text-primary);
    font-size: 20px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 15px;
}

.futuristic-card-title i {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 24px;
}

.futuristic-card-body {
    padding: 30px;
}

/* Formulário Futurista */
.futuristic-form {
    max-width: 800px;
    margin: 0 auto;
}

.futuristic-form-group {
    margin-bottom: 25px;
    animation: slideInUp 0.5s ease forwards;
    animation-delay: calc(var(--item-index, 0) * 0.1s);
    opacity: 0;
}

@keyframes slideInUp {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.futuristic-label {
    display: flex;
    align-items: center;
    gap: 10px;
    color: var(--text-primary);
    font-weight: 500;
    margin-bottom: 10px;
    font-size: 14px;
    letter-spacing: 0.5px;
}

.futuristic-label i {
    color: var(--primary);
    font-size: 16px;
    width: 20px;
    text-align: center;
}

.futuristic-label span {
    font-weight: 600;
    color: var(--accent);
}

.futuristic-input-group {
    position: relative;
}

.futuristic-input {
    width: 100%;
    padding: 16px 20px;
    background: rgba(10, 15, 28, 0.6);
    border: 1px solid var(--border);
    border-radius: 12px;
    color: var(--text-primary);
    font-size: 14px;
    transition: all 0.3s ease;
    outline: none;
}

.futuristic-input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 212, 255, 0.1);
    background: rgba(10, 15, 28, 0.8);
}

.futuristic-input::placeholder {
    color: var(--text-muted);
}

.futuristic-input-icon {
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-muted);
    font-size: 16px;
    z-index: 2;
    transition: color 0.3s ease;
}

.futuristic-input:focus + .futuristic-input-icon {
    color: var(--primary);
}

.futuristic-input-hint {
    display: block;
    color: var(--text-muted);
    font-size: 11px;
    margin-top: 6px;
    font-style: italic;
}

.futuristic-btn {
    padding: 16px 35px;
    border-radius: 12px;
    font-weight: 600;
    font-size: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 12px;
    text-decoration: none;
    border: none;
    min-width: 180px;
    justify-content: center;
}

.futuristic-btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    box-shadow: var(--glow);
}

.futuristic-btn-primary:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 30px rgba(0, 212, 255, 0.4);
    background: linear-gradient(135deg, var(--primary-dark), var(--primary));
}

.futuristic-btn-primary i {
    font-size: 18px;
}

/* Preview Card */
.futuristic-preview-card {
    background: rgba(10, 15, 28, 0.6);
    border-radius: 15px;
    padding: 25px;
    margin-top: 30px;
    border: 1px solid var(--border);
    position: relative;
    overflow: hidden;
}

.futuristic-preview-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, var(--accent), transparent);
}

.futuristic-preview-title {
    color: var(--accent);
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.futuristic-preview-content {
    color: var(--text-secondary);
    font-size: 14px;
    line-height: 1.6;
}

.futuristic-preview-badge {
    position: absolute;
    top: 15px;
    right: 15px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    box-shadow: var(--glow);
}

/* Stats Cards */
.futuristic-stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-top: 30px;
}

.futuristic-stat-card {
    background: rgba(10, 15, 28, 0.4);
    border-radius: 15px;
    padding: 20px;
    border: 1px solid var(--border);
    transition: all 0.3s ease;
}

.futuristic-stat-card:hover {
    transform: translateY(-5px);
    border-color: var(--primary);
}

.futuristic-stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 12px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 15px;
    font-size: 20px;
    color: white;
    box-shadow: var(--glow);
}

.futuristic-stat-title {
    color: var(--text-secondary);
    font-size: 13px;
    font-weight: 500;
    margin-bottom: 5px;
}

.futuristic-stat-value {
    color: var(--text-primary);
    font-size: 24px;
    font-weight: 700;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.futuristic-stat-desc {
    color: var(--text-muted);
    font-size: 11px;
    margin-top: 5px;
}

/* Responsividade */
@media (max-width: 768px) {
    .futuristic-container {
        padding: 15px;
    }
    
    .futuristic-title {
        font-size: 28px;
    }
    
    .futuristic-subtitle {
        font-size: 14px;
    }
    
    .futuristic-card-body {
        padding: 20px;
    }
    
    .futuristic-card-header {
        padding: 20px;
    }
    
    .futuristic-card-title {
        font-size: 18px;
    }
    
    .futuristic-input {
        padding: 14px 18px;
        font-size: 13px;
    }
    
    .futuristic-btn {
        width: 100%;
        padding: 14px 25px;
    }
    
    .futuristic-stats-container {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 480px) {
    .futuristic-container {
        padding: 10px;
    }
    
    .futuristic-title {
        font-size: 24px;
    }
    
    .futuristic-card-body {
        padding: 15px;
    }
    
    .futuristic-card-header {
        padding: 15px;
    }
    
    .futuristic-input {
        padding: 12px 16px;
        font-size: 12px;
    }
    
    .futuristic-btn {
        padding: 12px 20px;
        font-size: 14px;
    }
}

/* Character Counter */
.futuristic-char-counter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 5px;
    font-size: 11px;
    color: var(--text-muted);
}

.futuristic-char-count {
    font-weight: 600;
}

.futuristic-char-count.warning {
    color: var(--secondary);
}

.futuristic-char-count.danger {
    color: var(--error);
}

/* Notification Preview Animation */
@keyframes pulseGlow {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.7; }
}

.futuristic-notification-pulse {
    animation: pulseGlow 2s infinite;
}
</style>


<div class="futuristic-container">
    <h1 class="futuristic-title">Configuração de Notificações</h1>
    <p class="futuristic-subtitle">Gerencie as notificações do sistema para todos os usuários</p>
    
    <div class="futuristic-card">
        <div class="futuristic-card-header">
            <h2 class="futuristic-card-title">
                <i class="fas fa-bullhorn"></i>
                Configurar Notificação Global
            </h2>
        </div>
        
        <div class="futuristic-card-body">
            <form method="post" id="notificationForm" class="futuristic-form">
                <div class="futuristic-form-group" style="--item-index: 0">
                    <label class="futuristic-label">
                        <i class="fas fa-heading"></i>
                        <span>Título da Notificação</span>
                    </label>
                    <div class="futuristic-input-group">
                        <input type="text" class="futuristic-input" id="title" name="title" 
                               placeholder="Digite o título da notificação" 
                               value="<?php echo htmlspecialchars($title); ?>" 
                               maxlength="100" required>
                    </div>
                    <div class="futuristic-char-counter">
                        <span>Máximo: 100 caracteres</span>
                        <span class="futuristic-char-count" id="titleCounter"><?php echo strlen($title); ?>/100</span>
                    </div>
                </div>
                
                <div class="futuristic-form-group" style="--item-index: 1">
                    <label class="futuristic-label">
                        <i class="fas fa-comment-alt"></i>
                        <span>Mensagem da Notificação</span>
                    </label>
                    <div class="futuristic-input-group">
                        <textarea class="futuristic-input" id="content" name="content" 
                                  placeholder="Digite a mensagem da notificação" 
                                  rows="4" maxlength="500" required
                                  style="resize: vertical; min-height: 120px;"><?php echo htmlspecialchars($content); ?></textarea>
                    </div>
                    <div class="futuristic-char-counter">
                        <span>Máximo: 500 caracteres</span>
                        <span class="futuristic-char-count" id="contentCounter"><?php echo strlen($content); ?>/500</span>
                    </div>
                </div>
                
                <div class="futuristic-preview-card futuristic-notification-pulse">
                    <span class="futuristic-preview-badge">PREVIEW</span>
                    <div class="futuristic-preview-title">
                        <i class="fas fa-eye"></i>
                        Visualização da Notificação
                    </div>
                    <div class="futuristic-preview-content">
                        <div style="margin-bottom: 15px;">
                            <strong style="color: var(--primary);" id="previewTitle"><?php echo htmlspecialchars($title); ?></strong>
                        </div>
                        <div id="previewContent">
                            <?php echo nl2br(htmlspecialchars($content)); ?>
                        </div>
                    </div>
                </div>
                
                <div style="margin-top: 30px; text-align: center;">
                    <button type="submit" name="text" class="futuristic-btn futuristic-btn-primary" id="submitBtn">
                        <i class="fas fa-paper-plane"></i>
                        <span>Atualizar Notificação</span>
                    </button>
                </div>
                
                <!-- Botão de Ativar/Desativar -->
<div style="text-align: center; margin: 20px 0;">
    <form method="post">
        <button type="submit" name="toggle" class="futuristic-btn futuristic-btn-primary">
            <i class="fas fa-power-off"></i>
            <?php echo $enabled ? 'Desativar Notificação' : 'Ativar Notificação'; ?>
        </button>
    </form>
</div>

<!-- Exibir Status Atual -->
<div style="text-align: center; margin-bottom: 20px;">
    <strong>Status da Notificação:</strong> <?php echo $enabled ? 'Ativa' : 'Inativa'; ?>
</div>

            </form>
        </div>
    </div>
    
    <!-- Cards de Estatísticas -->
    <div class="futuristic-stats-container">
        <div class="futuristic-stat-card">
            <div class="futuristic-stat-icon">
                <i class="fas fa-broadcast-tower"></i>
            </div>
            <div class="futuristic-stat-title">Alcance</div>
            <div class="futuristic-stat-value" id="reachValue">Todos</div>
            <div class="futuristic-stat-desc">Todos os usuários do sistema</div>
        </div>
        
        <div class="futuristic-stat-card">
            <div class="futuristic-stat-icon">
                <i class="fas fa-clock"></i>
            </div>
            <div class="futuristic-stat-title">Última Atualização</div>
            <div class="futuristic-stat-value" id="lastUpdate">
                <?php 
                    if (file_exists($file_path)) {
                        $fileTime = filemtime($file_path);
                        echo date('d/m H:i', $fileTime);
                    } else {
                        echo 'Nunca';
                    }
                ?>
            </div>
            <div class="futuristic-stat-desc">Horário da última alteração</div>
        </div>
        
        <div class="futuristic-stat-card">
            <div class="futuristic-stat-icon">
                <i class="fas fa-users"></i>
            </div>
            <div class="futuristic-stat-title">Status</div>
            <div class="futuristic-stat-value">
                <?php echo (!empty($title) || !empty($content)) ? 'Ativa' : 'Inativa'; ?>
            </div>
            <div class="futuristic-stat-desc">
                <?php echo (!empty($title) || !empty($content)) ? 'Notificação visível' : 'Sem notificação'; ?>
            </div>
        </div>
        
        <div class="futuristic-stat-card">
            <div class="futuristic-stat-icon">
                <i class="fas fa-code"></i>
            </div>
            <div class="futuristic-stat-title">JSON Status</div>
            <div class="futuristic-stat-value" id="jsonStatus">
                <?php echo (json_last_error() === JSON_ERROR_NONE) ? 'OK' : 'Erro'; ?>
            </div>
            <div class="futuristic-stat-desc">
                <?php echo (json_last_error() === JSON_ERROR_NONE) ? 'JSON válido' : 'JSON inválido'; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Elementos
    const form = document.getElementById('notificationForm');
    const titleInput = document.getElementById('title');
    const contentInput = document.getElementById('content');
    const titleCounter = document.getElementById('titleCounter');
    const contentCounter = document.getElementById('contentCounter');
    const previewTitle = document.getElementById('previewTitle');
    const previewContent = document.getElementById('previewContent');
    const submitBtn = document.getElementById('submitBtn');
    const reachValue = document.getElementById('reachValue');
    const jsonStatus = document.getElementById('jsonStatus');
    
    // Atualizar contadores de caracteres
    function updateCharCounters() {
        const titleLength = titleInput.value.length;
        const contentLength = contentInput.value.length;
        
        // Atualizar contadores
        titleCounter.textContent = `${titleLength}/100`;
        contentCounter.textContent = `${contentLength}/500`;
        
        // Estilizar baseado no limite
        titleCounter.className = 'futuristic-char-count';
        contentCounter.className = 'futuristic-char-count';
        
        if (titleLength > 80) {
            titleCounter.classList.add('warning');
        }
        if (titleLength > 95) {
            titleCounter.classList.add('danger');
        }
        
        if (contentLength > 400) {
            contentCounter.classList.add('warning');
        }
        if (contentLength > 480) {
            contentCounter.classList.add('danger');
        }
        
        // Atualizar preview
        previewTitle.textContent = titleInput.value || '[Sem título]';
        previewContent.innerHTML = contentInput.value.replace(/\n/g, '<br>') || '[Sem mensagem]';
    }
    
    // Inicializar contadores
    updateCharCounters();
    
    // Atualizar em tempo real
    titleInput.addEventListener('input', updateCharCounters);
    contentInput.addEventListener('input', updateCharCounters);
    
    // Calcular alcance estimado
    function calculateReach() {
        // Esta função poderia buscar dados reais do banco de dados
        // Por enquanto, é apenas visual
        const titleLength = titleInput.value.length;
        const contentLength = contentInput.value.length;
        
        if (titleLength === 0 && contentLength === 0) {
            reachValue.textContent = 'Nenhum';
            reachValue.style.color = 'var(--text-muted)';
        } else if (titleLength < 5 || contentLength < 10) {
            reachValue.textContent = 'Baixo';
            reachValue.style.color = 'var(--secondary)';
        } else if (titleLength < 20 || contentLength < 100) {
            reachValue.textContent = 'Médio';
            reachValue.style.color = 'var(--primary)';
        } else {
            reachValue.textContent = 'Alto';
            reachValue.style.color = 'var(--accent)';
        }
    }
    
    // Atualizar alcance em tempo real
    titleInput.addEventListener('input', calculateReach);
    contentInput.addEventListener('input', calculateReach);
    
    // Validar formulário
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const title = titleInput.value.trim();
        const content = contentInput.value.trim();
        
        let isValid = true;
        const errors = [];
        
        // Validar título
        if (title.length === 0) {
            errors.push('O título é obrigatório');
            isValid = false;
        } else if (title.length > 100) {
            errors.push('O título não pode ter mais de 100 caracteres');
            isValid = false;
        }
        
        // Validar conteúdo
        if (content.length === 0) {
            errors.push('A mensagem é obrigatória');
            isValid = false;
        } else if (content.length > 500) {
            errors.push('A mensagem não pode ter mais de 500 caracteres');
            isValid = false;
        }
        
        if (!isValid) {
            Swal.fire({
                icon: 'error',
                title: 'Erro de Validação',
                html: '<div style="text-align: left;">' + 
                      errors.map(error => `<p>• ${error}</p>`).join('') + 
                      '</div>',
                confirmButtonColor: '#00D4FF'
            });
            return;
        }
        
        // Mostrar loading
        const originalContent = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Atualizando...';
        submitBtn.disabled = true;
        
        // Simular delay para efeito visual
        setTimeout(() => {
            // Se tudo estiver OK, enviar formulário
            form.submit();
        }, 1000);
    });
    
    // Efeitos visuais nos inputs
    const inputs = [titleInput, contentInput];
    inputs.forEach(input => {
        // Efeito de foco
        input.addEventListener('focus', function() {
            this.style.borderColor = 'var(--primary)';
            this.style.boxShadow = '0 0 0 2px rgba(0, 212, 255, 0.1)';
        });
        
        input.addEventListener('blur', function() {
            this.style.borderColor = '';
            this.style.boxShadow = '';
        });
        
        // Auto-expand textarea
        if (input.tagName === 'TEXTAREA') {
            input.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = (this.scrollHeight) + 'px';
            });
        }
    });
    
    // Auto-focus no título
    setTimeout(() => {
        titleInput.focus();
    }, 300);
    
    // Verificar status do JSON
    function checkJsonStatus() {
        // Simulação - em produção, poderia fazer uma requisição AJAX
        const currentData = {
            title: titleInput.value,
            content: contentInput.value
        };
        
        try {
            const jsonStr = JSON.stringify(currentData);
            JSON.parse(jsonStr);
            jsonStatus.textContent = 'OK';
            jsonStatus.style.color = 'var(--accent)';
        } catch (error) {
            jsonStatus.textContent = 'Erro';
            jsonStatus.style.color = 'var(--error)';
        }
    }
    
    // Verificar JSON em tempo real
    titleInput.addEventListener('input', checkJsonStatus);
    contentInput.addEventListener('input', checkJsonStatus);
    
    // Inicializar cálculos
    calculateReach();
    checkJsonStatus();
    
    // Configurar SweetAlert2
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Notificações',
            text: 'Configure as notificações globais do sistema.',
            icon: 'info',
            timer: 3000,
            showConfirmButton: false,
            toast: true,
            position: 'top-end'
        });
    }
    
    // Efeito de digitação para preview (opcional)
    function typeWriterEffect(element, text, speed = 50) {
        let i = 0;
        element.innerHTML = '';
        
        function type() {
            if (i < text.length) {
                element.innerHTML += text.charAt(i);
                i++;
                setTimeout(type, speed);
            }
        }
        
        type();
    }
    
    // Aplicar efeito de digitação na inicialização (apenas para demonstração)
    if (titleInput.value.length > 0) {
        setTimeout(() => {
            typeWriterEffect(previewTitle, titleInput.value, 100);
        }, 500);
    }
});
</script>

<?php 
include 'includes/footer.php';
?>
</html>