<?php
// admin/maintenance.php - Script de manutenção dos dados de visitantes únicos

// Define BASE_PATH apenas se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

$pageTitle = 'Manutenção do Sistema';
$pageHeader = 'Manutenção do Sistema';
$currentPage = 'maintenance';

require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/visitor-tracking.php';

// Requer autenticação de administrador
$auth->requireAuth();

if (!isset($_SESSION['admin_role']) || $_SESSION['admin_role'] !== 'admin') {
    setAlert('Acesso negado. Apenas administradores podem acessar esta área.', ALERT_ERROR);
    redirect('admin/index.php');
    exit;
}

$maintenanceResults = [];
$errors = [];

// Processamento de ações de manutenção
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    try {
        switch ($action) {
            case 'clean_old_data':
                $daysToKeep = isset($_POST['days_to_keep']) ? intval($_POST['days_to_keep']) : 90;
                if ($daysToKeep < 7) {
                    throw new Exception('Mínimo de 7 dias deve ser mantido.');
                }
                
                $result = $visitorTracking->cleanOldVisitorData($daysToKeep);
                if ($result) {
                    $maintenanceResults[] = [
                        'type' => 'success',
                        'title' => 'Limpeza de Dados Concluída',
                        'message' => "Removidos {$result['unique_visitors_deleted']} registros de visitantes únicos e {$result['page_views_deleted']} visualizações de página."
                    ];
                } else {
                    throw new Exception('Erro durante a limpeza de dados.');
                }
                break;
                
            case 'optimize_database':
                // Otimizar tabelas do banco de dados
                $tables = ['unique_page_visitors', 'page_views', 'page_actions', 'page_engagement'];
                $optimized = 0;
                
                foreach ($tables as $table) {
                    try {
                        $db->query("OPTIMIZE TABLE {$table}");
                        $db->execute();
                        $optimized++;
                    } catch (Exception $e) {
                        logError("Erro ao otimizar tabela {$table}: " . $e->getMessage());
                    }
                }
                
                $maintenanceResults[] = [
                    'type' => 'success',
                    'title' => 'Otimização do Banco de Dados',
                    'message' => "Otimizadas {$optimized} de " . count($tables) . " tabelas."
                ];
                break;
                
            case 'recalculate_stats':
                // Recalcular estatísticas agregadas
                $db->query("SELECT COUNT(DISTINCT visitor_hash) as total_unique FROM unique_page_visitors");
                $totalUnique = $db->single();
                
                $db->query("SELECT COUNT(*) as total_views FROM page_views");
                $totalViews = $db->single();
                
                $maintenanceResults[] = [
                    'type' => 'info',
                    'title' => 'Estatísticas Recalculadas',
                    'message' => "Total de visitantes únicos: " . number_format($totalUnique['total_unique']) . 
                                " | Total de visualizações: " . number_format($totalViews['total_views'])
                ];
                break;
                
            case 'backup_data':
                // Criar backup dos dados de visitantes únicos
                $backupDir = BASE_PATH . '/backups';
                if (!file_exists($backupDir)) {
                    mkdir($backupDir, 0755, true);
                }
                
                $backupFile = $backupDir . '/visitor_data_backup_' . date('Y-m-d_H-i-s') . '.sql';
                
                $tables = ['unique_page_visitors', 'page_views', 'page_actions', 'page_engagement'];
                $backup = '';
                
                foreach ($tables as $table) {
                    $backup .= "-- Backup da tabela {$table}\n";
                    $backup .= "DROP TABLE IF EXISTS {$table}_backup;\n";
                    $backup .= "CREATE TABLE {$table}_backup AS SELECT * FROM {$table};\n\n";
                }
                
                if (file_put_contents($backupFile, $backup)) {
                    $maintenanceResults[] = [
                        'type' => 'success',
                        'title' => 'Backup Criado',
                        'message' => "Backup salvo em: " . basename($backupFile)
                    ];
                } else {
                    throw new Exception('Erro ao criar arquivo de backup.');
                }
                break;
                
            case 'analyze_performance':
                // Analisar performance das consultas
                $performanceData = [];
                
                // Verificar tamanho das tabelas
                $db->query("SELECT 
                            table_name,
                            round(((data_length + index_length) / 1024 / 1024), 2) as 'size_mb',
                            table_rows
                            FROM information_schema.tables 
                            WHERE table_schema = :schema 
                            AND table_name IN ('unique_page_visitors', 'page_views', 'page_actions', 'page_engagement')");
                $db->bind(':schema', DB_NAME);
                $tableStats = $db->resultSet();
                
                $performanceData['table_stats'] = $tableStats;
                
                // Verificar índices
                $db->query("SHOW INDEX FROM unique_page_visitors");
                $indexes = $db->resultSet();
                $performanceData['indexes'] = count($indexes);
                
                $maintenanceResults[] = [
                    'type' => 'info',
                    'title' => 'Análise de Performance',
                    'message' => 'Dados de performance coletados.',
                    'data' => $performanceData
                ];
                break;
                
            default:
                throw new Exception('Ação de manutenção inválida.');
        }
        
    } catch (Exception $e) {
        $errors[] = $e->getMessage();
        logError("Erro na manutenção: " . $e->getMessage());
    }
}

