<?php

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


include 'includes/header.php';

// Configurações
$json_dir = 'a/json/';
$db_path = 'a/.eggziedb.db';

// Criar diretório se não existir
if (!file_exists($json_dir)) {
    mkdir($json_dir, 0777, true);
}

// Função para buscar todos os clientes do banco
function getAllClients($db_path) {
    if (!file_exists($db_path)) {
        return [];
    }
    
    try {
        $db = new SQLite3($db_path);
        
        // Query - MAC, Extra e mais algumas colunas úteis
        $queryStr = "SELECT mac_address, extra, username, expire_date FROM ibo WHERE mac_address IS NOT NULL AND mac_address != '' ORDER BY mac_address ASC";
        
        $query = $db->query($queryStr);
        
        $clients = [];
        while ($row = $query->fetchArray(SQLITE3_ASSOC)) {
            $clients[] = [
                'mac_address' => $row['mac_address'] ?? '',
                'extra' => $row['extra'] ?? '',
                'username' => $row['username'] ?? '',
                'expire_date' => $row['expire_date'] ?? ''
            ];
        }
        
        return $clients;
        
    } catch (Exception $e) {
        return [];
    }
}

// Buscar clientes
$clients = getAllClients($db_path);

// Função para ativar/desativar notificação individual
if (isset($_GET['toggle_notification'])) {
    $mac = $_GET['toggle_notification'];
    $action = $_GET['action'] ?? 'disable';
    
    // Nome do arquivo baseado no MAC
    $filename = str_replace([':', '/', '\\', '?', '*', '"', '<', '>', '|'], '_', strtolower($mac)) . '.json';
    $filepath = $json_dir . $filename;
    
    if (file_exists($filepath)) {
        $content = file_get_contents($filepath);
        $data = json_decode($content, true);
        
        if ($action === 'disable') {
            $data['enabled'] = false;
            $data['updated_at'] = date('Y-m-d H:i:s');
            $success = "Notificação desativada para MAC: $mac";
        } else {
            $data['enabled'] = true;
            $data['updated_at'] = date('Y-m-d H:i:s');
            $success = "Notificação ativada para MAC: $mac";
        }
        
        file_put_contents($filepath, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    }
}

// Processar envio de notificação individual
if (isset($_POST['send_individual'])) {
    $mac = $_POST['mac_address'] ?? '';
    $title = $_POST['title'] ?? '';
    $content = $_POST['content'] ?? '';
    $expire_date = $_POST['expire_date'] ?? '';
    
    // Validar MAC
    if (empty($mac) || empty($title)) {
        $error = "MAC address e título são obrigatórios!";
    } else {
        // Criar JSON individual
        $notification_data = [
            'title' => $title,
            'content' => $content,
            'expire_date' => $expire_date,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'enabled' => true
        ];
        
        // Nome do arquivo baseado no MAC
        $filename = str_replace([':', '/', '\\', '?', '*', '"', '<', '>', '|'], '_', strtolower($mac));
$filepath = $json_dir . $filename . '.json';
        
        // Salvar arquivo
        if (file_put_contents($filepath, json_encode($notification_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT))) {
            $success = "Notificação enviada para MAC: <strong>$mac</strong>";
        } else {
            $error = "Erro ao salvar notificação para MAC: $mac";
        }
    }
}

// Processar envio em massa
if (isset($_POST['send_bulk'])) {
    $title = $_POST['bulk_title'] ?? '';
    $content = $_POST['bulk_content'] ?? '';
    $enabled_by_default = isset($_POST['enabled_by_default']) ? true : false;
    
    if (empty($title) || empty($content)) {
        $bulk_error = "Título e conteúdo são obrigatórios!";
    } else {
        $selected_clients = $_POST['selected_clients'] ?? [];
        $bulk_success = [];
        $bulk_failed = [];
        
        foreach ($selected_clients as $mac) {
            $notification_data = [
                'title' => $title,
                'content' => $content,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'enabled' => $enabled_by_default
            ];
            
            $filename = str_replace([':', '/', '\\', '?', '*', '"', '<', '>', '|'], '_', strtolower($mac));
$filepath = $json_dir . $filename . '.json';
            
            if (file_put_contents($filepath, json_encode($notification_data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT))) {
                $bulk_success[] = $mac;
            } else {
                $bulk_failed[] = $mac;
            }
        }
        
        if (!empty($bulk_success)) {
            $bulk_message = "Enviado para " . count($bulk_success) . " cliente(s)";
        }
        if (!empty($bulk_failed)) {
            $bulk_message .= "<br>Falha em " . count($bulk_failed) . " cliente(s)";
        }
    }
}

// Função para excluir notificação
if (isset($_POST['delete_file'])) {
    $file_to_delete = $_POST['delete_file'];
    $filepath = $json_dir . $file_to_delete;
    
    if (file_exists($filepath) && unlink($filepath)) {
        $success = "Notificação excluída com sucesso!";
    } else {
        $error = "Erro ao excluir notificação.";
    }
}

// Listar notificações existentes
function getExistingNotifications($json_dir) {
    $notifications = [];
    
    if (file_exists($json_dir) && is_dir($json_dir)) {
        $files = glob($json_dir . '*.json');
        
        foreach ($files as $file) {
            $content = file_get_contents($file);
            $data = json_decode($content, true);
            $filename = basename($file, '.json');
            
            // Converter MAC de volta (substituir underscores por dois-pontos)
            $mac = str_replace('_', ':', $filename);
            
            $notifications[] = [
                'mac' => $mac,
                'title' => $data['title'] ?? '',
                'content' => $data['content'] ?? '',
                'created_at' => $data['created_at'] ?? '',
                'expire_date' => $data['expire_date'] ?? '',
                'enabled' => isset($data['enabled']) ? (bool)$data['enabled'] : true,
                'file' => basename($file)
            ];
        }
    }
    
    return $notifications;
}

$existing_notifications = getExistingNotifications($json_dir);
?>

<style>
/* Estilos mantidos do seu código */
: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;
    --warning: #FFA502;
}

