<?php
/**
 * Dashboard Analytics moderne - SERVICES-AE
 * Utilise le template Materio avec graphiques avancés
 */

// Protection d'authentification (comme les autres pages admin)
require_once __DIR__ . '/auth-check.php';

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

// Configuration de la page
$page_title = 'Analytics & Statistiques';
$current_page = 'analytics';
$include_charts = true;

// Période sélectionnée
$period = $_GET['period'] ?? 'today';
$period_labels = [
    'today' => 'Aujourd\'hui',
    '7days' => '7 derniers jours', 
    '30days' => '30 derniers jours',
    'all' => 'Toutes les données'
];
$period_label = $period_labels[$period] ?? 'Aujourd\'hui';

// Conditions de date selon la période
switch ($period) {
    case 'today':
        $date_condition = "DATE(visit_date) = CURDATE()";
        break;
    case '7days':
        $date_condition = "visit_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
        break;
    case '30days':
        $date_condition = "visit_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
        break;
    default:
        $date_condition = "1=1";
}

// Statistiques générales
try {
    // Statistiques par pays
    $country_stats = fetchAll("
        SELECT country, COUNT(*) as count
        FROM site_analytics
        WHERE $date_condition AND country IS NOT NULL AND country != ''
        GROUP BY country
        ORDER BY count DESC
        LIMIT 10
    ");
    $total_visits = fetchOne("SELECT COUNT(*) as count FROM site_analytics WHERE $date_condition")['count'];
    $unique_visitors = fetchOne("SELECT COUNT(DISTINCT visitor_ip) as count FROM site_analytics WHERE $date_condition")['count'];
    $total_events = fetchOne("SELECT COUNT(*) as count FROM site_events WHERE event_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)")['count'];
    $bounce_rate = $unique_visitors > 0 ? round((($unique_visitors - fetchOne("SELECT COUNT(DISTINCT visitor_ip) as count FROM site_analytics WHERE $date_condition AND visitor_ip IN (SELECT visitor_ip FROM site_analytics WHERE $date_condition GROUP BY visitor_ip HAVING COUNT(*) > 1)")['count']) / $unique_visitors) * 100, 1) : 0;
    
    // Pages populaires
    $top_pages = fetchAll("
        SELECT page_title, page_url, COUNT(*) as visits
        FROM site_analytics 
        WHERE $date_condition AND page_title != ''
        GROUP BY page_url, page_title
        ORDER BY visits DESC
        LIMIT 5
    ");
    
    // Navigateurs
    $browser_stats = fetchAll("
        SELECT browser, COUNT(*) as count
        FROM site_analytics 
        WHERE $date_condition AND browser != ''
        GROUP BY browser
        ORDER BY count DESC
        LIMIT 5
    ");
    
    // Systèmes d'exploitation
    $os_stats = fetchAll("
        SELECT os, COUNT(*) as count
        FROM site_analytics 
        WHERE $date_condition AND os != ''
        GROUP BY os
        ORDER BY count DESC
        LIMIT 5
    ");
    
    // Répartition mobile vs desktop
    $mobile_stats = fetchOne("
        SELECT 
            SUM(CASE WHEN is_mobile = 1 THEN 1 ELSE 0 END) as mobile,
            SUM(CASE WHEN is_mobile = 0 THEN 1 ELSE 0 END) as desktop,
            COUNT(*) as total
        FROM site_analytics 
        WHERE $date_condition
    ");
    
    // Statistiques par heure (pour aujourd'hui) ou par jour
    if ($period === 'today') {
        $time_stats = fetchAll("
            SELECT 
                HOUR(visit_date) as time_unit,
                COUNT(*) as visits
            FROM site_analytics 
            WHERE DATE(visit_date) = CURDATE()
            GROUP BY HOUR(visit_date)
            ORDER BY time_unit
        ");
        $time_label = 'Visites par heure';
    } else {
        $time_stats = fetchAll("
            SELECT 
                DATE(visit_date) as time_unit,
                COUNT(*) as visits
            FROM site_analytics 
            WHERE $date_condition
            GROUP BY DATE(visit_date)
            ORDER BY time_unit DESC
            LIMIT 10
        ");
        $time_label = 'Visites par jour';
    }
    
    // Événements récents
    $recent_events = fetchAll("
        SELECT event_type, event_action, event_label, page_url,
               DATE_FORMAT(event_date, '%d/%m/%Y %H:%i') as date_fmt
        FROM site_events 
        ORDER BY event_date DESC 
        LIMIT 10
    ");
    
    // Performance moyenne
    $avg_performance = fetchOne("
        SELECT 
            AVG(load_time) as avg_load_time,
            COUNT(*) as measurements
        FROM page_performance 
        WHERE measurement_date >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    
    // Témoignages pour contexte
    $pending_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE approuve = 0")['count'];
    
} catch (Exception $e) {
    $error_message = "Erreur lors du chargement des statistiques : " . $e->getMessage();
}

// Contenu de la page
ob_start();
?>

<?php if (isset($error_message)): ?>
<div class="alert alert-warning alert-dismissible fade show" role="alert">
    <i class="ri-error-warning-line me-2"></i>
    <?php echo $error_message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Sélecteur de période -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <h5 class="mb-1">Période d'analyse : <strong><?php echo $period_label; ?></strong></h5>
                        <p class="text-muted mb-0">
                            <i class="ri-calendar-line me-1"></i>
                            Dernière mise à jour : <?php echo date('d/m/Y à H:i'); ?>
                        </p>
                    </div>
                    <div class="btn-group" role="group">
                        <a href="?period=today" class="btn <?php echo $period === 'today' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                            Aujourd'hui
                        </a>
                        <a href="?period=7days" class="btn <?php echo $period === '7days' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                            7 jours
                        </a>
                        <a href="?period=30days" class="btn <?php echo $period === '30days' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                            30 jours
                        </a>
                        <a href="?period=all" class="btn <?php echo $period === 'all' ? 'btn-primary' : 'btn-outline-primary'; ?>">
                            Tout
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Monitoring en temps réel -->
<div class="row mb-6">
    <div class="col-12">
        <div class="card border-start border-4 border-danger shadow-lg">
            <div class="card-header">
                <div class="d-flex align-items-center justify-content-between">
                    <div>
                        <h4 class="mb-1 text-danger"><i class="ri ri-live-line me-2"></i>Monitoring en Temps Réel</h4>
                        <small class="text-muted">Mise à jour automatique toutes les 30 secondes</small>
                    </div>
                    <div>
                        <span id="last-update" class="badge bg-danger text-white">
                            <i class="ri ri-refresh-line me-1"></i>
                            En cours...
                        </span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row text-center g-4">
                    <div class="col-md-3">
                        <div class="p-3 border border-success rounded">
                            <div class="text-center mb-2">
                                <i class="ri ri-user-line text-success" style="font-size: 2rem;"></i>
                            </div>
                            <h3 id="activeVisitors" class="text-success mb-1 text-center">-</h3>
                            <small class="text-muted d-block text-center">Visiteurs Actifs</small>
                            <div class="small text-success"><i class="ri-circle-fill ri-xs me-1"></i>Dernières 5 min</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 border border-info rounded">
                            <div class="text-center mb-2">
                                <i class="ri ri-eye-line text-info" style="font-size: 2rem;"></i>
                            </div>
                            <h3 id="realtimeViews" class="text-info mb-1 text-center">-</h3>
                            <small class="text-muted d-block text-center">Vues/Heure</small>
                            <div class="small text-info"><i class="ri-trending-up-line ri-xs me-1"></i>Dernière heure</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 border border-warning rounded">
                            <div class="text-center mb-2">
                                <i class="ri ri-mouse-line text-warning" style="font-size: 2rem;"></i>
                            </div>
                            <h3 id="realtimeEvents" class="text-warning mb-1 text-center">-</h3>
                            <small class="text-muted d-block text-center">Événements/Heure</small>
                            <div class="small text-warning"><i class="ri-flashlight-line ri-xs me-1"></i>Interactions</div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 border border-danger rounded">
                            <div class="text-center mb-2">
                                <i class="ri ri-timer-line text-danger" style="font-size: 2rem;"></i>
                            </div>
                            <h3 id="avgResponseTime" class="text-danger mb-1 text-center">-</h3>
                            <small class="text-muted d-block text-center">Temps Réponse</small>
                            <div class="small text-danger"><i class="ri-time-line ri-xs me-1"></i>Moyenne</div>
                        </div>
                    </div>
                </div>
                
                <div class="row mt-4">
                    <div class="col-md-8">
                        <canvas id="realtimeChart" height="80"></canvas>
                    </div>
                    <div class="col-md-4">
                        <h6 class="text-muted mb-3"><i class="ri-pulse-line me-2 text-primary"></i>Activité Récente</h6>
                        <div id="recentActivity" style="max-height: 200px; overflow-y: auto;">
                            <div class="text-center text-muted">Chargement...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Statistiques principales -->
<div class="row mb-6">
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 border-primary">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-eye-line text-primary" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title text-primary mb-2"><?php echo number_format($total_visits); ?></h3>
                <p class="text-muted mb-0">Visites Totales</p>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 border-success">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-user-line text-success" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title text-success mb-2"><?php echo number_format($unique_visitors); ?></h3>
                <p class="text-muted mb-0">Visiteurs Uniques</p>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 border-info">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-mouse-line text-info" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title text-info mb-2"><?php echo number_format($total_events); ?></h3>
                <p class="text-muted mb-0">Événements</p>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 <?php echo $bounce_rate > 70 ? 'border-warning' : 'border-dark'; ?>">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-logout-box-line <?php echo $bounce_rate > 70 ? 'text-warning' : 'text-dark'; ?>" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title <?php echo $bounce_rate > 70 ? 'text-warning' : 'text-dark'; ?> mb-2"><?php echo $bounce_rate; ?>%</h3>
                <p class="text-muted mb-0">Taux de Rebond</p>
            </div>
        </div>
    </div>
</div>

<!-- Graphiques -->
<div class="row mb-6">
    <!-- Graphique temporel -->
    <div class="col-lg-8 mb-4">
        <div class="card h-100">
            <div class="card-header d-flex align-items-center">
                <h5 class="mb-0">
                    <i class="ri-line-chart-line me-2 text-primary"></i>
                    <?php echo $time_label; ?>
                </h5>
            </div>
            <div class="card-body">
                <canvas id="visitsChart" height="100"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Répartition mobile/desktop -->
    <div class="col-lg-4 mb-4">
        <div class="card h-100">
            <div class="card-header d-flex align-items-center">
                <h5 class="mb-0">
                    <i class="ri-pie-chart-line me-2 text-success"></i>
                    Appareils
                </h5>
            </div>
            <div class="card-body d-flex align-items-center justify-content-center">
                <canvas id="deviceChart" width="200" height="200"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- Données détaillées -->
<div class="row">
    <!-- Pays des visiteurs -->
    <div class="col-lg-6 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="ri-earth-line me-2 text-success"></i>
                    Pays des visiteurs
                </h5>
            </div>
            <div class="card-body">
                <?php if (!empty($country_stats)): ?>
                <div class="d-flex flex-column gap-3">
                    <?php 
                    $total_country_visits = array_sum(array_column($country_stats, 'count'));
                    foreach ($country_stats as $country): 
                        $percentage = $total_country_visits > 0 ? round(($country['count'] / $total_country_visits) * 100) : 0;
                    ?>
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between mb-1">
                                <span class="fw-medium"><?php echo htmlspecialchars($country['country'] ?: 'Inconnu'); ?></span>
                                <span class="text-muted"><?php echo $percentage; ?>%</span>
                            </div>
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-success" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </div>
                        <div class="ms-3">
                            <span class="badge bg-label-secondary"><?php echo number_format($country['count']); ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="text-center py-4 text-muted">
                    <i class="ri-earth-line ri-3x mb-3 d-block"></i>
                    <p>Aucune donnée de pays disponible</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <!-- Top pages -->
    <div class="col-lg-6 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="ri-file-list-line me-2 text-warning"></i>
                    Pages Populaires
                </h5>
            </div>
            <div class="card-body">
                <?php if (!empty($top_pages)): ?>
                <div class="table-responsive">
                    <table class="table table-borderless">
                        <thead>
                            <tr>
                                <th>Page</th>
                                <th class="text-end">Visites</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($top_pages as $page): ?>
                            <tr>
                                <td>
                                    <div>
                                        <strong><?php echo htmlspecialchars($page['page_title'] ?: 'Page sans titre'); ?></strong>
                                        <br><small class="text-muted"><?php echo htmlspecialchars($page['page_url']); ?></small>
                                    </div>
                                </td>
                                <td class="text-end">
                                    <span class="badge bg-label-primary"><?php echo number_format($page['visits']); ?></span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php else: ?>
                <div class="text-center py-4 text-muted">
                    <i class="ri-inbox-line ri-3x mb-3 d-block"></i>
                    <p>Aucune donnée de page disponible</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Navigateurs -->
    <div class="col-lg-6 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="ri-global-line me-2 text-info"></i>
                    Navigateurs
                </h5>
            </div>
            <div class="card-body">
                <?php if (!empty($browser_stats)): ?>
                <div class="d-flex flex-column gap-3">
                    <?php 
                    $total_browser_visits = array_sum(array_column($browser_stats, 'count'));
                    foreach ($browser_stats as $browser): 
                        $percentage = $total_browser_visits > 0 ? round(($browser['count'] / $total_browser_visits) * 100) : 0;
                    ?>
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between mb-1">
                                <span class="fw-medium"><?php echo htmlspecialchars($browser['browser']); ?></span>
                                <span class="text-muted"><?php echo $percentage; ?>%</span>
                            </div>
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar bg-info" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </div>
                        <div class="ms-3">
                            <span class="badge bg-label-secondary"><?php echo number_format($browser['count']); ?></span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="text-center py-4 text-muted">
                    <i class="ri-computer-line ri-3x mb-3 d-block"></i>
                    <p>Aucune donnée de navigateur disponible</p>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
$page_content = ob_get_clean();

// JavaScript pour les graphiques et temps réel
$page_js = '
let realtimeChart;
let visitsChart;
let deviceChart;

// Données PHP pour JS
const timeStats = ' . json_encode($time_stats) . ';
const mobileStats = ' . json_encode($mobile_stats) . ';
const timeLabel = "' . $time_label . '";

document.addEventListener("DOMContentLoaded", function() {
    initCharts();
    initRealTimeUpdates();
});

function initCharts() {
    // Graphique temps réel
    const realtimeCtx = document.getElementById("realtimeChart").getContext("2d");
    realtimeChart = new Chart(realtimeCtx, {
        type: "line",
        data: {
            labels: [],
            datasets: [{
                label: "Visites",
                data: [],
                borderColor: "#28a745",
                backgroundColor: "rgba(40, 167, 69, 0.1)",
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
    
    // Graphique des visites
    const visitsCtx = document.getElementById("visitsChart").getContext("2d");
    visitsChart = new Chart(visitsCtx, {
        type: "line",
        data: {
            labels: timeStats.map(item => item.time_unit),
            datasets: [{
                label: "Visites",
                data: timeStats.map(item => item.visits),
                borderColor: "#667eea",
                backgroundColor: "rgba(102, 126, 234, 0.1)",
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false }
            }
        }
    });
    
    // Graphique répartition appareils
    const deviceCtx = document.getElementById("deviceChart").getContext("2d");
    deviceChart = new Chart(deviceCtx, {
        type: "doughnut",
        data: {
            labels: ["Mobile", "Desktop"],
            datasets: [{
                data: [mobileStats.mobile || 0, mobileStats.desktop || 0],
                backgroundColor: ["#FF6384", "#36A2EB"],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: "bottom",
                    labels: { padding: 20 }
                }
            }
        }
    });
}

function initRealTimeUpdates() {
    updateRealTimeData();
    setInterval(updateRealTimeData, 30000);
}

async function updateRealTimeData() {
    try {
        const response = await fetch("../api-analytics.php?action=live_stats");
        const data = await response.json();
        
        if (data.error) {
            console.error("Erreur API:", data.error);
            return;
        }
        
        // Mettre à jour les compteurs
        document.getElementById("activeVisitors").textContent = data.active_visitors?.active_count || "0";
        
        const hourlyTotal = data.hourly_activity?.reduce((sum, item) => sum + parseInt(item.visits), 0) || 0;
        document.getElementById("realtimeViews").textContent = hourlyTotal;
        
        const eventsTotal = data.event_types?.reduce((sum, item) => sum + parseInt(item.count), 0) || 0;
        document.getElementById("realtimeEvents").textContent = eventsTotal;
        
        const avgTime = data.avg_performance?.avg_load_time ? 
            Math.round(data.avg_performance.avg_load_time) + "ms" : "N/A";
        document.getElementById("avgResponseTime").textContent = avgTime;
        
        // Mettre à jour l\'heure
        document.getElementById("last-update").innerHTML = 
            \'<i class="ri-check-line me-1"></i>\' + new Date().toLocaleTimeString("fr-FR");
        
        // Mettre à jour le graphique temps réel
        if (realtimeChart && data.hourly_activity) {
            const labels = data.hourly_activity.map(item => item.time_slot);
            const visits = data.hourly_activity.map(item => parseInt(item.visits));
            
            realtimeChart.data.labels = labels;
            realtimeChart.data.datasets[0].data = visits;
            realtimeChart.update("none");
        }
        
        // Mettre à jour l\'activité récente
        updateRecentActivity();
        
    } catch (error) {
        console.error("Erreur mise à jour temps réel:", error);
        document.getElementById("last-update").innerHTML = 
            \'<i class="ri-error-warning-line me-1"></i>Erreur\';
    }
}

async function updateRecentActivity() {
    try {
        const [visitsResponse, eventsResponse] = await Promise.all([
            fetch("../api-analytics.php?action=recent_visits"),
            fetch("../api-analytics.php?action=recent_events")
        ]);
        
        const visits = await visitsResponse.json();
        const events = await eventsResponse.json();
        
        let html = "";
        
        const allActivity = [
            ...(visits.visits || []).map(v => ({...v, type: "visit", time: v.visit_date})),
            ...(events.events || []).map(e => ({...e, type: "event", time: e.event_date}))
        ].sort((a, b) => new Date(b.time) - new Date(a.time)).slice(0, 8);
        
        allActivity.forEach(item => {
            const timeAgo = getTimeAgo(item.time);
            if (item.type === "visit") {
                html += `
                    <div class="d-flex justify-content-between align-items-center mb-2 p-2 bg-light rounded">
                        <div>
                            <span class="badge bg-success me-2">👀</span>
                            <small><strong>${item.page_title || "Page sans titre"}</strong></small>
                        </div>
                        <small class="text-muted">${timeAgo}</small>
                    </div>
                `;
            } else {
                html += `
                    <div class="d-flex justify-content-between align-items-center mb-2 p-2 bg-light rounded">
                        <div>
                            <span class="badge bg-primary me-2">⚡</span>
                            <small>${item.event_action} (${item.event_category})</small>
                        </div>
                        <small class="text-muted">${timeAgo}</small>
                    </div>
                `;
            }
        });
        
        document.getElementById("recentActivity").innerHTML = 
            html || \'<div class="text-muted text-center">Aucune activité récente</div>\';
        
    } catch (error) {
        console.error("Erreur activité récente:", error);
    }
}

function getTimeAgo(timestamp) {
    const now = new Date();
    const time = new Date(timestamp);
    const diffMs = now - time;
    const diffMins = Math.floor(diffMs / 60000);
    
    if (diffMins < 1) return "À l\'instant";
    if (diffMins < 60) return `Il y a ${diffMins}min`;
    
    const diffHours = Math.floor(diffMins / 60);
    if (diffHours < 24) return `Il y a ${diffHours}h`;
    
    const diffDays = Math.floor(diffHours / 24);
    return `Il y a ${diffDays}j`;
}
';

// Inclure le template
include 'template.php';
?>