<?php
/**
 * API pour récupérer les données analytics en temps réel
 * SERVICES-AE Analytics Real-time Data
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once 'config/config.php';
require_once 'config/db.php';

try {
    $action = $_GET['action'] ?? 'summary';
    
    switch ($action) {
        case 'summary':
            echo json_encode(getSummary());
            break;
        case 'recent_visits':
            echo json_encode(getRecentVisits());
            break;
        case 'recent_events':
            echo json_encode(getRecentEvents());
            break;
        case 'live_stats':
            echo json_encode(getLiveStats());
            break;
        default:
            throw new Exception('Action inconnue');
    }
    
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}

/**
 * Résumé des statistiques
 */
function getSummary() {
    $today = date('Y-m-d');
    
    // Statistiques du jour
    $todayStats = executeQuery("
        SELECT 
            COUNT(*) as total_visits,
            COUNT(DISTINCT visitor_ip) as unique_visitors,
            COUNT(DISTINCT session_id) as unique_sessions,
            AVG(CASE WHEN is_mobile = 1 THEN 1 ELSE 0 END) * 100 as mobile_percentage
        FROM site_analytics 
        WHERE DATE(visit_date) = ?
    ", [$today])->fetch();
    
    // Événements du jour
    $todayEvents = executeQuery("
        SELECT COUNT(*) as total_events
        FROM site_events 
        WHERE DATE(event_date) = ?
    ", [$today])->fetch();
    
    // Pages les plus visitées aujourd'hui
    $topPages = executeQuery("
        SELECT 
            page_url, 
            page_title,
            COUNT(*) as visits
        FROM site_analytics 
        WHERE DATE(visit_date) = ?
        GROUP BY page_url, page_title
        ORDER BY visits DESC
        LIMIT 5
    ", [$today])->fetchAll();
    
    // Navigateurs du jour
    $browsers = executeQuery("
        SELECT 
            browser,
            COUNT(*) as count
        FROM site_analytics 
        WHERE DATE(visit_date) = ? AND browser != ''
        GROUP BY browser
        ORDER BY count DESC
        LIMIT 5
    ", [$today])->fetchAll();
    
    return [
        'today_stats' => $todayStats,
        'today_events' => $todayEvents,
        'top_pages' => $topPages,
        'browsers' => $browsers,
        'last_update' => date('Y-m-d H:i:s')
    ];
}

/**
 * Visites récentes
 */
function getRecentVisits($limit = 10) {
    $visits = executeQuery("
        SELECT 
            id,
            visitor_ip,
            page_url,
            page_title,
            browser,
            os,
            is_mobile,
            DATE_FORMAT(visit_date, '%Y-%m-%dT%H:%i:%s') as visit_date
        FROM site_analytics 
        ORDER BY visit_date DESC
        LIMIT ?
    ", [$limit])->fetchAll();
    
    return [
        'visits' => $visits,
        'count' => count($visits)
    ];
}

/**
 * Événements récents
 */
function getRecentEvents($limit = 10) {
    $events = executeQuery("
        SELECT 
            id,
            event_type,
            event_category,
            event_action,
            event_label,
            event_value,
            page_url,
            visitor_ip,
            DATE_FORMAT(event_date, '%Y-%m-%dT%H:%i:%s') as event_date
        FROM site_events 
        ORDER BY event_date DESC
        LIMIT ?
    ", [$limit])->fetchAll();
    
    return [
        'events' => $events,
        'count' => count($events)
    ];
}

/**
 * Statistiques en temps réel
 */
function getLiveStats() {
    $now = date('Y-m-d H:i:s');
    $oneHourAgo = date('Y-m-d H:i:s', strtotime('-1 hour'));
    $fiveMinutesAgo = date('Y-m-d H:i:s', strtotime('-5 minutes'));
    
    // Visiteurs actifs (dernières 5 minutes)
    $activeVisitors = executeQuery("
        SELECT COUNT(DISTINCT session_id) as active_count
        FROM site_analytics 
        WHERE visit_date >= ?
    ", [$fiveMinutesAgo])->fetch();
    
    // Activité dernière heure
    $hourlyActivity = executeQuery("
        SELECT 
            DATE_FORMAT(visit_date, '%H:%i') as time_slot,
            COUNT(*) as visits
        FROM site_analytics 
        WHERE visit_date >= ?
        GROUP BY DATE_FORMAT(visit_date, '%H:%i')
        ORDER BY time_slot DESC
        LIMIT 12
    ", [$oneHourAgo])->fetchAll();
    
    // Événements récents par type
    $eventTypes = executeQuery("
        SELECT 
            event_type,
            COUNT(*) as count
        FROM site_events 
        WHERE event_date >= ?
        GROUP BY event_type
        ORDER BY count DESC
    ", [$oneHourAgo])->fetchAll();
    
    // Performance moyenne
    $avgPerformance = executeQuery("
        SELECT 
            AVG(load_time) as avg_load_time,
            COUNT(*) as measurements
        FROM page_performance 
        WHERE measurement_date >= ?
    ", [$oneHourAgo])->fetch();
    
    return [
        'active_visitors' => $activeVisitors,
        'hourly_activity' => array_reverse($hourlyActivity),
        'event_types' => $eventTypes,
        'avg_performance' => $avgPerformance,
        'timestamp' => $now
    ];
}
?>