<?php
/**
 * API de tracking pour les statistiques - SERVICES-AE
 */

// Headers pour AJAX
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Seulement traiter les requêtes POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

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

// Démarrer la session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Récupérer les données POST
$data = json_decode(file_get_contents('php://input'), true);

if (!$data) {
    $data = $_POST;
}

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

try {
    switch ($action) {
        case 'track_visit':
            trackVisit($data);
            break;
        case 'track_event':
            trackEvent($data);
            break;
        case 'track_performance':
            trackPerformance($data);
            break;
        default:
            throw new Exception('Action non reconnue');
    }
    
    echo json_encode(['success' => true]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

/**
 * Enregistrer une visite de page
 */
function trackVisit($data) {
    $visitor_ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();

    // Détection du pays via GeoIP
    $country = '';
    try {
        $geo = @file_get_contents('http://ip-api.com/json/' . $visitor_ip);
        if ($geo) {
            $geoData = json_decode($geo, true);
            if (!empty($geoData['country'])) {
                $country = $geoData['country'];
            }
        }
    } catch (Exception $e) {
        $country = '';
    }

    // Analyser le user agent
    $browser = detectBrowser($user_agent);
    $os = detectOS($user_agent);
    $is_mobile = detectMobile($user_agent);
    $is_bot = detectBot($user_agent);

    // Utiliser le timestamp fourni ou l'heure actuelle
    $visit_date = isset($data['timestamp']) ? date('Y-m-d H:i:s', strtotime($data['timestamp'])) : date('Y-m-d H:i:s');

    $visit_data = [
        'visitor_ip' => $visitor_ip,
        'user_agent' => $user_agent,
        'page_url' => $data['page_url'] ?? '',
        'page_title' => $data['page_title'] ?? '',
        'referrer' => $data['referrer'] ?? '',
        'session_id' => $session_id,
        'visit_date' => $visit_date,
        'visit_duration' => 0, // Sera mis à jour plus tard
        'is_mobile' => $is_mobile ? 1 : 0,
        'is_bot' => $is_bot ? 1 : 0,
        'country' => $country,
        'browser' => $browser,
        'os' => $os,
        'screen_resolution' => $data['screen_resolution'] ?? '',
        'language' => $data['language'] ?? ''
    ];

    executeQuery("
        INSERT INTO site_analytics
        (visitor_ip, user_agent, page_url, page_title, referrer, session_id, visit_date, visit_duration, is_mobile, is_bot, country, browser, os, screen_resolution, language)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ", array_values($visit_data));
}

/**
 * Enregistrer un événement
 */
function trackEvent($data) {
    $visitor_ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();

    // Utiliser le timestamp fourni ou l'heure actuelle
    $event_date = isset($data['timestamp']) ? date('Y-m-d H:i:s', strtotime($data['timestamp'])) : date('Y-m-d H:i:s');

    $event_data = [
        'session_id' => $session_id,
        'event_type' => $data['event_type'] ?? '',
        'event_category' => $data['event_category'] ?? '',
        'event_action' => $data['event_action'] ?? '',
        'event_label' => $data['event_label'] ?? '',
        'event_value' => floatval($data['event_value'] ?? 0),
        'page_url' => $data['page_url'] ?? '',
        'visitor_ip' => $visitor_ip,
        'event_date' => $event_date,
        'user_agent' => $user_agent
    ];

    executeQuery("
        INSERT INTO site_events
        (session_id, event_type, event_category, event_action, event_label, event_value, page_url, visitor_ip, event_date, user_agent)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ", array_values($event_data));
}

/**
 * Enregistrer les performances de page
 */
function trackPerformance($data) {
    $visitor_ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';

    // Utiliser le timestamp fourni ou l'heure actuelle
    $measurement_date = isset($data['timestamp']) ? date('Y-m-d H:i:s', strtotime($data['timestamp'])) : date('Y-m-d H:i:s');

    $perf_data = [
        'page_url' => $data['page_url'] ?? '',
        'load_time' => floatval($data['load_time'] ?? 0),
        'dom_ready_time' => floatval($data['dom_ready_time'] ?? 0),
        'page_size' => intval($data['page_size'] ?? 0),
        'num_requests' => intval($data['num_requests'] ?? 0),
        'visitor_ip' => $visitor_ip,
        'measurement_date' => $measurement_date
    ];

    executeQuery("
        INSERT INTO page_performance
        (page_url, load_time, dom_ready_time, page_size, num_requests, visitor_ip, measurement_date)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ", array_values($perf_data));
}

/**
 * Détecter le navigateur
 */
function detectBrowser($user_agent) {
    if (strpos($user_agent, 'Chrome') !== false && strpos($user_agent, 'Edg') === false) {
        return 'Chrome';
    } elseif (strpos($user_agent, 'Firefox') !== false) {
        return 'Firefox';
    } elseif (strpos($user_agent, 'Safari') !== false && strpos($user_agent, 'Chrome') === false) {
        return 'Safari';
    } elseif (strpos($user_agent, 'Edg') !== false) {
        return 'Edge';
    } elseif (strpos($user_agent, 'Opera') !== false || strpos($user_agent, 'OPR') !== false) {
        return 'Opera';
    } elseif (strpos($user_agent, 'Trident') !== false || strpos($user_agent, 'MSIE') !== false) {
        return 'Internet Explorer';
    }
    return 'Autre';
}

/**
 * Détecter le système d'exploitation
 */
function detectOS($user_agent) {
    if (strpos($user_agent, 'Windows NT 10') !== false) {
        return 'Windows 10';
    } elseif (strpos($user_agent, 'Windows NT') !== false) {
        return 'Windows';
    } elseif (strpos($user_agent, 'Mac OS X') !== false) {
        return 'macOS';
    } elseif (strpos($user_agent, 'Linux') !== false) {
        return 'Linux';
    } elseif (strpos($user_agent, 'Android') !== false) {
        return 'Android';
    } elseif (strpos($user_agent, 'iPhone') !== false || strpos($user_agent, 'iPad') !== false) {
        return 'iOS';
    }
    return 'Autre';
}

/**
 * Détecter si c'est un appareil mobile
 */
function detectMobile($user_agent) {
    return preg_match('/Mobile|Android|iPhone|iPad|iPod|BlackBerry|Windows Phone/', $user_agent);
}

/**
 * Détecter si c'est un bot
 */
function detectBot($user_agent) {
    $bot_patterns = [
        'Googlebot', 'Bingbot', 'Yahoo', 'facebookexternalhit', 
        'Twitterbot', 'WhatsApp', 'LinkedInBot', 'Applebot',
        'crawler', 'spider', 'bot', 'slurp'
    ];
    
    foreach ($bot_patterns as $pattern) {
        if (stripos($user_agent, $pattern) !== false) {
            return true;
        }
    }
    return false;
}
?>