<?php
// admin/ajax/get-visitors-chart-data.php

require_once '../../includes/config.php';
require_once '../../includes/db.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Verifica autenticação
if (!$auth->isLoggedIn()) {
    http_response_code(403);
    echo json_encode(['error' => 'Acesso negado']);
    exit;
}

// Recebe parâmetros
$period = $_POST['period'] ?? '7d';
$dateFrom = $_POST['date_from'] ?? date('Y-m-d', strtotime('-7 days'));
$dateTo = $_POST['date_to'] ?? date('Y-m-d');

try {
    $labels = [];
    $visitors = [];
    
    // Determina o número de dias baseado no período
    $days = match($period) {
        '24h' => 1,
        '7d' => 7,
        '30d' => 30,
        'custom' => (strtotime($dateTo) - strtotime($dateFrom)) / (60 * 60 * 24) + 1,
        default => 7
    };
    
    // Limita o número máximo de dias para performance
    $days = min($days, 30);
    
    if ($period === 'custom') {
        // Para período customizado, usa as datas fornecidas
        $startDate = new DateTime($dateFrom);
        $endDate = new DateTime($dateTo);
        $interval = new DateInterval('P1D');
        $dateRange = new DatePeriod($startDate, $interval, $endDate->modify('+1 day'));
        
        foreach ($dateRange as $date) {
            $dateStr = $date->format('Y-m-d');
            $labels[] = $date->format('d/m');
            
            // Busca visitantes únicos para esta data
            $db->query("
                SELECT COUNT(DISTINCT visitor_hash) as count
                FROM visitor_sessions 
                WHERE DATE(created_at) = :date
            ");
            $db->bind(':date', $dateStr);
            $result = $db->single();
            
            $visitors[] = intval($result['count'] ?? 0);
        }
    } else {
        // Para períodos predefinidos
        for ($i = $days - 1; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $labels[] = date('d/m', strtotime("-{$i} days"));
            
            // Determina o intervalo de tempo
            $timeCondition = match($period) {
                '24h' => "created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)",
                '7d' => "DATE(created_at) = '{$date}'",
                '30d' => "DATE(created_at) = '{$date}'",
                default => "DATE(created_at) = '{$date}'"
            };
            
            if ($period === '24h') {
                // Para 24h, divide em horas
                $hour = 24 - $i;
                $timeCondition = "created_at >= DATE_SUB(NOW(), INTERVAL {$hour} HOUR) 
                                AND created_at < DATE_SUB(NOW(), INTERVAL " . ($hour - 1) . " HOUR)";
                $labels[$days - 1 - $i] = ($hour < 24) ? sprintf('%02d:00', $hour) : 'Agora';
            }
            
            // Busca visitantes únicos
            $db->query("
                SELECT COUNT(DISTINCT visitor_hash) as count
                FROM visitor_sessions 
                WHERE {$timeCondition}
            ");
            
            $result = $db->single();
            $visitors[] = intval($result['count'] ?? 0);
        }
    }
    
    // Adiciona dados de tendência
    $totalVisitors = array_sum($visitors);
    $avgVisitors = $totalVisitors > 0 ? round($totalVisitors / count($visitors), 2) : 0;
    
    // Calcula crescimento (compara primeira metade com segunda metade)
    $firstHalf = array_slice($visitors, 0, floor(count($visitors) / 2));
    $secondHalf = array_slice($visitors, floor(count($visitors) / 2));
    
    $firstHalfAvg = count($firstHalf) > 0 ? array_sum($firstHalf) / count($firstHalf) : 0;
    $secondHalfAvg = count($secondHalf) > 0 ? array_sum($secondHalf) / count($secondHalf) : 0;
    
    $growth = 0;
    if ($firstHalfAvg > 0) {
        $growth = round((($secondHalfAvg - $firstHalfAvg) / $firstHalfAvg) * 100, 2);
    }
    
    // Retorna dados em formato JSON
    $response = [
        'labels' => $labels,
        'visitors' => $visitors,
        'total' => $totalVisitors,
        'average' => $avgVisitors,
        'growth' => $growth,
        'period' => $period,
        'success' => true
    ];
    
    header('Content-Type: application/json');
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("Erro ao gerar dados do gráfico: " . $e->getMessage());
    
    // Retorna dados de fallback em caso de erro
    $fallbackLabels = [];
    $fallbackVisitors = [];
    
    $days = match($period) {
        '24h' => 24,
        '7d' => 7,
        '30d' => 30,
        default => 7
    };
    
    for ($i = $days - 1; $i >= 0; $i--) {
        if ($period === '24h') {
            $fallbackLabels[] = sprintf('%02d:00', 24 - $i);
        } else {
            $fallbackLabels[] = date('d/m', strtotime("-{$i} days"));
        }
        $fallbackVisitors[] = rand(5, 50);
    }
    
    $response = [
        'labels' => $fallbackLabels,
        'visitors' => $fallbackVisitors,
        'total' => array_sum($fallbackVisitors),
        'average' => round(array_sum($fallbackVisitors) / count($fallbackVisitors), 2),
        'growth' => 0,
        'period' => $period,
        'success' => false,
        'error' => 'Dados de fallback - ' . $e->getMessage()
    ];
    
    header('Content-Type: application/json');
    echo json_encode($response);
}
?>