// Obter estatísticas atuais do sistema
$systemStats = [];
try {
    // Tamanho atual das tabelas
    $db->query("SELECT 
                table_name as 'table',
                round(((data_length + index_length) / 1024 / 1024), 2) as 'size_mb',
                table_rows as 'rows'
                FROM information_schema.tables 
                WHERE table_schema = :schema 
                AND table_name IN ('unique_page_visitors', 'page_views', 'page_actions', 'page_engagement')
                ORDER BY (data_length + index_length) DESC");
    $db->bind(':schema', DB_NAME);
    $systemStats['tables'] = $db->resultSet();
    
    // Registros mais antigos
    $db->query("SELECT MIN(visit_date) as oldest_unique, MAX(visit_date) as newest_unique FROM unique_page_visitors");
    $uniqueRange = $db->single();
    
    $db->query("SELECT MIN(DATE(viewed_at)) as oldest_views, MAX(DATE(viewed_at)) as newest_views FROM page_views");
    $viewsRange = $db->single();
    
    $systemStats['date_ranges'] = [
        'unique' => $uniqueRange,
        'views' => $viewsRange
    ];
    
    // Contadores gerais
    $db->query("SELECT COUNT(DISTINCT visitor_hash) as unique_visitors FROM unique_page_visitors");
    $uniqueCount = $db->single();
    
    $db->query("SELECT COUNT(*) as total_views FROM page_views");
    $viewsCount = $db->single();
    
    $systemStats['counts'] = [
        'unique_visitors' => $uniqueCount['unique_visitors'],
        'total_views' => $viewsCount['total_views']
    ];
    
} catch (Exception $e) {
    logError("Erro ao obter estatísticas do sistema: " . $e->getMessage());
}

require_once 'inc/header.php';
?>

<div class="container-fluid px-4">
    <!-- Header -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-gradient-primary text-white">
                    <div class="row align-items-center">
                        <div class="col">
                            <h4 class="mb-0">
                                <i class="fas fa-tools me-2"></i>
                                Manutenção do Sistema de Rastreamento
                            </h4>
                            <p class="mb-0 opacity-75">Gerencie dados de visitantes únicos e otimize a performance</p>
                        </div>
                        <div class="col-auto">
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-database me-1"></i>
                                <?php echo number_format($systemStats['counts']['unique_visitors'] ?? 0); ?> visitantes únicos
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Alertas e Resultados -->
    <?php if (!empty($errors)): ?>
    <div class="row">
        <div class="col-12">
            <div class="alert alert-danger">
                <h5><i class="fas fa-exclamation-triangle me-2"></i>Erros Encontrados</h5>
                <ul class="mb-0">
                    <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php if (!empty($maintenanceResults)): ?>
    <div class="row">
        <div class="col-12">
            <?php foreach ($maintenanceResults as $result): ?>
            <div class="alert alert-<?php echo $result['type'] === 'success' ? 'success' : ($result['type'] === 'info' ? 'info' : 'warning'); ?>">
                <h6><i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($result['title']); ?></h6>
                <p class="mb-0"><?php echo htmlspecialchars($result['message']); ?></p>
                
                <?php if (isset($result['data']) && !empty($result['data'])): ?>
                <div class="mt-3">
                    <?php if (isset($result['data']['table_stats'])): ?>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Tabela</th>
                                    <th>Tamanho (MB)</th>
                                    <th>Registros</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($result['data']['table_stats'] as $table): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($table['table_name']); ?></td>
                                    <td><?php echo number_format($table['size_mb'], 2); ?> MB</td>
                                    <td><?php echo number_format($table['table_rows']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Estatísticas do Sistema -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-chart-bar me-2"></i>
                        Estatísticas das Tabelas
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($systemStats['tables'])): ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Tabela</th>
                                    <th class="text-end">Tamanho</th>
                                    <th class="text-end">Registros</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($systemStats['tables'] as $table): ?>
                                <tr>
                                    <td>
                                        <code><?php echo htmlspecialchars($table['table']); ?></code>
                                    </td>
                                    <td class="text-end">
                                        <span class="badge bg-<?php echo $table['size_mb'] > 100 ? 'warning' : ($table['size_mb'] > 50 ? 'info' : 'success'); ?>">
                                            <?php echo number_format($table['size_mb'], 2); ?> MB
                                        </span>
                                    </td>
                                    <td class="text-end">
                                        <?php echo number_format($table['rows']); ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php else: ?>
                    <p class="text-muted">Não foi possível obter estatísticas das tabelas.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card border-0 shadow-sm">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-calendar-alt me-2"></i>
                        Intervalos de Datas
                    </h5>
                </div>
                <div class="card-body">
                    <?php if (!empty($systemStats['date_ranges'])): ?>
                    <div class="row">
                        <div class="col-12 mb-3">
                            <h6>Visitantes Únicos</h6>
                            <p class="text-muted mb-1">
                                <i class="fas fa-calendar-day me-1"></i>
                                Primeiro: <?php echo $systemStats['date_ranges']['unique']['oldest_unique'] ? date('d/m/Y', strtotime($systemStats['date_ranges']['unique']['oldest_unique'])) : 'N/A'; ?>
                            </p>
                            <p class="text-muted">
                                <i class="fas fa-calendar-day me-1"></i>
                                Último: <?php echo $systemStats['date_ranges']['unique']['newest_unique'] ? date('d/m/Y', strtotime($systemStats['date_ranges']['unique']['newest_unique'])) : 'N/A'; ?>
                            </p>
                        </div>
                        
                        <div class="col-12">
                            <h6>Visualizações</h6>
                            <p class="text-muted mb-1">
                                <i class="fas fa-calendar-day me-1"></i>
                                Primeira: <?php echo $systemStats['date_ranges']['views']['oldest_views'] ? date('d/m/Y', strtotime($systemStats['date_ranges']['views']['oldest_views'])) : 'N/A'; ?>
                            </p>
                            <p class="text-muted">
                                <i class="fas fa-calendar-day me-1"></i>
                                Última: <?php echo $systemStats['date_ranges']['views']['newest_views'] ? date('d/m/Y', strtotime($systemStats['date_ranges']['views']['newest_views'])) : 'N/A'; ?>
                            </p>
                        </div>
                    </div>
                    <?php else: ?>
                    <p class="text-muted">Não foi possível obter intervalos de datas.</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Ações de Manutenção -->
    <div class="row">
        <div class="col-lg-6 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-broom me-2"></i>
                        Limpeza de Dados
                    </h5>
                </div>
                <div class="card-body">
                    <p class="text-muted">Remove dados antigos para otimizar o banco de dados.</p>
                    
                    <form method="post" onsubmit="return confirm('Tem certeza que deseja limpar os dados antigos? Esta ação não pode ser desfeita.');">
                        <input type="hidden" name="action" value="clean_old_data">
                        
                        <div class="mb-3">
                            <label for="days_to_keep" class="form-label">Manter dados dos últimos (dias)</label>
                            <select class="form-select" id="days_to_keep" name="days_to_keep">
                                <option value="30">30 dias</option>
                                <option value="60">60 dias</option>
                                <option value="90" selected>90 dias</option>
                                <option value="180">180 dias</option>
                                <option value="365">1 ano</option>
                            </select>
                            <div class="form-text">Dados mais antigos que este período serão removidos.</div>
                        </div>
                        
                        <button type="submit" class="btn btn-warning">
                            <i class="fas fa-broom me-2"></i>Limpar Dados Antigos
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-6 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-tachometer-alt me-2"></i>
                        Otimização
                    </h5>
                </div>
                <div class="card-body">
                    <p class="text-muted">Otimiza as tabelas do banco de dados para melhor performance.</p>
                    
                    <div class="d-grid gap-2">
                        <form method="post" class="d-inline">
                            <input type="hidden" name="action" value="optimize_database">
                            <button type="submit" class="btn btn-info w-100">
                                <i class="fas fa-rocket me-2"></i>Otimizar Banco de Dados
                            </button>
                        </form>
                        
                        <form method="post" class="d-inline">
                            <input type="hidden" name="action" value="recalculate_stats">
                            <button type="submit" class="btn btn-outline-info w-100">
                                <i class="fas fa-calculator me-2"></i>Recalcular Estatísticas
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-6 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-shield-alt me-2"></i>
                        Backup e Segurança
                    </h5>
                </div>
                <div class="card-body">
                    <p class="text-muted">Crie backups dos dados de rastreamento.</p>
                    
                    <form method="post">
                        <input type="hidden" name="action" value="backup_data">
                        <button type="submit" class="btn btn-success w-100">
                            <i class="fas fa-download me-2"></i>Criar Backup
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-6 mb-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-analytics me-2"></i>
                        Análise de Performance
                    </h5>
                </div>
                <div class="card-body">
                    <p class="text-muted">Analisa a performance do sistema de rastreamento.</p>
                    
                    <form method="post">
                        <input type="hidden" name="action" value="analyze_performance">
                        <button type="submit" class="btn btn-outline-primary w-100">
                            <i class="fas fa-chart-line me-2"></i>Analisar Performance
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Recomendações -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-lightbulb me-2"></i>
                        Recomendações de Manutenção
                    </h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <h6><i class="fas fa-clock me-1"></i> Frequência Recomendada</h6>
                            <ul class="list-unstyled">
                                <li><i class="fas fa-check text-success me-2"></i>Limpeza de dados: Mensal</li>
                                <li><i class="fas fa-check text-success me-2"></i>Otimização do banco: Semanal</li>
                                <li><i class="fas fa-check text-success me-2"></i>Backup: Diário</li>
                                <li><i class="fas fa-check text-success me-2"></i>Análise de performance: Mensal</li>
                            </ul>
                        </div>
                        
                        <div class="col-md-6">
                            <h6><i class="fas fa-exclamation-triangle me-1"></i> Alertas</h6>
                            <ul class="list-unstyled">
                                <?php 
                                $totalSize = 0;
                                if (!empty($systemStats['tables'])) {
                                    foreach ($systemStats['tables'] as $table) {
                                        $totalSize += $table['size_mb'];
                                    }
                                }
                                ?>
                                <?php if ($totalSize > 500): ?>
                                <li><i class="fas fa-exclamation-triangle text-warning me-2"></i>Banco de dados grande (<?php echo number_format($totalSize, 2); ?> MB)</li>
                                <?php endif; ?>
                                
                                <?php if (!empty($systemStats['date_ranges']['unique']['oldest_unique']) && strtotime($systemStats['date_ranges']['unique']['oldest_unique']) < strtotime('-180 days')): ?>
                                <li><i class="fas fa-calendar-times text-info me-2"></i>Dados antigos detectados (>180 dias)</li>
                                <?php endif; ?>
                                
                                <?php if (empty($systemStats['counts']['unique_visitors']) || $systemStats['counts']['unique_visitors'] == 0): ?>
                                <li><i class="fas fa-info-circle text-info me-2"></i>Nenhum visitante único registrado</li>
                                <?php endif; ?>
                                
                                <?php if ($totalSize == 0 && empty($maintenanceResults)): ?>
                                <li><i class="fas fa-check-circle text-success me-2"></i>Sistema funcionando normalmente</li>
                                <?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card {
    border-radius: 0.75rem;
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15) !important;
}

