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

session_start();
if (!isset($_SESSION['eggzie_iboPlayer'])) {
    header('Location: login.php');
    exit();
}

error_reporting(0);

// Conexão com banco da API
function getAPIDB() {
    $db_path = __DIR__ . '/api/.adb.db';
    return new SQLite3($db_path);
}

// Limpar TODOS os registros antigos
function limparHistoricoCompleto() {
    $db = getAPIDB();
    
    // Contar registros antes de limpar
    $result = $db->query("SELECT COUNT(*) as total FROM connections");
    $row = $result->fetchArray();
    $total_antes = $row['total'] ?? 0;
    
    // Limpar TODA a tabela
    $db->exec("DELETE FROM connections");
    
    // Resetar o autoincrement (opcional)
    $db->exec("DELETE FROM sqlite_sequence WHERE name='connections'");
    
    // Vacuum para otimizar espaço
    $db->exec("VACUUM");
    
    return $total_antes;
}

// Limpar apenas registros ANTIGOS (anteriores a uma data)
function limparHistoricoAntigo($dias = 0, $horas = 0) {
    $db = getAPIDB();
    
    // Calcular limite de tempo
    $limite_segundos = ($dias * 86400) + ($horas * 3600);
    $limite_data = date('Y-m-d H:i:s', time() - $limite_segundos);
    
    // Contar registros antes de limpar
    $stmt = $db->prepare("SELECT COUNT(*) as total FROM connections WHERE last_seen < :limite");
    $stmt->bindValue(':limite', $limite_data, SQLITE3_TEXT);
    $result = $stmt->execute();
    $row = $result->fetchArray();
    $total_antes = $row['total'] ?? 0;
    
    // Limpar registros antigos
    $stmt = $db->prepare("DELETE FROM connections WHERE last_seen < :limite");
    $stmt->bindValue(':limite', $limite_data, SQLITE3_TEXT);
    $stmt->execute();
    
    // Vacuum para otimizar espaço
    $db->exec("VACUUM");
    
    return $total_antes;
}

