<?php
// admin/pixel-events-ajax.php

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

header('Content-Type: application/json');

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(401);
    echo json_encode(['error' => 'Não autorizado']);
    exit;
}

$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'recent':
            handleRecentEvents();
            break;
            
        case 'export':
            handleExport();
            break;
            
        case 'stats':
            handleStats();
            break;
            
        default:
            throw new Exception('Ação não reconhecida');
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}

function handleRecentEvents() {
    global $db;
    
    $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-7 days'));
    $endDate = $_GET['end_date'] ?? date('Y-m-d');
    $campaign = $_GET['campaign'] ?? '';
    $limit = $_GET['limit'] ?? 50;
    
    $whereClause = "WHERE pe.created_at BETWEEN :start_date AND :end_date";
    $params = [
        ':start_date' => $startDate . ' 00:00:00',
        ':end_date' => $endDate . ' 23:59:59'
    ];
    
    if (!empty($campaign)) {
        $whereClause .= " AND pe.utm_campaign = :campaign";
        $params[':campaign'] = $campaign;
    }
    
    $sql = "SELECT 
                pe.*,
                p.title as page_title,
                p.slug as page_slug
            FROM pixel_events pe
            LEFT JOIN pages p ON pe.page_id = p.id
            {$whereClause}
            ORDER BY pe.created_at DESC
            LIMIT :limit";
    
    $db->query($sql);
    
    foreach ($params as $key => $value) {
        $db->bind($key, $value);
    }
    $db->bind(':limit', (int)$limit, PDO::PARAM_INT);
    
    $events = $db->resultSet();
    
    echo json_encode(['events' => $events]);
}

function handleExport() {
    global $db;
    
    $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
    $endDate = $_GET['end_date'] ?? date('Y-m-d');
    $campaign = $_GET['campaign'] ?? '';
    
    $whereClause = "WHERE pe.created_at BETWEEN :start_date AND :end_date";
    $params = [
        ':start_date' => $startDate . ' 00:00:00',
        ':end_date' => $endDate . ' 23:59:59'
    ];
    
    if (!empty($campaign)) {
        $whereClause .= " AND pe.utm_campaign = :campaign";
        $params[':campaign'] = $campaign;
    }
    
    $sql = "SELECT 
                pe.created_at as 'Data/Hora',
                pe.utm_campaign as 'Campanha',
                pe.utm_source as 'Fonte',
                pe.utm_medium as 'Meio',
                pe.utm_term as 'Termo',
                pe.utm_content as 'Conteúdo',
                p.title as 'Página',
                pe.visitor_ip as 'IP',
                pe.user_agent as 'User Agent',
                pe.referrer as 'Referrer'
            FROM pixel_events pe
            LEFT JOIN pages p ON pe.page_id = p.id
            {$whereClause}
            ORDER BY pe.created_at DESC";
    
    $db->query($sql);
    
    foreach ($params as $key => $value) {
        $db->bind($key, $value);
    }
    
    $events = $db->resultSet();
    
    // Gera CSV
    $filename = 'pixel_events_' . $startDate . '_to_' . $endDate . '.csv';
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    $output = fopen('php://output', 'w');
    
    // BOM para UTF-8
    fwrite($output, "\xEF\xBB\xBF");
    
    if (!empty($events)) {
        // Headers
        fputcsv($output, array_keys($events[0]));
        
        // Dados
        foreach ($events as $event) {
            fputcsv($output, $event);
        }
    }
    
    fclose($output);
    exit;
}

function handleStats() {
    global $db;
    
    $startDate = $_GET['start_date'] ?? date('Y-m-d', strtotime('-7 days'));
    $endDate = $_GET['end_date'] ?? date('Y-m-d');
    
    // Estatísticas gerais
    $db->query("SELECT 
        COUNT(*) as total_events,
        COUNT(DISTINCT visitor_ip) as unique_visitors,
        COUNT(DISTINCT utm_campaign) as total_campaigns
        FROM pixel_events 
        WHERE created_at BETWEEN :start_date AND :end_date");
    
    $db->bind(':start_date', $startDate . ' 00:00:00');
    $db->bind(':end_date', $endDate . ' 23:59:59');
    
    $summary = $db->single();
    
    // Eventos por dia
    $db->query("SELECT 
        DATE(created_at) as date,
        COUNT(*) as events,
        COUNT(DISTINCT visitor_ip) as unique_visitors
        FROM pixel_events 
        WHERE created_at BETWEEN :start_date AND :end_date
        GROUP BY DATE(created_at)
        ORDER BY date");
    
    $db->bind(':start_date', $startDate . ' 00:00:00');
    $db->bind(':end_date', $endDate . ' 23:59:59');
    
    $dailyStats = $db->resultSet();
    
    // Top campanhas
    $db->query("SELECT 
        utm_campaign,
        COUNT(*) as events,
        COUNT(DISTINCT visitor_ip) as unique_visitors
        FROM pixel_events 
        WHERE created_at BETWEEN :start_date AND :end_date
        AND utm_campaign IS NOT NULL 
        AND utm_campaign != ''
        GROUP BY utm_campaign 
        ORDER BY events DESC 
        LIMIT 10");
    
    $db->bind(':start_date', $startDate . ' 00:00:00');
    $db->bind(':end_date', $endDate . ' 23:59:59');
    
    $topCampaigns = $db->resultSet();
    
    echo json_encode([
        'summary' => $summary,
        'daily_stats' => $dailyStats,
        'top_campaigns' => $topCampaigns
    ]);
}
?>