<?php
/**
 * Installation du système de statistiques - SERVICES-AE
 */

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

echo "<!DOCTYPE html>
<html>
<head>
    <meta charset='UTF-8'>
    <title>Installation Statistiques</title>
    <style>
        body { font-family: Arial; margin: 20px; background: #f8f9fa; }
        .success { background: #d4edda; border: 2px solid #28a745; padding: 15px; margin: 15px 0; border-radius: 8px; }
        .error { background: #f8d7da; border: 2px solid #dc3545; padding: 15px; margin: 15px 0; border-radius: 8px; }
        .info { background: #d1ecf1; border: 2px solid #17a2b8; padding: 15px; margin: 15px 0; border-radius: 8px; }
        code { background: #e9ecef; padding: 2px 6px; border-radius: 3px; }
    </style>
</head>
<body>
    <h1>📊 Installation du Système de Statistiques</h1>";

try {
    // Table pour les visites
    executeQuery("
        CREATE TABLE IF NOT EXISTS site_analytics (
            id INT AUTO_INCREMENT PRIMARY KEY,
            visitor_ip VARCHAR(45) NOT NULL,
            user_agent TEXT,
            page_url VARCHAR(500) NOT NULL,
            page_title VARCHAR(200),
            referrer VARCHAR(500),
            session_id VARCHAR(100),
            visit_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            visit_duration INT DEFAULT 0,
            is_mobile BOOLEAN DEFAULT FALSE,
            is_bot BOOLEAN DEFAULT FALSE,
            country VARCHAR(50),
            browser VARCHAR(50),
            os VARCHAR(50),
            screen_resolution VARCHAR(20),
            language VARCHAR(10)
        )
    ");
    
    echo "<div class='success'>✅ Table 'site_analytics' créée avec succès</div>";
    
    // Table pour les événements (clics, téléchargements, etc.)
    executeQuery("
        CREATE TABLE IF NOT EXISTS site_events (
            id INT AUTO_INCREMENT PRIMARY KEY,
            session_id VARCHAR(100) NOT NULL,
            event_type VARCHAR(50) NOT NULL,
            event_category VARCHAR(50),
            event_action VARCHAR(100),
            event_label VARCHAR(200),
            event_value DECIMAL(10,2),
            page_url VARCHAR(500),
            visitor_ip VARCHAR(45),
            event_date DATETIME DEFAULT CURRENT_TIMESTAMP,
            user_agent TEXT
        )
    ");
    
    echo "<div class='success'>✅ Table 'site_events' créée avec succès</div>";
    
    // Table pour les performances des pages
    executeQuery("
        CREATE TABLE IF NOT EXISTS page_performance (
            id INT AUTO_INCREMENT PRIMARY KEY,
            page_url VARCHAR(500) NOT NULL,
            load_time DECIMAL(5,3),
            dom_ready_time DECIMAL(5,3),
            page_size INT,
            num_requests INT,
            visitor_ip VARCHAR(45),
            measurement_date DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    ");
    
    echo "<div class='success'>✅ Table 'page_performance' créée avec succès</div>";
    
    // Table pour les erreurs 404
    executeQuery("
        CREATE TABLE IF NOT EXISTS error_logs (
            id INT AUTO_INCREMENT PRIMARY KEY,
            error_code INT NOT NULL,
            requested_url VARCHAR(500) NOT NULL,
            referrer VARCHAR(500),
            visitor_ip VARCHAR(45),
            user_agent TEXT,
            error_date DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    ");
    
    echo "<div class='success'>✅ Table 'error_logs' créée avec succès</div>";
    
    // Ajouter des index pour les performances
    executeQuery("ALTER TABLE site_analytics ADD INDEX idx_visit_date (visit_date)");
    executeQuery("ALTER TABLE site_analytics ADD INDEX idx_visitor_ip (visitor_ip)");
    executeQuery("ALTER TABLE site_analytics ADD INDEX idx_page_url (page_url)");
    executeQuery("ALTER TABLE site_events ADD INDEX idx_event_date (event_date)");
    executeQuery("ALTER TABLE site_events ADD INDEX idx_event_type (event_type)");
    
    echo "<div class='success'>✅ Index de performance ajoutés</div>";
    
    // Insérer quelques données de test
    $test_data = [
        ['127.0.0.1', 'index.php', 'Accueil - SERVICES-AE'],
        ['127.0.0.1', 'it_service.html', 'Nos Services - SERVICES-AE'],
        ['127.0.0.1', 'add-testimonial.php', 'Ajouter Témoignage - SERVICES-AE'],
        ['127.0.0.1', 'it_contact.html', 'Contact - SERVICES-AE'],
        ['192.168.1.100', 'index.php', 'Accueil - SERVICES-AE'],
        ['192.168.1.101', 'it_service.html', 'Nos Services - SERVICES-AE']
    ];
    
    foreach ($test_data as $data) {
        executeQuery("
            INSERT INTO site_analytics (visitor_ip, page_url, page_title, user_agent, session_id, is_mobile, browser, os) 
            VALUES (?, ?, ?, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', ?, FALSE, 'Chrome', 'Windows')
        ", [$data[0], $data[1], $data[2], 'session_' . uniqid()]);
    }
    
    echo "<div class='info'>📊 Données de test ajoutées (6 visites simulées)</div>";
    
    // Insérer des événements de test
    $events = [
        ['click', 'navigation', 'menu_services', 'Menu Services'],
        ['click', 'testimonial', 'add_testimonial', 'Bouton Ajouter Témoignage'],
        ['form_submit', 'contact', 'contact_form', 'Formulaire Contact'],
        ['download', 'document', 'brochure_pdf', 'Téléchargement Brochure']
    ];
    
    foreach ($events as $event) {
        executeQuery("
            INSERT INTO site_events (session_id, event_type, event_category, event_action, event_label, page_url, visitor_ip) 
            VALUES (?, ?, ?, ?, ?, 'index.php', '127.0.0.1')
        ", ['session_' . uniqid(), $event[0], $event[1], $event[2], $event[3]]);
    }
    
    echo "<div class='info'>🎯 Événements de test ajoutés (4 événements simulés)</div>";
    
    echo "
    <div class='success'>
        <h2>🎉 Installation terminée avec succès !</h2>
        <p>Le système de statistiques est maintenant prêt. Vous pouvez :</p>
        <ul>
            <li><a href='admin/dashboard-stats.php' style='color: #007bff;'>📊 Accéder au tableau de bord</a></li>
            <li><a href='install-tracking.php' style='color: #28a745;'>🔧 Installer le code de tracking</a></li>
            <li><a href='index.php' style='color: #6c757d;'>🏠 Retour à l'accueil</a></li>
        </ul>
    </div>";

} catch (Exception $e) {
    echo "<div class='error'>❌ Erreur lors de l'installation : " . $e->getMessage() . "</div>";
}

echo "</body></html>";
?>