<?php
/**
 * Admin - Global Advertising Analytics Dashboard
 * Comprehensive statistics for all ads across ERP instances
 */
require_once '../config.php';
$admin = isAdminLogged();
$currentPage = 'advertising';

// =============================================
// FETCH ALL GLOBAL STATISTICS
// =============================================

// 1. Global KPIs
$globalKPIs = $pdo->query("
    SELECT 
        (SELECT COUNT(*) FROM server_ads) as total_ads,
        (SELECT COUNT(*) FROM server_ads WHERE is_active = 1) as active_ads,
        (SELECT SUM(views) FROM server_ads) as total_views,
        (SELECT SUM(clicks) FROM server_ads) as total_clicks,
        (SELECT COUNT(DISTINCT ip_address) FROM server_ads_stats WHERE action_type = 'view') as unique_reach
")->fetch(PDO::FETCH_ASSOC);

$globalCTR = $globalKPIs['total_views'] > 0 
    ? round(($globalKPIs['total_clicks'] / $globalKPIs['total_views']) * 100, 2) 
    : 0;

// 2. Performance by Placement Zone
$zonePerformance = $pdo->query("
    SELECT 
        a.placement,
        COUNT(a.id) as ad_count,
        SUM(a.views) as total_views,
        SUM(a.clicks) as total_clicks,
        ROUND(SUM(a.clicks) / NULLIF(SUM(a.views), 0) * 100, 2) as ctr
    FROM server_ads a
    GROUP BY a.placement
    ORDER BY total_views DESC
")->fetchAll(PDO::FETCH_ASSOC);

// 3. Performance by Tenant (ERP Node)
$tenantPerformance = $pdo->query("
    SELECT 
        COALESCE(t.name, 'Global (Sans ciblage)') as tenant_name,
        COUNT(a.id) as ad_count,
        SUM(a.views) as total_views,
        SUM(a.clicks) as total_clicks,
        ROUND(SUM(a.clicks) / NULLIF(SUM(a.views), 0) * 100, 2) as ctr
    FROM server_ads a
    LEFT JOIN tenants t ON a.tenant_id = t.id
    GROUP BY a.tenant_id, t.name
    ORDER BY total_views DESC
")->fetchAll(PDO::FETCH_ASSOC);

// 4. Top Performing Ads (by CTR)
$topAds = $pdo->query("
    SELECT 
        id, title, placement, views, clicks,
        ROUND(clicks / NULLIF(views, 0) * 100, 2) as ctr
    FROM server_ads
    WHERE views > 0
    ORDER BY ctr DESC, clicks DESC
    LIMIT 10
")->fetchAll(PDO::FETCH_ASSOC);

// 5. Daily Trend (Last 30 days)
$dailyTrend = $pdo->query("
    SELECT 
        DATE(viewed_at) as date,
        SUM(CASE WHEN action_type = 'view' THEN 1 ELSE 0 END) as views,
        SUM(CASE WHEN action_type = 'click' THEN 1 ELSE 0 END) as clicks
    FROM server_ads_stats
    WHERE viewed_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY DATE(viewed_at)
    ORDER BY date ASC
")->fetchAll(PDO::FETCH_ASSOC);

// 6. Hourly Distribution (Heat Map Data)
$hourlyDistribution = $pdo->query("
    SELECT 
        HOUR(viewed_at) as hour,
        DAYOFWEEK(viewed_at) as day_of_week,
        COUNT(*) as count
    FROM server_ads_stats
    WHERE action_type = 'view' AND viewed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
    GROUP BY HOUR(viewed_at), DAYOFWEEK(viewed_at)
")->fetchAll(PDO::FETCH_ASSOC);

// Zone Labels
$zoneLabels = [
    'dashboard_hero' => 'Dashboard Hero',
    'dashboard_sidebar' => 'Dashboard Sidebar',
    'dashboard_footer' => 'Dashboard Footer',
    'module_discovery' => 'Module Discovery',
    'login_page' => 'Login Page',
    'login_welcome' => 'Login Welcome',
    'global_banner' => 'Global Banner',
    'employees_header' => 'Employés Header',
    'calendar_widget' => 'Calendrier Widget',
    'profile_actions' => 'Profil Actions',
    'todo_suggestion' => 'Todo Suggestion',
    '404_recovery' => '404 Error',
    'session_timeout' => 'Session Timeout',
    'print_sponsor' => 'Print Sponsor'
];
$pageTitle = 'Analytics Publicitaires - Admin License';
?>
<?php include 'includes/header.php'; ?>

    <?php include 'includes/sidebar.php'; ?>
    
    <main class="ml-64 p-8 min-h-screen">
        <!-- Header -->
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-3xl font-black text-slate-800 dark:text-white">
                    <i class="fa-solid fa-chart-pie text-indigo-500 mr-3"></i>Analytics Publicitaires
                </h1>
                <p class="text-slate-500 dark:text-slate-400 mt-1">Vue d'ensemble des performances publicitaires sur tout le système</p>
            </div>
            <a href="advertising.php" class="px-4 py-2 bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 font-bold rounded-lg transition-colors shadow-sm">
                <i class="fa-solid fa-arrow-left mr-2"></i>Retour
            </a>
        </div>

        <!-- Global KPIs -->
        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 shadow-sm border border-slate-100 dark:border-slate-700">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-10 h-10 bg-indigo-100 dark:bg-indigo-900/30 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-rectangle-ad text-indigo-600 dark:text-indigo-400"></i>
                    </div>
                    <span class="text-xs font-bold text-slate-400 uppercase">Total Pubs</span>
                </div>
                <div class="text-3xl font-black text-slate-800 dark:text-white"><?= number_format($globalKPIs['total_ads']) ?></div>
                <div class="text-xs text-emerald-600 dark:text-emerald-400 mt-1"><i class="fa-solid fa-circle text-[6px] mr-1"></i><?= $globalKPIs['active_ads'] ?> actives</div>
            </div>
            
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 shadow-sm border border-slate-100 dark:border-slate-700">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-10 h-10 bg-blue-100 dark:bg-blue-900/30 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-eye text-blue-600 dark:text-blue-400"></i>
                    </div>
                    <span class="text-xs font-bold text-slate-400 uppercase">Impressions</span>
                </div>
                <div class="text-3xl font-black text-slate-800 dark:text-white"><?= number_format($globalKPIs['total_views'] ?? 0) ?></div>
            </div>
            
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 shadow-sm border border-slate-100 dark:border-slate-700">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-10 h-10 bg-emerald-100 dark:bg-emerald-900/30 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-users text-emerald-600 dark:text-emerald-400"></i>
                    </div>
                    <span class="text-xs font-bold text-slate-400 uppercase">Portée Unique</span>
                </div>
                <div class="text-3xl font-black text-slate-800 dark:text-white"><?= number_format($globalKPIs['unique_reach'] ?? 0) ?></div>
            </div>
            
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 shadow-sm border border-slate-100 dark:border-slate-700">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-10 h-10 bg-amber-100 dark:bg-amber-900/30 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-mouse-pointer text-amber-600 dark:text-amber-400"></i>
                    </div>
                    <span class="text-xs font-bold text-slate-400 uppercase">Total Clics</span>
                </div>
                <div class="text-3xl font-black text-slate-800 dark:text-white"><?= number_format($globalKPIs['total_clicks'] ?? 0) ?></div>
            </div>
            
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 shadow-sm border border-slate-100 dark:border-slate-700">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-10 h-10 bg-rose-100 dark:bg-rose-900/30 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-percent text-rose-600 dark:text-rose-400"></i>
                    </div>
                    <span class="text-xs font-bold text-slate-400 uppercase">CTR Global</span>
                </div>
                <div class="text-3xl font-black text-slate-800 dark:text-white"><?= $globalCTR ?>%</div>
            </div>
            
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-5 shadow-sm border border-slate-100 dark:border-slate-700">
                <div class="flex items-center gap-3 mb-2">
                    <div class="w-10 h-10 bg-violet-100 dark:bg-violet-900/30 rounded-xl flex items-center justify-center">
                        <i class="fa-solid fa-repeat text-violet-600 dark:text-violet-400"></i>
                    </div>
                    <span class="text-xs font-bold text-slate-400 uppercase">Fréquence</span>
                </div>
                <?php $freq = ($globalKPIs['unique_reach'] > 0) ? round($globalKPIs['total_views'] / $globalKPIs['unique_reach'], 1) : 0; ?>
                <div class="text-3xl font-black text-slate-800 dark:text-white"><?= $freq ?>x</div>
            </div>
        </div>

        <!-- Charts Row -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- Daily Trend Chart -->
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-slate-100 dark:border-slate-700">
                <h3 class="font-bold text-slate-800 dark:text-white mb-4"><i class="fa-solid fa-chart-line text-indigo-500 mr-2"></i>Tendance 30 Jours</h3>
                <canvas id="trendChart" height="200"></canvas>
            </div>
            
            <!-- Zone Performance Chart -->
            <div class="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-slate-100 dark:border-slate-700">
                <h3 class="font-bold text-slate-800 dark:text-white mb-4"><i class="fa-solid fa-chart-bar text-emerald-500 mr-2"></i>Performance par Zone</h3>
                <canvas id="zoneChart" height="200"></canvas>
            </div>
        </div>

        <!-- Tables Row -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- Performance by Tenant -->
            <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
                <div class="px-6 py-4 border-b border-slate-100 bg-slate-50">
                    <h3 class="font-bold text-slate-800"><i class="fa-solid fa-building text-blue-500 mr-2"></i>Performance par Client ERP</h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 text-slate-500 uppercase text-xs">
                            <tr>
                                <th class="px-6 py-3 text-left">Client</th>
                                <th class="px-4 py-3 text-center">Pubs</th>
                                <th class="px-4 py-3 text-center">Vues</th>
                                <th class="px-4 py-3 text-center">Clics</th>
                                <th class="px-4 py-3 text-center">CTR</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($tenantPerformance as $t): ?>
                            <tr class="border-b border-slate-50 hover:bg-slate-50">
                                <td class="px-6 py-3 font-medium text-slate-700"><?= htmlspecialchars($t['tenant_name']) ?></td>
                                <td class="px-4 py-3 text-center text-slate-500"><?= $t['ad_count'] ?></td>
                                <td class="px-4 py-3 text-center"><span class="bg-indigo-100 text-indigo-700 px-2 py-0.5 rounded-full text-xs font-bold"><?= number_format($t['total_views'] ?? 0) ?></span></td>
                                <td class="px-4 py-3 text-center"><span class="bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full text-xs font-bold"><?= number_format($t['total_clicks'] ?? 0) ?></span></td>
                                <td class="px-4 py-3 text-center font-bold text-<?= ($t['ctr'] > 2 ? 'emerald' : 'slate') ?>-600"><?= $t['ctr'] ?? 0 ?>%</td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if(empty($tenantPerformance)): ?>
                            <tr><td colspan="5" class="px-6 py-8 text-center text-slate-400">Aucune donnée</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Performance by Zone -->
            <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
                <div class="px-6 py-4 border-b border-slate-100 bg-slate-50">
                    <h3 class="font-bold text-slate-800"><i class="fa-solid fa-map-location-dot text-purple-500 mr-2"></i>Performance par Emplacement</h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full text-sm">
                        <thead class="bg-slate-50 text-slate-500 uppercase text-xs">
                            <tr>
                                <th class="px-6 py-3 text-left">Zone</th>
                                <th class="px-4 py-3 text-center">Pubs</th>
                                <th class="px-4 py-3 text-center">Vues</th>
                                <th class="px-4 py-3 text-center">Clics</th>
                                <th class="px-4 py-3 text-center">CTR</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach($zonePerformance as $z): ?>
                            <tr class="border-b border-slate-50 hover:bg-slate-50">
                                <td class="px-6 py-3 font-medium text-slate-700"><?= $zoneLabels[$z['placement']] ?? $z['placement'] ?></td>
                                <td class="px-4 py-3 text-center text-slate-500"><?= $z['ad_count'] ?></td>
                                <td class="px-4 py-3 text-center"><span class="bg-indigo-100 text-indigo-700 px-2 py-0.5 rounded-full text-xs font-bold"><?= number_format($z['total_views'] ?? 0) ?></span></td>
                                <td class="px-4 py-3 text-center"><span class="bg-amber-100 text-amber-700 px-2 py-0.5 rounded-full text-xs font-bold"><?= number_format($z['total_clicks'] ?? 0) ?></span></td>
                                <td class="px-4 py-3 text-center font-bold text-<?= ($z['ctr'] > 2 ? 'emerald' : 'slate') ?>-600"><?= $z['ctr'] ?? 0 ?>%</td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if(empty($zonePerformance)): ?>
                            <tr><td colspan="5" class="px-6 py-8 text-center text-slate-400">Aucune donnée</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Top Ads -->
        <div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden mb-8">
            <div class="px-6 py-4 border-b border-slate-100 bg-gradient-to-r from-amber-50 to-orange-50">
                <h3 class="font-bold text-slate-800"><i class="fa-solid fa-trophy text-amber-500 mr-2"></i>Top 10 Publicités (par CTR)</h3>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-sm">
                    <thead class="bg-slate-50 text-slate-500 uppercase text-xs">
                        <tr>
                            <th class="px-6 py-3 text-left">#</th>
                            <th class="px-6 py-3 text-left">Titre</th>
                            <th class="px-4 py-3 text-center">Zone</th>
                            <th class="px-4 py-3 text-center">Vues</th>
                            <th class="px-4 py-3 text-center">Clics</th>
                            <th class="px-4 py-3 text-center">CTR</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($topAds as $i => $ad): ?>
                        <tr class="border-b border-slate-50 hover:bg-amber-50/30">
                            <td class="px-6 py-3">
                                <?php if($i < 3): ?>
                                    <span class="w-6 h-6 rounded-full bg-<?= ['amber', 'slate', 'orange'][$i] ?>-100 text-<?= ['amber', 'slate', 'orange'][$i] ?>-600 flex items-center justify-center text-xs font-bold">
                                        <?= $i + 1 ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-slate-400"><?= $i + 1 ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-3 font-medium text-slate-700"><?= htmlspecialchars($ad['title']) ?></td>
                            <td class="px-4 py-3 text-center"><span class="text-xs bg-slate-100 text-slate-600 px-2 py-1 rounded"><?= $zoneLabels[$ad['placement']] ?? $ad['placement'] ?></span></td>
                            <td class="px-4 py-3 text-center text-slate-600"><?= number_format($ad['views']) ?></td>
                            <td class="px-4 py-3 text-center text-slate-600"><?= number_format($ad['clicks']) ?></td>
                            <td class="px-4 py-3 text-center">
                                <span class="font-bold text-lg <?= $ad['ctr'] > 5 ? 'text-emerald-600' : ($ad['ctr'] > 2 ? 'text-blue-600' : 'text-slate-600') ?>"><?= $ad['ctr'] ?>%</span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($topAds)): ?>
                        <tr><td colspan="6" class="px-6 py-8 text-center text-slate-400">Aucune donnée disponible</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </main>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Detect dark mode for proper chart colors
    const isDark = document.documentElement.classList.contains('dark');
    const gridColor = isDark ? '#334155' : '#f1f5f9';
    const textColor = isDark ? '#94a3b8' : '#64748b';

    // Daily Trend Chart
    const trendData = <?= json_encode($dailyTrend) ?>;
    const trendLabels = trendData.map(d => new Date(d.date).toLocaleDateString('fr-FR', {day: '2-digit', month: 'short'}));
    const trendViews = trendData.map(d => d.views);
    const trendClicks = trendData.map(d => d.clicks);

    new Chart(document.getElementById('trendChart'), {
        type: 'line',
        data: {
            labels: trendLabels,
            datasets: [
                {
                    label: 'Impressions',
                    data: trendViews,
                    borderColor: '#6366f1',
                    backgroundColor: 'rgba(99, 102, 241, 0.1)',
                    fill: true,
                    tension: 0.4
                },
                {
                    label: 'Clics',
                    data: trendClicks,
                    borderColor: '#f59e0b',
                    backgroundColor: 'rgba(245, 158, 11, 0.1)',
                    fill: true,
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            plugins: { 
                legend: { 
                    position: 'bottom',
                    labels: { color: textColor }
                } 
            },
            scales: { 
                y: { 
                    beginAtZero: true,
                    grid: { color: gridColor },
                    ticks: { color: textColor }
                },
                x: {
                    grid: { color: gridColor },
                    ticks: { color: textColor }
                }
            }
        }
    });

    // Zone Performance Chart
    const zoneData = <?= json_encode($zonePerformance) ?>;
    const zoneLabelsMap = <?= json_encode($zoneLabels) ?>;
    
    new Chart(document.getElementById('zoneChart'), {
        type: 'bar',
        data: {
            labels: zoneData.map(z => zoneLabelsMap[z.placement] || z.placement),
            datasets: [
                {
                    label: 'Vues',
                    data: zoneData.map(z => z.total_views),
                    backgroundColor: 'rgba(99, 102, 241, 0.7)',
                },
                {
                    label: 'Clics',
                    data: zoneData.map(z => z.total_clicks),
                    backgroundColor: 'rgba(245, 158, 11, 0.7)',
                }
            ]
        },
        options: {
            responsive: true,
            plugins: { 
                legend: { 
                    position: 'bottom',
                    labels: { color: textColor }
                } 
            },
            scales: { 
                y: { 
                    beginAtZero: true,
                    grid: { color: gridColor },
                    ticks: { color: textColor }
                },
                x: {
                    grid: { color: gridColor },
                    ticks: { color: textColor }
                }
            }
        }
    });
</script>

</body>
</html>
