<?php
/**
 * Admin - Advertising Management
 */
require_once '../config.php';
$admin = isAdminLogged();
$currentPage = 'advertising';

$message = '';
$error = '';

// Fetch tenants for dropdown
$tenants = $pdo->query("SELECT id, name FROM tenants ORDER BY name")->fetchAll();

// API: Get Ad Stats (AJAX)
if (isset($_GET['action']) && $_GET['action'] === 'get_stats' && isset($_GET['id'])) {
    header('Content-Type: application/json');
    try {
        $stmt = $pdo->prepare("
            SELECT 
                DATE(viewed_at) as date, 
                SUM(CASE WHEN action_type = 'view' THEN 1 ELSE 0 END) as total_views, 
                COUNT(DISTINCT CASE WHEN action_type = 'view' THEN ip_address END) as unique_ips,
                SUM(CASE WHEN action_type = 'click' THEN 1 ELSE 0 END) as total_clicks,
                MAX(viewed_at) as last_seen
            FROM server_ads_stats 
            WHERE ad_id = ? 
            GROUP BY DATE(viewed_at) 
            ORDER BY date DESC
            LIMIT 30
        ");
        $stmt->execute([$_GET['id']]);
        $dailyStats = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Calculate Summary Stats
        $summary = [
            'total_views' => 0,
            'total_clicks' => 0,
            'unique_ips' => 0,
            'avg_frequency' => 0
        ];

        // Global Stats Query
        $stmtGlobal = $pdo->prepare("
            SELECT 
                COUNT(DISTINCT CASE WHEN action_type = 'view' THEN ip_address END) as global_unique,
                SUM(CASE WHEN action_type = 'view' THEN 1 ELSE 0 END) as global_views,
                SUM(CASE WHEN action_type = 'click' THEN 1 ELSE 0 END) as global_clicks
            FROM server_ads_stats 
            WHERE ad_id = ?
        ");
        $stmtGlobal->execute([$_GET['id']]);
        $g = $stmtGlobal->fetch(PDO::FETCH_ASSOC);
        
        $summary['total_views'] = (int)$g['global_views'];
        $summary['total_clicks'] = (int)$g['global_clicks'];
        $summary['unique_ips'] = (int)$g['global_unique'];
        $summary['avg_frequency'] = $summary['unique_ips'] > 0 ? round($summary['total_views'] / $summary['unique_ips'], 1) : 0;

        echo json_encode([
            'success' => true, 
            'data' => $dailyStats,
            'summary' => $summary
        ]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

/**
 * Handle Upload & Form Submission
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // CREATE / UPLOAD
    if ($action === 'create') {
        $title = trim($_POST['title']);
        $link = trim($_POST['link_url']);
        $start = !empty($_POST['start_date']) ? $_POST['start_date'] : date('Y-m-d H:i:s');
        $end = !empty($_POST['end_date']) ? $_POST['end_date'] : date('Y-m-d H:i:s', strtotime('+1 month'));
        
        // Handle File Upload
        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
            $fileTmp = $_FILES['banner_image']['tmp_name'];
            $fileName = $_FILES['banner_image']['name'];
            $fileSize = $_FILES['banner_image']['size'];
            $fileType = $_FILES['banner_image']['type'];
            
            // Validate Extension
            $allowedExts = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'];
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            
            if (!in_array($ext, $allowedExts)) {
                $error = "Extension non autorisée. Seuls PNG, JPEG, GIF, SVG, WebP sont acceptés.";
            } elseif ($fileSize > 2 * 1024 * 1024) { // 2MB max
                $error = "Fichier trop volumineux (Max 2MB).";
            } else {
                // Move File
                $uploadDir = '../uploads/ads/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                
                $newFileName = uniqid('ad_') . '.' . $ext;
                $destPath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($fileTmp, $destPath)) {
                    // Save to DB
                    // Path stored should be relative to license-server root for API access
                    $dbPath = 'uploads/ads/' . $newFileName; 
                    $placement = $_POST['placement'] ?? 'dashboard_hero';
                    $tenantId = !empty($_POST['tenant_id']) ? (int)$_POST['tenant_id'] : null;
                    $maxViews = !empty($_POST['max_views']) ? (int)$_POST['max_views'] : null;
                    $useSmartAlgo = isset($_POST['use_smart_algo']) ? 1 : 0;
                    // Legacy freq cap: kept for manual control if smart algo is OFF
                    $freqCap = 24; 
                    
                    $stmt = $pdo->prepare("INSERT INTO server_ads (title, image_path, link_url, start_date, end_date, placement, tenant_id, max_views, frequency_cap_hours, use_smart_algo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$title, $dbPath, $link, $start, $end, $placement, $tenantId, $maxViews, $freqCap, $useSmartAlgo]);
                    $message = "Publicité créée avec succès.";
                } else {
                    $error = "Erreur lors de l'upload du fichier.";
                }
            }
        } else {
            $error = "Veuillez sélectionner une image.";
        }
    }

    // UPDATE STATUS
    if ($action === 'toggle_status') {
        $id = $_POST['id'];
        $current = (int)$_POST['current_status'];
        $new = $current ? 0 : 1;
        $pdo->prepare("UPDATE server_ads SET is_active = ? WHERE id = ?")->execute([$new, $id]);
        $message = "Statut mis à jour.";
    }

    // DELETE
    if ($action === 'delete') {
        $id = $_POST['id'];
        // Get path to delete file
        $stmt = $pdo->prepare("SELECT image_path FROM server_ads WHERE id = ?");
        $stmt->execute([$id]);
        $ad = $stmt->fetch();
        
        if ($ad) {
            $filePath = '../' . $ad['image_path'];
            if (file_exists($filePath)) unlink($filePath);
            
            $pdo->prepare("DELETE FROM server_ads WHERE id = ?")->execute([$id]);
            $message = "Publicité supprimée.";
        }
    }
    
    // UPDATE (EDIT)
    if ($action === 'update') {
        $id = (int)$_POST['id'];
        $title = trim($_POST['title']);
        $link = trim($_POST['link_url']);
        $start = !empty($_POST['start_date']) ? $_POST['start_date'] : date('Y-m-d H:i:s');
        $end = !empty($_POST['end_date']) ? $_POST['end_date'] : date('Y-m-d H:i:s', strtotime('+1 month'));
        $placement = $_POST['placement'] ?? 'dashboard_hero';
        $tenantId = !empty($_POST['tenant_id']) ? (int)$_POST['tenant_id'] : null;
        $maxViews = !empty($_POST['max_views']) ? (int)$_POST['max_views'] : null;
        $useSmartAlgo = isset($_POST['use_smart_algo']) ? 1 : 0;
        
        // Check if new image uploaded
        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
            $fileTmp = $_FILES['banner_image']['tmp_name'];
            $fileName = $_FILES['banner_image']['name'];
            $fileSize = $_FILES['banner_image']['size'];
            
            $allowedExts = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'];
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            
            if (!in_array($ext, $allowedExts)) {
                $error = "Extension non autorisée. Seuls PNG, JPEG, GIF, SVG, WebP sont acceptés.";
            } elseif ($fileSize > 2 * 1024 * 1024) {
                $error = "Fichier trop volumineux (Max 2MB).";
            } else {
                // Delete old image
                $stmt = $pdo->prepare("SELECT image_path FROM server_ads WHERE id = ?");
                $stmt->execute([$id]);
                $oldAd = $stmt->fetch();
                if ($oldAd && file_exists('../' . $oldAd['image_path'])) {
                    unlink('../' . $oldAd['image_path']);
                }
                
                // Upload new image
                $uploadDir = '../uploads/ads/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
                $newFileName = uniqid('ad_') . '.' . $ext;
                $destPath = $uploadDir . $newFileName;
                
                if (move_uploaded_file($fileTmp, $destPath)) {
                    $dbPath = 'uploads/ads/' . $newFileName;
                    $stmt = $pdo->prepare("UPDATE server_ads SET title=?, image_path=?, link_url=?, start_date=?, end_date=?, placement=?, tenant_id=?, max_views=?, use_smart_algo=? WHERE id=?");
                    $stmt->execute([$title, $dbPath, $link, $start, $end, $placement, $tenantId, $maxViews, $useSmartAlgo, $id]);
                    $message = "Publicité mise à jour.";
                } else {
                    $error = "Erreur lors de l'upload.";
                }
            }
        } else {
            // Update without changing image
            $stmt = $pdo->prepare("UPDATE server_ads SET title=?, link_url=?, start_date=?, end_date=?, placement=?, tenant_id=?, max_views=?, use_smart_algo=? WHERE id=?");
            $stmt->execute([$title, $link, $start, $end, $placement, $tenantId, $maxViews, $useSmartAlgo, $id]);
            $message = "Publicité mise à jour.";
        }
    }
}

// Fetch Ads
$ads = $pdo->query("SELECT * FROM server_ads ORDER BY created_at DESC")->fetchAll();
$currentPage = 'advertising';
$pageTitle = 'Publicité - Admin License';
?>
<?php include 'includes/header.php'; ?>

    <!-- Sidebar -->
    <?php include 'includes/sidebar.php'; ?>
    
    <!-- Main Content -->
    <div class="ml-64 p-8">
        <div class="max-w-6xl mx-auto">
            
            <!-- Header -->
            <div class="flex justify-between items-center mb-8">
                <div>
                    <h1 class="text-2xl font-bold text-slate-800">Gestion Publicité</h1>
                    <p class="text-slate-500 text-sm">Diffusez des annonces sur les dashboards clients</p>
                </div>
                <div class="flex gap-3">
                    <a href="ad_analytics.php" 
                        class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white px-4 py-2 rounded-lg hover:opacity-90 transition flex items-center gap-2 text-sm font-medium shadow-sm">
                        <i class="fa-solid fa-chart-pie"></i> Analytics
                    </a>
                    <button onclick="document.getElementById('createModal').classList.remove('hidden')" 
                        class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition flex items-center gap-2 text-sm font-medium shadow-sm">
                        <i class="fa-solid fa-plus"></i> Nouvelle Pub
                    </button>
                </div>
            </div>

            <!-- Messages -->
            <?php if ($message): ?>
                <div class="mb-6 p-4 bg-emerald-50 border border-emerald-200 text-emerald-700 rounded-lg flex items-center gap-3 animate-fade-in">
                    <i class="fa-solid fa-check-circle text-lg"></i>
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="mb-6 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg flex items-center gap-3 animate-fade-in">
                    <i class="fa-solid fa-circle-exclamation text-lg"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <!-- Ads Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <!-- Info Card -->
                <div class="col-span-1 md:col-span-2 lg:col-span-3 bg-blue-50 border border-blue-100 rounded-xl p-6">
                    <div class="flex items-start gap-4 mb-4">
                        <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center text-blue-600 shrink-0">
                            <i class="fa-solid fa-circle-info"></i>
                        </div>
                        <div>
                            <h3 class="font-bold text-blue-900">Zones d'affichage disponibles</h3>
                            <p class="text-sm text-blue-700 mt-1">Formats acceptés : <strong>PNG, JPEG, GIF, SVG, WebP</strong> (max 2MB)</p>
                        </div>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-3 text-[10px]">
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-house mr-1"></i> Dashboard</div>
                            <div class="text-blue-600">1200 x 200 px</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-table-columns mr-1"></i> Sidebar</div>
                            <div class="text-blue-600">300 x 250 px</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-right-to-bracket mr-1"></i> Login</div>
                            <div class="text-blue-600">400 x 300 px</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-globe mr-1"></i> Pop-up</div>
                            <div class="text-blue-600">Plein Écran</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-users mr-1"></i> Header RH</div>
                            <div class="text-blue-600">100% x 80</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-calendar mr-1"></i> Calendrier</div>
                            <div class="text-blue-600">260 x 180</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-print mr-1"></i> Print</div>
                            <div class="text-blue-600">100% x 40</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-shoe-prints mr-1"></i> Foot Dash</div>
                            <div class="text-blue-600">100% x 100</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-puzzle-piece mr-1"></i> Discovery</div>
                            <div class="text-blue-600">Native</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-hand-holding-hand mr-1"></i> Welcome</div>
                            <div class="text-blue-600">100% x 60</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-user-gear mr-1"></i> Profil</div>
                            <div class="text-blue-600">100% x 60</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-check-double mr-1"></i> Todo</div>
                            <div class="text-blue-600">Native</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-ban mr-1"></i> 404 Error</div>
                            <div class="text-blue-600">400 x 300</div>
                        </div>
                        <div class="bg-white/60 rounded-lg p-2 border border-blue-100">
                            <div class="font-bold text-blue-800 mb-1 truncate"><i class="fa-solid fa-stopwatch mr-1"></i> Timeout</div>
                            <div class="text-blue-600">500 x 400</div>
                        </div>
                    </div>
                </div>

                <?php foreach ($ads as $ad): ?>
                    <?php 
                        // Define height classes based on placement for proper aspect ratio preview
                        $placement = $ad['placement'] ?? 'dashboard_hero';
                        $heightClass = match($placement) {
                            'dashboard_hero' => 'h-[100px]',    
                            'dashboard_sidebar' => 'h-[150px]', 
                            'dashboard_footer' => 'h-[60px]',
                            'module_discovery' => 'h-[120px]',
                            'login_page' => 'h-[135px]',        
                            'login_welcome' => 'h-[40px]',
                            'global_banner' => 'h-[180px]',      
                            'employees_header' => 'h-[50px]',
                            'calendar_widget' => 'h-[110px]',
                            'profile_actions' => 'h-[40px]',
                            'todo_suggestion' => 'h-[130px]',
                            '404_recovery' => 'h-[135px]',
                            'session_timeout' => 'h-[160px]',
                            'print_sponsor' => 'h-[30px]',
                            default => 'h-32'
                        };
                    ?>
                    <div class="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden group hover:shadow-md transition-shadow">
                        <!-- Image Preview -->
                        <div class="<?= $heightClass ?> bg-slate-100 relative overflow-hidden flex items-center justify-center">
                            <?php 
                                $ext = strtolower(pathinfo($ad['image_path'], PATHINFO_EXTENSION));
                                $isImg = in_array($ext, ['jpg','jpeg','png','gif','svg','webp']);
                            ?>
                            <?php if($isImg): ?>
                                <img src="../<?= $ad['image_path'] ?>" class="w-full h-full object-cover">
                            <?php else: ?>
                                <i class="fa-solid fa-file text-slate-300 text-4xl"></i>
                            <?php endif; ?>
                            
                            <!-- Status Badge -->
                            <div class="absolute top-3 right-3">
                                <form method="POST">
                                    <input type="hidden" name="action" value="toggle_status">
                                    <input type="hidden" name="id" value="<?= $ad['id'] ?>">
                                    <input type="hidden" name="current_status" value="<?= $ad['is_active'] ?>">
                                    <button type="submit" class="px-2 py-1 rounded-full text-xs font-bold shadow-sm transition-colors <?= $ad['is_active'] ? 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' : 'bg-slate-100 text-slate-500 hover:bg-slate-200' ?>">
                                        <?= $ad['is_active'] ? 'ACTIF' : 'INACTIF' ?>
                                    </button>
                                </form>
                            </div>
                        </div>

                        <!-- Content -->
                        <div class="p-4">
                            <div class="flex justify-between items-start mb-2">
                                <h3 class="font-bold text-slate-800 truncate" title="<?= htmlspecialchars($ad['title']) ?>">
                                    <?= htmlspecialchars($ad['title']) ?>
                                </h3>
                                <div class="flex gap-2">
                                    <div class="text-xs text-slate-400 flex items-center gap-1" title="Vues">
                                        <i class="fa-solid fa-eye"></i> <?= $ad['views'] ?>
                                    </div>
                                    <div class="text-xs text-slate-400 flex items-center gap-1" title="Clics">
                                        <i class="fa-solid fa-mouse-pointer"></i> <?= $ad['clicks'] ?>
                                    </div>
                                    <?php 
                                        $ctr = $ad['views'] > 0 ? round(($ad['clicks'] / $ad['views']) * 100, 1) : 0;
                                        $ctrColor = $ctr > 2 ? 'emerald' : ($ctr > 0.5 ? 'indigo' : 'slate');
                                    ?>
                                    <div class="text-[10px] font-bold bg-<?= $ctrColor ?>-100 text-<?= $ctrColor ?>-700 px-1.5 py-0.5 rounded" title="CTR (Taux de clic)">
                                        <?= $ctr ?>%
                                    </div>
                                </div>
                            </div>
                            
                            <div class="flex items-center gap-2 mb-3">
                                <?php 
                                    $zoneLabels = [
                                        'dashboard_hero' => ['Dashboard Hero', 'indigo'],
                                        'dashboard_sidebar' => ['Sidebar Widget', 'purple'],
                                        'dashboard_footer' => ['Dashboard Footer', 'blue'],
                                        'module_discovery' => ['Module Native', 'violet'],
                                        'login_page' => ['Login Sidebar', 'amber'],
                                        'login_welcome' => ['Login Welcome', 'orange'],
                                        'global_banner' => ['Global Pop-up', 'emerald'],
                                        'employees_header' => ['Employés Header', 'cyan'],
                                        'calendar_widget' => ['Calendrier Widget', 'teal'],
                                        'profile_actions' => ['Profil Actions', 'sky'],
                                        'todo_suggestion' => ['Todo Native', 'lime'],
                                        '404_recovery' => ['404 Error', 'rose'],
                                        'session_timeout' => ['Session Timeout', 'red'],
                                        'print_sponsor' => ['Print Footer', 'slate']
                                    ];
                                    $zone = $ad['placement'] ?? 'dashboard_hero';
                                    $zl = $zoneLabels[$zone] ?? ['Inconnu', 'slate'];
                                    
                                    // Get tenant name if targeted
                                    $clientName = 'Global';
                                    if (!empty($ad['tenant_id'])) {
                                        foreach ($tenants as $t) {
                                            if ($t['id'] == $ad['tenant_id']) {
                                                $clientName = $t['name'];
                                                break;
                                            }
                                        }
                                    }
                                ?>
                                <span class="text-[10px] font-bold uppercase px-2 py-0.5 rounded-full bg-<?= $zl[1] ?>-100 text-<?= $zl[1] ?>-700">
                                    <?= $zl[0] ?>
                                </span>
                                <?php if ($clientName !== 'Global'): ?>
                                    <span class="text-[10px] font-bold uppercase px-2 py-0.5 rounded-full bg-sky-100 text-sky-700" title="Client ciblé">
                                        <i class="fa-solid fa-building mr-0.5"></i><?= htmlspecialchars($clientName) ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-[10px] font-bold uppercase px-2 py-0.5 rounded-full bg-slate-100 text-slate-500">
                                        🌍 Global
                                    </span>
                                <?php endif; ?>
                                <span class="text-xs text-slate-400 flex items-center gap-1">
                                    <i class="fa-solid fa-calendar text-slate-300"></i>
                                    <?= date('d M', strtotime($ad['start_date'])) ?> - <?= date('d M', strtotime($ad['end_date'])) ?>
                                </span>
                            </div>

                            <div class="flex justify-between items-center pt-3 border-t border-slate-50">
                                <?php if($ad['link_url']): ?>
                                    <a href="<?= htmlspecialchars($ad['link_url']) ?>" target="_blank" class="text-xs text-indigo-600 hover:underline flex items-center gap-1">
                                        <i class="fa-solid fa-external-link-alt"></i> Lien
                                    </a>
                                <?php else: ?>
                                    <span class="text-xs text-slate-400">Sans lien</span>
                                <?php endif; ?>

                                <div class="flex gap-3">
                                    <button type="button" onclick="openStatsModal(<?= $ad['id'] ?>, '<?= htmlspecialchars(addslashes($ad['title'])) ?>')" 
                                        class="text-indigo-500 hover:text-indigo-700 text-xs font-medium flex items-center gap-1 transition-colors">
                                        <i class="fa-solid fa-chart-line"></i> Stats
                                    </button>
                                    <button type="button" onclick="openEditModal(<?= htmlspecialchars(json_encode($ad)) ?>)" 
                                        class="text-amber-500 hover:text-amber-700 text-xs font-medium flex items-center gap-1 transition-colors">
                                        <i class="fa-solid fa-pen"></i> Éditer
                                    </button>
                                    <form method="POST" onsubmit="return confirm('Supprimer cette publicité ?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $ad['id'] ?>">
                                        <button type="submit" class="text-rose-500 hover:text-rose-700 text-xs font-medium flex items-center gap-1 transition-colors">
                                            <i class="fa-solid fa-trash"></i> Supprimer
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

        </div>
    </div>

    <!-- Create Modal -->
    <div id="createModal" class="fixed inset-0 bg-slate-900/50 hidden z-50 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 overflow-hidden animate-slide-up">
            <div class="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50">
                <h3 class="font-bold text-slate-800">Nouvelle Publicité</h3>
                <button onclick="document.getElementById('createModal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600">
                    <i class="fa-solid fa-xmark text-xl"></i>
                </button>
            </div>
            
            <form method="POST" enctype="multipart/form-data" class="p-6 space-y-4">
                <input type="hidden" name="action" value="create">
                
                <!-- Title -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Titre de la campagne</label>
                    <input type="text" name="title" required class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm">
                </div>

                <!-- Image Upload with Preview -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Bannière (PNG, JPG, GIF, SVG)</label>
                    <div class="border-2 border-dashed border-slate-300 rounded-xl p-6 text-center hover:bg-slate-50 transition-colors cursor-pointer relative group" onclick="document.getElementById('bannerInput').click()">
                        <input type="file" id="bannerInput" name="banner_image" accept=".png,.jpg,.jpeg,.gif,.svg" class="hidden" required onchange="previewImage(this)">
                        
                        <div id="uploadPlaceholder" class="space-y-2">
                            <div class="w-12 h-12 bg-indigo-50 text-indigo-500 rounded-full flex items-center justify-center mx-auto group-hover:scale-110 transition-transform">
                                <i class="fa-solid fa-cloud-arrow-up text-xl"></i>
                            </div>
                            <p class="text-sm text-slate-600 font-medium">Cliquez pour uploader une image</p>
                            <p class="text-xs text-slate-400">Max 2MB</p>
                        </div>
                        
                        <img id="imagePreview" class="hidden w-full h-32 object-contain rounded-lg shadow-sm border border-slate-200">
                    </div>
                </div>

                <!-- Link -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Lien de redirection (Optionnel)</label>
                    <div class="relative">
                        <i class="fa-solid fa-link absolute left-3 top-2.5 text-slate-400 text-xs"></i>
                        <input type="url" name="link_url" placeholder="https://..." class="w-full pl-8 pr-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                </div>

                <!-- Zone Selector -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Zone d'affichage</label>
                    <select name="placement" id="placementSelect" onchange="updateSizeHint()" 
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm bg-white">
                        <option value="dashboard_hero">🏠 Dashboard Principal (1200x200 px)</option>
                        <option value="dashboard_sidebar">📊 Sidebar Widget (300x250 px)</option>
                        <option value="dashboard_footer">🦶 Dashboard Footer (100% x 100 px)</option>
                        <option value="module_discovery">🧩 Module Discovery (Native Card)</option>
                        <option value="login_page">🔐 Login Sidebar (400x300 px)</option>
                        <option value="login_welcome">👋 Login Welcome (100% x 60 px)</option>
                        <option value="global_banner">🌐 Global Pop-up (Plein Écran)</option>
                        <option value="employees_header">👥 Employés Header (100% x 80 px)</option>
                        <option value="calendar_widget">📅 Calendrier Widget (260x180 px)</option>
                        <option value="profile_actions">👤 Profil Actions (100% x 60 px)</option>
                        <option value="todo_suggestion">✅ Todo Native (Native Card)</option>
                        <option value="404_recovery">🚫 404 Recovery (400x300 px)</option>
                        <option value="session_timeout">⏱️ Session Timeout (500x400 px)</option>
                        <option value="print_sponsor">🖨️ Print Footer (100% x 40 px)</option>
                    </select>
                    <p id="sizeHint" class="text-xs text-indigo-600 mt-1 font-medium">Taille recommandée : 1200 x 200 pixels</p>
                </div>

                <!-- Dates -->
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Début</label>
                        <input type="datetime-local" name="start_date" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Fin</label>
                        <input type="datetime-local" name="end_date" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm">
                    </div>
                </div>

                <!-- Client/Tenant Selector -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Client Cible</label>
                    <select name="tenant_id" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm bg-white">
                        <option value="">🌍 Tous les Clients (Global)</option>
                        <?php foreach ($tenants as $t): ?>
                            <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="text-xs text-slate-400 mt-1">Laisser "Global" pour afficher sur tous les ERP clients</p>
                </div>

                <!-- 📊 Impression Controls -->
                <div class="grid grid-cols-2 gap-4 pt-2 border-t border-slate-100">
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">
                            <i class="fa-solid fa-eye text-indigo-400 mr-1"></i>Max Impressions
                        </label>
                        <input type="number" name="max_views" min="0" value="0" placeholder="0 = Illimité"
                            class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 text-sm">
                        <p class="text-xs text-slate-400 mt-1">0 = Illimité</p>
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">
                            <i class="fa-solid fa-brain text-purple-500 mr-1"></i>Optimisation IA
                        </label>
                        <div class="flex items-center gap-3 mt-2">
                             <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="use_smart_algo" class="sr-only peer" checked>
                                <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                                <span class="ml-3 text-sm font-medium text-slate-700">Algorithme Intelligent</span>
                            </label>
                        </div>
                        <p class="text-[10px] text-slate-400 mt-1">Gère la fréquence automatiquement pour éviter la saturation</p>
                    </div>
                </div>

                <div class="pt-4 flex justify-end gap-3">
                    <button type="button" onclick="document.getElementById('createModal').classList.add('hidden')" class="px-4 py-2 text-slate-600 font-medium hover:bg-slate-100 rounded-lg transition-colors text-sm">Annuler</button>
                    <button type="submit" class="px-6 py-2 bg-indigo-600 text-white font-bold rounded-lg hover:bg-indigo-700 transition-colors shadow-lg shadow-indigo-200 text-sm">Créer la Campagne</button>
                </div>
            </form>
        </div>
    </div>


    <!-- Edit Modal -->
    <div id="editModal" class="fixed inset-0 bg-slate-900/50 hidden z-50 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-lg mx-4 overflow-hidden max-h-[90vh] overflow-y-auto">
            <div class="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-amber-50">
                <h3 class="font-bold text-slate-800"><i class="fa-solid fa-pen mr-2 text-amber-500"></i>Modifier la Publicité</h3>
                <button onclick="closeEditModal()" class="text-slate-400 hover:text-slate-600">
                    <i class="fa-solid fa-xmark text-xl"></i>
                </button>
            </div>
            
            <form method="POST" enctype="multipart/form-data" class="p-6 space-y-4">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" id="edit_id">
                
                <!-- Title -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Titre</label>
                    <input type="text" name="title" id="edit_title" required class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm">
                </div>
                
                <!-- Current Image + New Upload -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Image actuelle</label>
                    <div class="mb-2 bg-slate-100 rounded-lg p-2 flex items-center justify-center h-24">
                        <img id="edit_current_image" class="max-h-full max-w-full object-contain rounded">
                    </div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Nouvelle image (optionnel)</label>
                    <input type="file" name="banner_image" accept=".png,.jpg,.jpeg,.gif,.svg" class="w-full text-xs border border-slate-300 rounded-lg p-2">
                </div>
                
                <!-- Link -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Lien (Optionnel)</label>
                    <input type="url" name="link_url" id="edit_link_url" placeholder="https://..." class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm">
                </div>
                
                <!-- Zone -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Zone d'affichage</label>
                    <select name="placement" id="edit_placement" onchange="updateSizeHintEdit()" 
                        class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm bg-white">
                        <option value="dashboard_hero">🏠 Dashboard Principal (1200x200 px)</option>
                        <option value="dashboard_sidebar">📊 Sidebar Widget (300x250 px)</option>
                        <option value="dashboard_footer">🦶 Dashboard Footer (100% x 100 px)</option>
                        <option value="module_discovery">🧩 Module Discovery (Native Card)</option>
                        <option value="login_page">🔐 Login Sidebar (400x300 px)</option>
                        <option value="login_welcome">👋 Login Welcome (100% x 60 px)</option>
                        <option value="global_banner">🌐 Global Pop-up (Plein Écran)</option>
                        <option value="employees_header">👥 Employés Header (100% x 80 px)</option>
                        <option value="calendar_widget">📅 Calendrier Widget (260x180 px)</option>
                        <option value="profile_actions">👤 Profil Actions (100% x 60 px)</option>
                        <option value="todo_suggestion">✅ Todo Native (Native Card)</option>
                        <option value="404_recovery">🚫 404 Recovery (400x300 px)</option>
                        <option value="session_timeout">⏱️ Session Timeout (500x400 px)</option>
                        <option value="print_sponsor">🖨️ Print Footer (100% x 40 px)</option>
                    </select>
                    <p id="sizeHintEdit" class="text-xs text-amber-600 mt-1 font-medium">Taille recommandée : 1200 x 200 pixels</p>
                </div>
                
                <!-- Client -->
                <div>
                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Client Cible</label>
                    <select name="tenant_id" id="edit_tenant_id" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm bg-white">
                        <option value="">🌍 Tous les Clients (Global)</option>
                        <?php foreach ($tenants as $t): ?>
                            <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Dates -->
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Début</label>
                        <input type="datetime-local" name="start_date" id="edit_start_date" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Fin</label>
                        <input type="datetime-local" name="end_date" id="edit_end_date" class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm">
                    </div>
                </div>
                
                <!-- 📊 Impression Controls -->
                <div class="grid grid-cols-2 gap-4 pt-2 border-t border-slate-100">
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">
                            <i class="fa-solid fa-eye text-amber-400 mr-1"></i>Max Impressions
                        </label>
                        <input type="number" name="max_views" id="edit_max_views" min="0" placeholder="0 = Illimité"
                            class="w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-amber-500 text-sm">
                        <p class="text-xs text-slate-400 mt-1">0 = Illimité</p>
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-500 uppercase mb-1">
                            <i class="fa-solid fa-brain text-purple-500 mr-1"></i>Optimisation IA
                        </label>
                        <div class="flex items-center gap-3 mt-2">
                             <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="use_smart_algo" id="edit_use_smart_algo" class="sr-only peer">
                                <div class="w-11 h-6 bg-slate-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                                <span class="ml-3 text-sm font-medium text-slate-700">Activer</span>
                            </label>
                        </div>
                    </div>
                </div>
                
                <div class="pt-4 flex justify-end gap-3">
                    <button type="button" onclick="closeEditModal()" class="px-4 py-2 text-slate-600 font-medium hover:bg-slate-100 rounded-lg transition-colors text-sm">Annuler</button>
                    <button type="submit" class="px-6 py-2 bg-amber-500 text-white font-bold rounded-lg hover:bg-amber-600 transition-colors shadow-lg shadow-amber-200 text-sm">Enregistrer</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Stats Modal -->
    <div id="statsModal" class="fixed inset-0 bg-slate-900/50 hidden z-50 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-2xl shadow-xl w-full max-w-3xl mx-4 overflow-hidden animate-slide-up max-h-[85vh] flex flex-col">
            <div class="px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-indigo-50">
                <div>
                    <h3 class="font-bold text-slate-800"><i class="fa-solid fa-chart-pie mr-2 text-indigo-500"></i>Statistiques Détaillées</h3>
                    <p id="statsTitle" class="text-xs text-indigo-600 font-medium"></p>
                </div>
                <button onclick="document.getElementById('statsModal').classList.add('hidden')" class="text-slate-400 hover:text-slate-600">
                    <i class="fa-solid fa-xmark text-xl"></i>
                </button>
            </div>
            
            <div class="p-6 bg-white border-b border-slate-100 grid grid-cols-4 gap-4">
                <div class="bg-indigo-50 rounded-xl p-4 text-center border border-indigo-100">
                    <p class="text-xs font-bold text-indigo-400 uppercase tracking-wide">Vues Totales</p>
                    <p id="summaryViews" class="text-2xl font-black text-indigo-700 mt-1">-</p>
                </div>
                <div class="bg-emerald-50 rounded-xl p-4 text-center border border-emerald-100">
                    <p class="text-xs font-bold text-emerald-500 uppercase tracking-wide">Public Unique</p>
                    <p id="summaryUniques" class="text-2xl font-black text-emerald-700 mt-1">-</p>
                </div>
                <div class="bg-amber-50 rounded-xl p-4 text-center border border-amber-100">
                    <p class="text-xs font-bold text-amber-500 uppercase tracking-wide">Répétition</p>
                    <p id="summaryFreq" class="text-2xl font-black text-amber-700 mt-1">-</p>
                </div>
                <div class="bg-rose-50 rounded-xl p-4 text-center border border-rose-100">
                    <p class="text-xs font-bold text-rose-500 uppercase tracking-wide">Efficacité (CTR)</p>
                    <p id="summaryCTR" class="text-2xl font-black text-rose-700 mt-1">-</p>
                </div>
            </div>

            <div class="p-0 overflow-y-auto flex-1">
                <table class="w-full text-sm text-left">
                    <thead class="bg-slate-50 text-slate-500 uppercase font-bold text-xs sticky top-0">
                        <tr>
                            <th class="px-6 py-3 border-b border-slate-200">Date</th>
                            <th class="px-6 py-3 border-b border-slate-200 text-center">Vues</th>
                            <th class="px-6 py-3 border-b border-slate-200 text-center">Uniques</th>
                            <th class="px-6 py-3 border-b border-slate-200 text-center">Clics</th>
                            <th class="px-6 py-3 border-b border-slate-200 text-center">CTR</th>
                            <th class="px-6 py-3 border-b border-slate-200 text-right">Dernière Vue</th>
                        </tr>
                    </thead>
                    <tbody id="statsBody">
                        <!-- Filled by JS -->
                        <tr><td colspan="6" class="text-center py-8 text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-2"></i>Chargement...</td></tr>
                    </tbody>
                </table>
            </div>
            
            <div class="px-6 py-4 bg-slate-50 border-t border-slate-100 text-right">
                <button onclick="document.getElementById('statsModal').classList.add('hidden')" class="px-4 py-2 bg-indigo-600 text-white font-bold rounded-lg hover:bg-indigo-700 text-sm">Fermer</button>
            </div>
        </div>
    </div>

    <script>
        const RECOMMENDED_SIZES = {
            'dashboard_hero': '1200 x 200 pixels',
            'dashboard_sidebar': '300 x 250 pixels',
            'dashboard_footer': '100% largeur x 100px (Leaderboard)',
            'module_discovery': '300 x 200 pixels (Format Carte)',
            'login_page': '400 x 300 pixels',
            'login_welcome': '100% largeur x 60px',
            'global_banner': 'Plein Écran (Auto-adaptatif)',
            'employees_header': '100% largeur x 80px',
            'calendar_widget': '260 x 180 pixels',
            'profile_actions': '100% largeur x 60px',
            'todo_suggestion': 'Format Carte Adaptatif',
            '404_recovery': '400 x 300 pixels',
            'session_timeout': '500 x 400 pixels (Modal)',
            'print_sponsor': '100% largeur x 40px'
        };

        function previewImage(input) {
            const preview = document.getElementById('imagePreview');
            const placeholder = document.getElementById('uploadPlaceholder');
            if (input.files && input.files[0]) {
                const reader = new FileReader();
                reader.onload = e => {
                    preview.src = e.target.result;
                    preview.classList.remove('hidden');
                    placeholder.classList.add('hidden');
                }
                reader.readAsDataURL(input.files[0]);
            }
        }
        
        function updateSizeHint() {
            const select = document.getElementById('placementSelect');
            const hint = document.getElementById('sizeHint');
            hint.textContent = 'Taille recommandée : ' + (RECOMMENDED_SIZES[select.value] || '1200 x 200 pixels');
        }

        function updateSizeHintEdit() {
            const select = document.getElementById('edit_placement');
            const hint = document.getElementById('sizeHintEdit');
            hint.textContent = 'Taille recommandée : ' + (RECOMMENDED_SIZES[select.value] || '1200 x 200 pixels');
        }
        
        function openEditModal(ad) {
            document.getElementById('edit_id').value = ad.id;
            document.getElementById('edit_title').value = ad.title || '';
            document.getElementById('edit_link_url').value = ad.link_url || '';
            document.getElementById('edit_placement').value = ad.placement || 'dashboard_hero';
            document.getElementById('edit_tenant_id').value = ad.tenant_id || '';
            document.getElementById('edit_max_views').value = ad.max_views || 0;
            document.getElementById('edit_use_smart_algo').checked = (ad.use_smart_algo == 1);
            
            if (ad.start_date) document.getElementById('edit_start_date').value = ad.start_date.replace(' ', 'T').slice(0, 16);
            if (ad.end_date) document.getElementById('edit_end_date').value = ad.end_date.replace(' ', 'T').slice(0, 16);
            
            document.getElementById('edit_current_image').src = '../' + ad.image_path;
            updateSizeHintEdit();
            document.getElementById('editModal').classList.remove('hidden');
        }
        
        function closeEditModal() {
            document.getElementById('editModal').classList.add('hidden');
        }
        
        function openStatsModal(adId, adTitle) {
            document.getElementById('statsModal').classList.remove('hidden');
            document.getElementById('statsTitle').textContent = adTitle;
            document.getElementById('summaryViews').textContent = '-';
            document.getElementById('summaryUniques').textContent = '-';
            document.getElementById('summaryFreq').textContent = '-';
            document.getElementById('summaryCTR').textContent = '-';
            const tbody = document.getElementById('statsBody');
            tbody.innerHTML = '<tr><td colspan="6" class="text-center py-8 text-slate-400"><i class="fa-solid fa-spinner fa-spin mr-2"></i>Chargement...</td></tr>';
            
            fetch('?action=get_stats&id=' + adId)
                .then(r => r.json())
                .then(result => {
                    if (result.success) {
                        document.getElementById('summaryViews').textContent = result.summary.total_views.toLocaleString();
                        document.getElementById('summaryUniques').textContent = result.summary.unique_ips.toLocaleString();
                        document.getElementById('summaryFreq').textContent = result.summary.avg_frequency + 'x';
                        
                        const globalCtr = result.summary.total_views > 0 ? ((result.summary.total_clicks / result.summary.total_views) * 100).toFixed(1) : 0;
                        document.getElementById('summaryCTR').textContent = globalCtr + '%';

                        if (result.data.length === 0) {
                            tbody.innerHTML = '<tr><td colspan="6" class="text-center py-8 text-slate-400">Aucune donnée.</td></tr>';
                            return;
                        }
                        let html = '';
                        result.data.forEach(row => {
                            const dailyCtr = row.total_views > 0 ? ((row.total_clicks / row.total_views) * 100).toFixed(1) : 0;
                            const lastSeen = row.last_seen ? row.last_seen.split(' ')[1].slice(0,5) : '-';
                            html += `<tr class="border-b border-slate-100 hover:bg-slate-50 transition-colors">
                                <td class="px-6 py-3 font-medium text-slate-700">${new Date(row.date).toLocaleDateString('fr-FR')}</td>
                                <td class="px-6 py-3 text-center"><span class="bg-indigo-100 text-indigo-700 px-2 py-1 rounded-full text-xs font-bold">${row.total_views}</span></td>
                                <td class="px-6 py-3 text-center"><span class="bg-emerald-100 text-emerald-700 px-2 py-1 rounded-full text-xs font-bold">${row.unique_ips}</span></td>
                                <td class="px-6 py-3 text-center font-bold text-slate-600">${row.total_clicks}</td>
                                <td class="px-6 py-3 text-center"><span class="font-bold text-indigo-600">${dailyCtr}%</span></td>
                                <td class="px-6 py-3 text-right text-xs text-slate-500 font-mono">${lastSeen}</td>
                            </tr>`;
                        });
                        tbody.innerHTML = html;
                    } else {
                        tbody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-red-500">Erreur : ' + result.error + '</td></tr>';
                    }
                })
                .catch(e => {
                    tbody.innerHTML = '<tr><td colspan="5" class="text-center py-4 text-red-500">Erreur réseau</td></tr>';
                });
        }
    </script>


</body>
</html>