// Executar ação se solicitado
$mensagem = '';
$tipo_mensagem = '';
if (isset($_GET['acao'])) {
    switch ($_GET['acao']) {
        case 'limpar_tudo':
            $total = limparHistoricoCompleto();
            $mensagem = "Histórico COMPLETAMENTE limpo! {$total} registros removidos.";
            $tipo_mensagem = 'success';
            break;
            
        case 'limpar_antigo':
            $total = limparHistoricoAntigo(1, 0); // Remove registros com mais de 1 dia
            $mensagem = "Histórico antigo limpo! {$total} registros antigos removidos.";
            $tipo_mensagem = 'warning';
            break;
            
        case 'limpar_agora':
            // Remove todos registros ANTES de agora
            $db = getAPIDB();
            $result = $db->query("SELECT COUNT(*) as total FROM connections");
            $row = $result->fetchArray();
            $total_antes = $row['total'] ?? 0;
            
            $db->exec("DELETE FROM connections");
            $db->exec("VACUUM");
            
            $mensagem = "Monitor reiniciado! {$total_antes} registros antigos removidos. O monitor começará do zero.";
            $tipo_mensagem = 'success';
            break;
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="google" content="notranslate">
    <title>Limpar Histórico - IBO Monitor</title>
    
    <!-- Material Icons -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons+Round" rel="stylesheet">
    
    <!-- Custom fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Custom styles futuristas -->
    <style>
        :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);
            --danger: #FF4757;
            --warning: #FFA502;
            --success: #00FF88;
            --info: #00D4FF;
            --glow: 0 0 20px rgba(0, 212, 255, 0.3);
            --glow-danger: 0 0 20px rgba(255, 71, 87, 0.3);
            --glow-success: 0 0 20px rgba(0, 255, 136, 0.3);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif !important;
            background: linear-gradient(135deg, #0A0F1C 0%, #151B2D 50%, #0A0F1C 100%) !important;
            color: var(--text-primary);
            min-height: 100vh;
            overflow-x: hidden;
        }
        
        /* Efeito de partículas */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: 
                radial-gradient(circle at 20% 80%, rgba(0, 212, 255, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 80% 20%, rgba(255, 107, 157, 0.1) 0%, transparent 50%),
                radial-gradient(circle at 40% 40%, rgba(0, 255, 136, 0.05) 0%, transparent 50%);
            pointer-events: none;
            z-index: -1;
        }
        
        /* Container principal */
        .limpar-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        
        /* Card principal */
        .limpar-card {
            background: rgba(26, 31, 44, 0.95);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border);
            border-radius: 20px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            position: relative;
            margin-bottom: 30px;
        }
        
        .limpar-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary), var(--accent), var(--primary));
        }
        
        /* Header do card */
        .limpar-header {
            padding: 30px 30px 20px;
            text-align: center;
            border-bottom: 1px solid var(--border);
            background: rgba(10, 15, 28, 0.5);
        }
        
        .limpar-title {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-bottom: 10px;
        }
        
        .limpar-title h1 {
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin: 0;
        }
        
        .limpar-title-icon {
            font-size: 36px;
            background: linear-gradient(135deg, var(--danger), #ff3838);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .limpar-subtitle {
            color: var(--text-secondary);
            font-size: 14px;
            font-weight: 400;
            margin: 0;
        }
        
        /* Corpo do card */
        .limpar-body {
            padding: 30px;
        }
        
        /* Alertas */
        .limpar-alert {
            background: rgba(255, 71, 87, 0.1);
            border: 1px solid rgba(255, 71, 87, 0.3);
            border-left: 4px solid var(--danger);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            animation: fadeIn 0.5s ease;
        }
        
        .limpar-alert.warning {
            background: rgba(255, 165, 2, 0.1);
            border: 1px solid rgba(255, 165, 2, 0.3);
            border-left: 4px solid var(--warning);
        }
        
        .limpar-alert.success {
            background: rgba(0, 255, 136, 0.1);
            border: 1px solid rgba(0, 255, 136, 0.3);
            border-left: 4px solid var(--success);
        }
        
        .limpar-alert.info {
            background: rgba(0, 212, 255, 0.1);
            border: 1px solid rgba(0, 212, 255, 0.3);
            border-left: 4px solid var(--info);
        }
        
        .limpar-alert-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        .limpar-alert-icon {
            font-size: 20px;
        }
        
        .limpar-alert.danger .limpar-alert-icon {
            color: var(--danger);
        }
        
        .limpar-alert.warning .limpar-alert-icon {
            color: var(--warning);
        }
        
        .limpar-alert.success .limpar-alert-icon {
            color: var(--success);
        }
        
        .limpar-alert h5 {
            font-size: 16px;
            font-weight: 600;
            margin: 0;
        }
        
        .limpar-alert p {
            font-size: 14px;
            color: var(--text-secondary);
            margin: 0;
            line-height: 1.5;
        }
        
        /* Grid de opções */
        .limpar-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        /* Card de opção */
        .limpar-option-card {
            background: var(--surface-lighter);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 25px;
            transition: all 0.3s ease;
            cursor: pointer;
            text-decoration: none;
            display: block;
            position: relative;
            overflow: hidden;
        }
        
        .limpar-option-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--glow);
            border-color: var(--primary);
        }
        
        .limpar-option-card.danger:hover {
            box-shadow: var(--glow-danger);
            border-color: var(--danger);
        }
        
        .limpar-option-card.success:hover {
            box-shadow: var(--glow-success);
            border-color: var(--success);
        }
        
        .limpar-option-card.warning:hover {
            box-shadow: 0 0 20px rgba(255, 165, 2, 0.3);
            border-color: var(--warning);
        }
        
        .limpar-option-header {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .limpar-option-icon {
            font-size: 32px;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 12px;
            background: linear-gradient(135deg, rgba(0, 212, 255, 0.1), rgba(0, 255, 136, 0.1));
        }
        
        .limpar-option-card.danger .limpar-option-icon {
            background: linear-gradient(135deg, rgba(255, 71, 87, 0.1), rgba(255, 107, 157, 0.1));
        }
        
        .limpar-option-card.success .limpar-option-icon {
            background: linear-gradient(135deg, rgba(0, 255, 136, 0.1), rgba(0, 212, 255, 0.1));
        }
        
        .limpar-option-card.warning .limpar-option-icon {
            background: linear-gradient(135deg, rgba(255, 165, 2, 0.1), rgba(255, 193, 7, 0.1));
        }
        
        .limpar-option-icon .material-icons-round {
            font-size: 28px;
        }
        
        .limpar-option-card.danger .limpar-option-icon .material-icons-round {
            background: linear-gradient(135deg, var(--danger), #ff3838);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .limpar-option-card.success .limpar-option-icon .material-icons-round {
            background: linear-gradient(135deg, var(--success), var(--primary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .limpar-option-card.warning .limpar-option-icon .material-icons-round {
            background: linear-gradient(135deg, var(--warning), #ffc107);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .limpar-option-title {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }
        
        .limpar-option-card.danger .limpar-option-title {
            color: var(--danger);
        }
        
        .limpar-option-card.success .limpar-option-title {
            color: var(--success);
        }
        
        .limpar-option-card.warning .limpar-option-title {
            color: var(--warning);
        }
        
        .limpar-option-description {
            font-size: 14px;
            color: var(--text-secondary);
            line-height: 1.5;
            margin-bottom: 20px;
        }
        
        /* Botão de ação */
        .limpar-action-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            padding: 12px 20px;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            text-decoration: none;
            text-align: center;
        }
        
        .limpar-action-btn.danger {
            background: linear-gradient(135deg, var(--danger), #ff3838);
            color: white;
        }
        
        .limpar-action-btn.success {
            background: linear-gradient(135deg, var(--success), var(--primary));
            color: #000;
        }
        
        .limpar-action-btn.warning {
            background: linear-gradient(135deg, var(--warning), #ffc107);
            color: #000;
        }
        
        .limpar-action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
        }
        
        .limpar-action-btn.danger:hover {
            box-shadow: 0 5px 20px rgba(255, 71, 87, 0.5);
        }
        
        .limpar-action-btn.success:hover {
            box-shadow: 0 5px 20px rgba(0, 255, 136, 0.5);
        }
        
        .limpar-action-btn.warning:hover {
            box-shadow: 0 5px 20px rgba(255, 165, 2, 0.5);
        }
        
        /* Opção única */
        .limpar-single-option {
            background: var(--surface-lighter);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 25px;
            margin-bottom: 25px;
        }
        
        /* Footer do card */
        .limpar-footer {
            padding: 20px 30px;
            border-top: 1px solid var(--border);
            text-align: center;
            background: rgba(10, 15, 28, 0.5);
        }
        
        .limpar-footer p {
            color: var(--text-muted);
            font-size: 12px;
            margin-bottom: 15px;
        }
        
        /* Botão voltar */
        .limpar-back-btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 25px;
            background: transparent;
            border: 1px solid var(--primary);
            border-radius: 12px;
            color: var(--primary);
            font-weight: 600;
            font-size: 14px;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        .limpar-back-btn:hover {
            background: rgba(0, 212, 255, 0.1);
            transform: translateY(-2px);
            box-shadow: var(--glow);
        }
        
        /* Animação */
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        /* Responsivo */
        @media (max-width: 768px) {
            .limpar-container {
                padding: 15px;
            }
            
            .limpar-grid {
                grid-template-columns: 1fr;
            }
            
            .limpar-header {
                padding: 20px 20px 15px;
            }
            
            .limpar-title h1 {
                font-size: 24px;
            }
            
            .limpar-body {
                padding: 20px;
            }
            
            .limpar-option-card {
                padding: 20px;
            }
            
            .limpar-option-icon {
                width: 50px;
                height: 50px;
                font-size: 24px;
            }
            
            .limpar-option-icon .material-icons-round {
                font-size: 24px;
            }
        }
        
        @media (max-width: 480px) {
            .limpar-title {
                flex-direction: column;
                gap: 10px;
            }
            
            .limpar-title h1 {
                font-size: 22px;
            }
            
            .limpar-subtitle {
                font-size: 12px;
            }
            
            .limpar-option-header {
                flex-direction: column;
                text-align: center;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/header.php' ?>
    <!-- Container principal -->
    <div class="limpar-container">
        <div class="limpar-card">
            <!-- Header -->
            <div class="limpar-header">
                <div class="limpar-title">
                    <span class="material-icons-round limpar-title-icon">delete_forever</span>
                    <h1>LIMPAR HISTÓRICO DO MONITOR</h1>
                </div>
                <p class="limpar-subtitle">Gerenciamento avançado de registros de conexão</p>
            </div>
            
            <!-- Body -->
            <div class="limpar-body">
                <!-- Alerta de atenção -->
                <div class="limpar-alert danger">
                    <div class="limpar-alert-header">
                        <span class="material-icons-round limpar-alert-icon">warning</span>
                        <h5>ATENÇÃO: AÇÃO IRREVERSÍVEL</h5>
                    </div>
                    
                </div>
                
                <!-- Mensagem de sucesso/erro -->
                <?php if (!empty($mensagem)): ?>
                    <div class="limpar-alert <?php echo $tipo_mensagem; ?>" style="animation: fadeIn 0.5s ease;">
                        <div class="limpar-alert-header">
                            <span class="material-icons-round limpar-alert-icon">
                                <?php 
                                if ($tipo_mensagem == 'success') echo 'check_circle';
                                elseif ($tipo_mensagem == 'warning') echo 'info';
                                else echo 'error';
                                ?>
                            </span>
                            <h5>
                                <?php 
                                if ($tipo_mensagem == 'success') echo '✅ AÇÃO CONCLUÍDA';
                                elseif ($tipo_mensagem == 'warning') echo '⚠️ AVISO';
                                else echo '❌ ERRO';
                                ?>
                            </h5>
                        </div>
                        <p><?php echo $mensagem; ?></p>
                    </div>
                <?php endif; ?>
                
                <!-- Grid de opções principais -->
                <div class="limpar-grid">
                    <!-- Opção 1: Limpar TUDO -->
                    <a href="?acao=limpar_tudo" 
                       class="limpar-option-card danger"
                       onclick="return confirmLimparTudo()">
                        <div class="limpar-option-header">
                            <div class="limpar-option-icon">
                                <span class="material-icons-round">delete_sweep</span>
                            </div>
                            <h3 class="limpar-option-title">LIMPAR TUDO</h3>
                        </div>
                        <p class="limpar-option-description">
                            Remove TODOS os registros de conexão permanentemente. 
                            Ideal para começar completamente do zero ou resolver problemas de dados.
                        </p>
                        <button class="limpar-action-btn danger">
                            <span class="material-icons-round">delete_forever</span>
                            LIMPAR COMPLETAMENTE
                        </button>
                    </a>
                    
                    <!-- Opção 2: Reiniciar Monitor -->
                    <a href="?acao=limpar_agora" 
                       class="limpar-option-card success"
                       onclick="return confirmReiniciar()">
                        <div class="limpar-option-header">
                            <div class="limpar-option-icon">
                                <span class="material-icons-round">restart_alt</span>
                            </div>
                            <h3 class="limpar-option-title">REINICIAR MONITOR</h3>
                        </div>
                        <p class="limpar-option-description">
                            Limpa histórico antigo e começa a monitorar apenas a partir de AGORA. 
                            Mantém dispositivos cadastrados, mas remove todos os pings anteriores.
                        </p>
                        <button class="limpar-action-btn success">
                            <span class="material-icons-round">play_circle</span>
                            COMEÇAR DO ZERO
                        </button>
                    </a>
                </div>
                
                <!-- Opção única: Limpar Antigo -->
                <div class="limpar-single-option">
                    <div class="limpar-option-header">
                        <div class="limpar-option-icon">
                            <span class="material-icons-round">history_toggle_off</span>
                        </div>
                        <h3 class="limpar-option-title">LIMPAR HISTÓRICO ANTIGO</h3>
                    </div>
                    <p class="limpar-option-description">
                        Remove apenas registros com mais de 1 dia. Ideal para manutenção regular 
                        sem afetar os dados recentes dos dispositivos.
                    </p>
                    <a href="?acao=limpar_antigo" 
                       class="limpar-action-btn warning"
                       onclick="return confirmLimparAntigo()">
                        <span class="material-icons-round">cleaning_services</span>
                        LIMPAR REGISTROS ANTIGOS
                    </a>
                </div>
            </div>
            
            <!-- Footer -->
            <div class="limpar-footer">
                <p>
                    <span class="material-icons-round" style="font-size: 14px; vertical-align: middle;">info</span>
                    Após limpar, aguarde os dispositivos se reconectarem para aparecerem novamente no monitor.
                </p>
                <a href="monitor.php" class="limpar-back-btn">
                    <span class="material-icons-round">arrow_back</span>
                    VOLTAR AO MONITOR
                </a>
            </div>
        </div>
    </div>
    
    <!-- Scripts -->
    <script>
        function confirmLimparTudo() {
            return confirm("🚨 LIMPEZA TOTAL\n\nTem ABSOLUTA certeza?\n\nIsso apagará TODOS os registros permanentemente!\n\nAção IRREVERSÍVEL!");
        }
        
        function confirmReiniciar() {
            return confirm("🔄 REINICIAR MONITOR\n\nReiniciar monitoramento?\n\nHistórico será limpo e começaremos do zero agora.\n\nOK para continuar?");
        }
        
        function confirmLimparAntigo() {
            return confirm("🧹 LIMPAR ANTIGO\n\nRemover registros com mais de 1 dia?\n\nIsso afetará apenas dados antigos.\n\nContinuar?");
        }
        
        // Auto-redirecionar após 5 segundos se houve ação
        <?php if (!empty($mensagem)): ?>
        setTimeout(function() {
            window.location.href = 'monitor.php';
        }, 5000);
        <?php endif; ?>
    </script>
</body>
</html>