.futuristic-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
}

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

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

.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);
    margin-bottom: 30px;
    padding: 25px;
}

/* Tabela de clientes */
.client-table-container {
    overflow-x: auto;
    margin-top: 20px;
}

.client-table {
    width: 100%;
    border-collapse: collapse;
    background: rgba(10, 15, 28, 0.6);
    border-radius: 12px;
    overflow: hidden;
}

.client-table th {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    padding: 15px;
    text-align: left;
    font-weight: 600;
    font-size: 14px;
}

.client-table td {
    padding: 12px 15px;
    border-bottom: 1px solid var(--border);
    color: var(--text-secondary);
}

.client-table tr:hover {
    background: rgba(0, 212, 255, 0.05);
}

.client-table .mac-cell {
    font-family: 'Courier New', monospace;
    color: var(--accent);
    font-weight: 600;
}

/* Formulários */
.two-column-form {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
}

@media (max-width: 992px) {
    .two-column-form {
        grid-template-columns: 1fr;
    }
}

.form-section {
    background: rgba(10, 15, 28, 0.4);
    border-radius: 15px;
    padding: 25px;
    border: 1px solid var(--border);
}

.section-title {
    color: var(--accent);
    font-size: 18px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 10px;
}

/* Checkbox personalizado */
.client-checkbox {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
    padding: 10px;
    background: rgba(255,255,255,0.05);
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.client-checkbox:hover {
    background: rgba(0, 212, 255, 0.1);
    border-color: var(--primary);
}

.client-checkbox input[type="checkbox"] {
    width: 18px;
    height: 18px;
    accent-color: var(--primary);
}

/* Notificações existentes - SEM BOTÕES */
.notification-item {
    background: rgba(10, 15, 28, 0.4);
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 10px;
    border-left: 3px solid var(--primary);
}

.notification-item.disabled {
    border-left-color: var(--text-muted);
    opacity: 0.7;
    background: rgba(107, 114, 128, 0.1);
}

.notification-info {
    flex: 1;
}

.notification-mac {
    color: var(--accent);
    font-weight: 600;
    font-family: 'Courier New', monospace;
    font-size: 14px;
}

.notification-title {
    color: var(--text-primary);
    font-weight: 500;
    margin: 5px 0;
    font-size: 16px;
}

.notification-content {
    color: var(--text-secondary);
    font-size: 13px;
    margin: 5px 0;
    line-height: 1.5;
}

.notification-date {
    color: var(--text-muted);
    font-size: 11px;
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

/* Status indicator */
.status-indicator {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-active {
    background: rgba(0, 255, 136, 0.1);
    color: var(--accent);
    border: 1px solid var(--accent);
}

.status-inactive {
    background: rgba(255, 165, 2, 0.1);
    color: var(--warning);
    border: 1px solid var(--warning);
}

/* Botões */
.futuristic-btn {
    padding: 12px 25px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    border: none;
    text-decoration: none;
    font-size: 14px;
}

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

.futuristic-btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 212, 255, 0.4);
}

.futuristic-btn-success {
    background: linear-gradient(135deg, var(--accent), #00CC7A);
    color: white;
    padding: 8px 15px;
}

.futuristic-btn-success:hover {
    background: linear-gradient(135deg, #00CC7A, var(--accent));
}

.futuristic-btn-warning {
    background: linear-gradient(135deg, var(--warning), #FF8C00);
    color: white;
    padding: 8px 15px;
}

.futuristic-btn-warning:hover {
    background: linear-gradient(135deg, #FF8C00, var(--warning));
}

.futuristic-btn-danger {
    background: linear-gradient(135deg, var(--error), #ff2e43);
    color: white;
    padding: 8px 15px;
    font-size: 13px;
}

.futuristic-btn-danger:hover {
    background: linear-gradient(135deg, #ff2e43, var(--error));
}

.futuristic-btn-sm {
    padding: 6px 12px;
    font-size: 12px;
    gap: 5px;
}

/* Inputs */
.futuristic-input {
    width: 100%;
    padding: 12px 15px;
    background: rgba(10, 15, 28, 0.6);
    border: 1px solid var(--border);
    border-radius: 10px;
    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);
}

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

/* Mensagens */
.success-message {
    background: rgba(0, 208, 132, 0.1);
    border: 1px solid var(--success);
    color: var(--success);
    padding: 15px;
    border-radius: 10px;
    margin-bottom: 20px;
}

.error-message {
    background: rgba(255, 71, 87, 0.1);
    border: 1px solid var(--error);
    color: var(--error);
    padding: 15px;
    border-radius: 10px;
    margin-bottom: 20px;
}

/* Estatísticas */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: rgba(10, 15, 28, 0.6);
    border-radius: 15px;
    padding: 20px;
    text-align: center;
    border: 1px solid var(--border);
}

.stat-number {
    font-size: 32px;
    font-weight: 700;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 5px;
}

.stat-label {
    color: var(--text-secondary);
    font-size: 14px;
}

/* Extra column style */
.extra-column {
    color: var(--primary);
    font-weight: 500;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.empty-message {
    text-align: center;
    padding: 40px;
    color: var(--text-muted);
}

.empty-message i {
    font-size: 48px;
    margin-bottom: 20px;
    opacity: 0.5;
}

/* Checkbox opção */
.option-checkbox {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 15px 0;
}

.option-checkbox input[type="checkbox"] {
    width: 18px;
    height: 18px;
    accent-color: var(--primary);
}

.option-checkbox label {
    color: var(--text-secondary);
    cursor: pointer;
}

/* Actions column in table */
.actions-column {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
}
</style>

<div class="futuristic-container">
    <h1 class="futuristic-title">Notificações Individuais</h1>
    <p class="futuristic-subtitle">Envie notificações específicas para cada cliente</p>
    
    <!-- Estatísticas -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-number"><?php echo count($clients); ?></div>
            <div class="stat-label">Clientes Cadastrados</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo count($existing_notifications); ?></div>
            <div class="stat-label">Notificações Criadas</div>
        </div>
        <div class="stat-card">
            <div class="stat-number">
                <?php 
                    $active_count = 0;
                    foreach ($existing_notifications as $notification) {
                        if ($notification['enabled']) $active_count++;
                    }
                    echo $active_count;
                ?>
            </div>
            <div class="stat-label">Notificações Ativas</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $json_dir; ?></div>
            <div class="stat-label">Pasta de JSONs</div>
        </div>
    </div>
    
    <!-- Mensagens de sucesso/erro -->
    <?php if (isset($success)): ?>
        <div class="success-message">
            <i class="fas fa-check-circle"></i> <?php echo $success; ?>
            <button type="button" class="close-message" style="float: right; background: none; border: none; color: var(--success); cursor: pointer;">×</button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($error)): ?>
        <div class="error-message">
            <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            <button type="button" class="close-message" style="float: right; background: none; border: none; color: var(--error); cursor: pointer;">×</button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($bulk_message)): ?>
        <div class="success-message">
            <i class="fas fa-check-circle"></i> <?php echo $bulk_message; ?>
            <button type="button" class="close-message" style="float: right; background: none; border: none; color: var(--success); cursor: pointer;">×</button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($bulk_error)): ?>
        <div class="error-message">
            <i class="fas fa-exclamation-circle"></i> <?php echo $bulk_error; ?>
            <button type="button" class="close-message" style="float: right; background: none; border: none; color: var(--error); cursor: pointer;">×</button>
        </div>
    <?php endif; ?>
    
    <div class="two-column-form">
        <!-- Formulário Individual -->
        <div class="form-section">
            <h3 class="section-title">
                <i class="fas fa-user"></i>
                Notificação Individual
            </h3>
            
            <form method="post">
                <div style="margin-bottom: 20px;">
                    <label style="color: var(--text-primary); display: block; margin-bottom: 8px;">
                        <i class="fas fa-network-wired"></i> MAC Address
                    </label>
                    <select name="mac_address" class="futuristic-input" required style="width: 100%;">
                        <option value="">Selecione um cliente pelo MAC</option>
                        <?php foreach ($clients as $client): ?>
                            <option value="<?php echo htmlspecialchars($client['mac_address']); ?>" 
                            data-expire-date="<?php echo htmlspecialchars($client['expire_date']); ?>">
                                <?php echo htmlspecialchars($client['mac_address']); ?>
                                <?php if (!empty($client['extra'])): ?>
                                    - <?php echo htmlspecialchars($client['extra']); ?>
                                <?php endif; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label style="color: var(--text-primary); display: block; margin-bottom: 8px;">
                        <i class="fas fa-heading"></i> Título
                    </label>
                    <input type="text" name="title" class="futuristic-input" placeholder="Título da notificação" required>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label style="color: var(--text-primary); display: block; margin-bottom: 8px;">
                        <i class="fas fa-comment-alt"></i> Mensagem
                    </label>
                    <textarea name="content" class="futuristic-input" rows="4" placeholder="Mensagem da notificação" required></textarea>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label style="color: var(--text-primary); display: block; margin-bottom: 8px;">
                        <i class="fas fa-calendar"></i> Data Referência (opcional)
                    </label>
                    <input type="date" name="expire_date" class="futuristic-input">
                </div>
                
                <button type="submit" name="send_individual" class="futuristic-btn futuristic-btn-primary">
                    <i class="fas fa-paper-plane"></i> Enviar Notificação Individual
                </button>
            </form>
        </div>
        
        <!-- Formulário em Massa -->
        <div class="form-section">
            <h3 class="section-title">
                <i class="fas fa-users"></i>
                Notificação em Massa
            </h3>
            
            <form method="post">
                <div style="margin-bottom: 20px;">
                    <label style="color: var(--text-primary); display: block; margin-bottom: 8px;">
                        <i class="fas fa-heading"></i> Título (para todos)
                    </label>
                    <input type="text" name="bulk_title" class="futuristic-input" placeholder="Título para todos" required>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <label style="color: var(--text-primary); display: block; margin-bottom: 8px;">
                        <i class="fas fa-comment-alt"></i> Mensagem (para todos)
                    </label>
                    <textarea name="bulk_content" class="futuristic-input" rows="4" placeholder="Mensagem para todos" required></textarea>
                </div>
                
                <div class="option-checkbox">
                    <input type="checkbox" id="enabled_by_default" name="enabled_by_default" checked>
                    <label for="enabled_by_default">Notificações ativas por padrão</label>
                </div>
                
                <div style="margin-bottom: 20px; max-height: 300px; overflow-y: auto; padding: 10px; background: rgba(0,0,0,0.2); border-radius: 8px;">
                    <div style="color: var(--text-primary); margin-bottom: 10px;">
                        <i class="fas fa-check-circle"></i> Selecione os clientes:
                    </div>
                    
                    <div style="margin-bottom: 10px;">
                        <label class="client-checkbox">
                            <input type="checkbox" id="selectAll">
                            <span style="color: var(--accent); font-weight: 600;">Selecionar Todos</span>
                        </label>
                    </div>
                    
                    <?php foreach ($clients as $client): ?>
                        <label class="client-checkbox">
                            <input type="checkbox" name="selected_clients[]" value="<?php echo htmlspecialchars($client['mac_address']); ?>">
                            <span>
                                <span class="notification-mac"><?php echo htmlspecialchars($client['mac_address']); ?></span>
                                <?php if (!empty($client['extra'])): ?>
                                    <span style="color: var(--primary); margin-left: 5px;">
                                        (<?php echo htmlspecialchars($client['extra']); ?>)
                                    </span>
                                <?php endif; ?>
                            </span>
                        </label>
                    <?php endforeach; ?>
                </div>
                
                <button type="submit" name="send_bulk" class="futuristic-btn futuristic-btn-primary">
                    <i class="fas fa-broadcast-tower"></i> Enviar para Selecionados
                </button>
            </form>
        </div>
    </div>
    
    <!-- Notificações Existentes - SEM BOTÕES -->
    <div class="futuristic-card">
        <h3 class="section-title">
            <i class="fas fa-history"></i>
            Notificações Enviadas (<?php echo count($existing_notifications); ?>)
        </h3>
        
        <?php if (empty($existing_notifications)): ?>
            <div class="empty-message">
                <i class="fas fa-inbox"></i>
                <p>Nenhuma notificação individual enviada ainda.</p>
            </div>
        <?php else: ?>
            <?php foreach ($existing_notifications as $notification): ?>
                <div class="notification-item <?php echo !$notification['enabled'] ? 'disabled' : ''; ?>">
                    <div class="notification-info">
                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                            <div class="notification-mac"><?php echo htmlspecialchars($notification['mac']); ?></div>
                            <span class="status-indicator <?php echo $notification['enabled'] ? 'status-active' : 'status-inactive'; ?>">
                                <i class="fas <?php echo $notification['enabled'] ? 'fa-bell' : 'fa-bell-slash'; ?>"></i>
                                <?php echo $notification['enabled'] ? 'Ativa' : 'Desativada'; ?>
                            </span>
                        </div>
                        <div class="notification-title"><?php echo htmlspecialchars($notification['title']); ?></div>
                        <div class="notification-content"><?php echo htmlspecialchars($notification['content']); ?></div>
                        <div class="notification-date">
                            <span><i class="fas fa-clock"></i> Criada: <?php echo htmlspecialchars($notification['created_at']); ?></span>
                            <?php if (!empty($notification['expire_date'])): ?>
                                <span><i class="fas fa-calendar"></i> Expira: <?php echo htmlspecialchars($notification['expire_date']); ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                    <!-- REMOVIDOS OS BOTÕES DAQUI -->
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <!-- Lista de Clientes - COM BOTÕES -->
    <div class="futuristic-card">
        <h3 class="section-title">
            <i class="fas fa-list"></i>
            Lista de Clientes (<?php echo count($clients); ?>)
        </h3>
        
        <?php if (empty($clients)): ?>
            <div class="empty-message">
                <i class="fas fa-database"></i>
                <p>Nenhum cliente encontrado no banco de dados.</p>
            </div>
        <?php else: ?>
            <div class="client-table-container">
                <table class="client-table">
                    <thead>
                        <tr>
                            <th width="40">#</th>
                            <th>MAC Address</th>
                            <th>Extra (Descrição)</th>
                            <th>Usuário</th>
                            <th>Expiração</th>
                            <th>Status Notif.</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($clients as $index => $client): ?>
                            <?php 
                                $status_file = str_replace([':', '/', '\\', '?', '*', '"', '<', '>', '|'], '_', strtolower($client['mac_address'])) . '.json';
                                $has_notification = file_exists($json_dir . $status_file);
                                $notification_enabled = false;
                                
                                if ($has_notification) {
                                    $content = @file_get_contents($json_dir . $status_file);
                                    $data = @json_decode($content, true);
                                    $notification_enabled = isset($data['enabled']) ? (bool)$data['enabled'] : true;
                                }
                            ?>
                            <tr>
                                <td><?php echo $index + 1; ?></td>
                                <td class="mac-cell"><?php echo htmlspecialchars($client['mac_address']); ?></td>
                                <td class="extra-column" title="<?php echo htmlspecialchars($client['extra']); ?>">
                                    <?php 
                                        if (!empty($client['extra'])) {
                                            echo htmlspecialchars($client['extra']);
                                        } else {
                                            echo '<span style="color: var(--text-muted); font-style: italic;">Nenhum</span>';
                                        }
                                    ?>
                                </td>
                                <td><?php echo htmlspecialchars($client['username']); ?></td>
                                <td>
                                    <?php 
                                        if (!empty($client['expire_date'])) {
                                            // Tentar formatar a data
                                            $date = $client['expire_date'];
                                            if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $date, $matches)) {
                                                echo $matches[3] . '/' . $matches[2] . '/' . $matches[1];
                                            } else {
                                                echo htmlspecialchars($date);
                                            }
                                        } else {
                                            echo '<span style="color: var(--text-muted);">N/A</span>';
                                        }
                                    ?>
                                </td>
                                <td>
                                    <?php if ($has_notification): ?>
                                        <?php if ($notification_enabled): ?>
                                            <span class="status-indicator status-active" style="font-size: 11px; padding: 3px 8px;">
                                                <i class="fas fa-bell"></i> Ativa
                                            </span>
                                        <?php else: ?>
                                            <span class="status-indicator status-inactive" style="font-size: 11px; padding: 3px 8px;">
                                                <i class="fas fa-bell-slash"></i> Inativa
                                            </span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span style="color: var(--text-muted); font-size: 12px;">
                                            <i class="far fa-bell"></i> Nenhuma
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="actions-column">
                                        <?php if ($has_notification): ?>
                                            <?php if ($notification_enabled): ?>
                                                <a href="note_individual.php?toggle_notification=<?php echo urlencode($client['mac_address']); ?>&action=disable" 
                                                   class="futuristic-btn futuristic-btn-warning futuristic-btn-sm"
                                                   title="Desativar notificação">
                                                    <i class="fas fa-toggle-off"></i>
                                                </a>
                                            <?php else: ?>
                                                <a href="note_individual.php?toggle_notification=<?php echo urlencode($client['mac_address']); ?>&action=enable" 
                                                   class="futuristic-btn futuristic-btn-success futuristic-btn-sm"
                                                   title="Ativar notificação">
                                                    <i class="fas fa-toggle-on"></i>
                                                </a>
                                            <?php endif; ?>
                                            
                                            <form method="post" style="display: inline;">
                                                <input type="hidden" name="delete_file" value="<?php echo htmlspecialchars(basename($status_file)); ?>">
                                                <button type="submit" class="futuristic-btn futuristic-btn-danger futuristic-btn-sm" 
                                                        onclick="return confirm('Excluir notificação para <?php echo htmlspecialchars($client['mac_address']); ?>?')"
                                                        title="Excluir notificação">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <span style="color: var(--text-muted); font-size: 11px;">N/A</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Selecionar todos os checkboxes
    const selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('input[name="selected_clients[]"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
    
    // Confirmar envio em massa
    const bulkForm = document.querySelector('form[name="send_bulk"]');
    if (bulkForm) {
        bulkForm.addEventListener('submit', function(e) {
            const selected = document.querySelectorAll('input[name="selected_clients[]"]:checked');
            if (selected.length === 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Nenhum cliente selecionado',
                    text: 'Selecione pelo menos um cliente para enviar a notificação.',
                    confirmButtonColor: '#00D4FF'
                });
            }
        });
    }
    
    // SweetAlert para ações
    const deleteButtons = document.querySelectorAll('.futuristic-btn-danger');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            if (!confirm('Tem certeza que deseja excluir esta notificação?')) {
                e.preventDefault();
            }
        });
    });
    
    // Corrigir links de ativar/desativar para manter na mesma página
    const toggleLinks = document.querySelectorAll('a[href*="toggle_notification"]');
    toggleLinks.forEach(link => {
        const href = link.getAttribute('href');
        // Garantir que o link aponte para o arquivo atual
        if (!href.includes('note_individual.php')) {
            link.setAttribute('href', 'note_individual.php' + href);
        }
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Função para esconder mensagens após 3 segundos
    function hideMessagesAfterDelay() {
        const successMessages = document.querySelectorAll('.success-message');
        const errorMessages = document.querySelectorAll('.error-message');
        
        // Esconder mensagens de sucesso após 3 segundos
        successMessages.forEach(message => {
            setTimeout(() => {
                message.style.transition = 'opacity 0.5s ease';
                message.style.opacity = '0';
                
                setTimeout(() => {
                    message.style.display = 'none';
                }, 500);
            }, 3000); // 3 segundos
        });
        
        // Esconder mensagens de erro após 5 segundos
        errorMessages.forEach(message => {
            setTimeout(() => {
                message.style.transition = 'opacity 0.5s ease';
                message.style.opacity = '0';
                
                setTimeout(() => {
                    message.style.display = 'none';
                }, 500);
            }, 5000); // 5 segundos para erro
        });
    }
    
    // Chamar a função quando a página carregar
    hideMessagesAfterDelay();
    
    // Opcional: Botão para fechar manualmente
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('close-message')) {
            const message = e.target.closest('.success-message, .error-message');
            if (message) {
                message.style.transition = 'opacity 0.3s ease';
                message.style.opacity = '0';
                
                setTimeout(() => {
                    message.style.display = 'none';
                }, 300);
            }
        }
    });
});
</script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const macSelect = document.querySelector('select[name="mac_address"]');
    const expireDateInput = document.querySelector('input[name="expire_date"]');

    if (macSelect && expireDateInput) {
        macSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const expireDate = selectedOption.getAttribute('data-expire-date');
            
            if (expireDate) {
                // O valor do banco de dados pode vir com timestamp (ex: 2025-12-16T03:12:50.000000Z)
                // O campo input[type="date"] só aceita o formato YYYY-MM-DD
                const cleanDate = expireDate.split('T')[0]; 
                expireDateInput.value = cleanDate;
            } else {
                // Limpa o campo se não houver data de expiração
                expireDateInput.value = '';
            }
        });
    }
});
</script>

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