<?php
/**
 * Debug Logic for get_ads.php
 * Traces why an ad is passed or blocked
 */
require_once '../config.php';
header('Content-Type: text/html; charset=utf-8');

// 1. Get Client IP using SAME function as get_ads.php
function getClientIP() {
    $ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key])[0];
            if (filter_var(trim($ip), FILTER_VALIDATE_IP)) {
                return trim($ip);
            }
        }
    }
    return '0.0.0.0';
}

$clientIP = getClientIP();
echo "<h1>🕵️ Debug Logique API</h1>";
echo "<p><strong>Votre IP détectée :</strong> $clientIP</p>";

// 2. Fetch all active ads like get_ads.php
try {
    $sql = "SELECT id, title, frequency_cap_hours FROM server_ads WHERE is_active = 1";
    $ads = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h2>Analyse des Publicités Actives</h2>";
    
    if (count($ads) == 0) echo "<p class='error'>Aucune publicité active trouvée.</p>";
    
    foreach ($ads as $ad) {
        echo "<div style='background:#f4f4f4; padding:15px; margin-bottom:15px; border-left:5px solid #333;'>";
        echo "<h3>Publicité ID: {$ad['id']} - {$ad['title']}</h3>";
        
        $freqCapHours = (int)($ad['frequency_cap_hours'] ?? 0);
        echo "Config 'Délai Anti-Abus' (BDD) : <strong>$freqCapHours h</strong><br>";
        
        if ($freqCapHours === 0) {
            echo "<span style='color:orange'>⚠️ PAS DE FILTRAGE : Le délai est à 0 (Illimité)</span>";
            continue;
        }
        
        // Check stats
        $sql = "SELECT COUNT(*) FROM server_ads_stats 
                WHERE ad_id = ? AND ip_address = ? AND action_type = 'view'
                AND viewed_at > DATE_SUB(NOW(), INTERVAL $freqCapHours HOUR)";
                
        echo "<code style='display:block;background:#222;color:#eee;padding:10px;margin:5px 0;'>$sql</code>";
        echo "Paramètres: ID={$ad['id']}, IP=$clientIP<br>";
        
        $checkStmt = $pdo->prepare($sql);
        $checkStmt->execute([$ad['id'], $clientIP]);
        $recentViews = $checkStmt->fetchColumn();
        
        echo "Vues récentes trouvées : <strong>$recentViews</strong><br>";
        
        if ($recentViews > 0) {
            echo "<span style='color:green;font-weight:bold;'>✅ RÉSULTAT FILTER : BLOQUÉ (Correct)</span>";
        } else {
            echo "<span style='color:red;font-weight:bold;'>❌ RÉSULTAT FILTER : AUTORISÉ (S'affichera)</span>";
            
            // Check last view timestamp if any
            $lastView = $pdo->query("SELECT MAX(viewed_at) FROM server_ads_stats WHERE ad_id = {$ad['id']} AND ip_address = '$clientIP'")->fetchColumn();
            echo "<br>Dernière vue connue : " . ($lastView ? $lastView : "Aucune");
        }
        
        echo "</div>";
    }

} catch (PDOException $e) {
    echo "Erreur BDD: " . $e->getMessage();
}