.btn {
    border-radius: 0.5rem;
    font-weight: 500;
    transition: all 0.3s ease;
}

.btn:hover {
    transform: translateY(-1px);
}

.table th {
    border-top: none;
    font-weight: 600;
    font-size: 0.875rem;
    color: #495057;
}

.badge {
    font-size: 0.75rem;
    font-weight: 500;
}

code {
    background: #f8f9fa;
    padding: 2px 6px;
    border-radius: 4px;
    font-size: 0.875rem;
}

.alert {
    border-radius: 0.75rem;
    border: none;
}

.form-control, .form-select {
    border-radius: 0.5rem;
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
}

.form-control:focus, .form-select:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Adicionar confirmação para ações destrutivas
    document.querySelectorAll('form').forEach(form => {
        const action = form.querySelector('input[name="action"]').value;
        
        if (['clean_old_data', 'optimize_database'].includes(action)) {
            form.addEventListener('submit', function(e) {
                const actionNames = {
                    'clean_old_data': 'limpar dados antigos',
                    'optimize_database': 'otimizar o banco de dados'
                };
                
                if (!confirm(`Tem certeza que deseja ${actionNames[action]}? Esta operação pode demorar alguns minutos.`)) {
                    e.preventDefault();
                }
            });
        }
    });
    
    // Auto-refresh da página a cada 30 segundos se houver operações em andamento
    if (document.querySelector('.alert-info')) {
        setTimeout(() => {
            if (confirm('Atualizar a página para verificar o status das operações?')) {
                location.reload();
            }
        }, 30000);
    }
});
</script>

<?php require_once 'inc/footer.php'; ?>