<?php
/**
 * API: Get Active Advertisements
 * Returns JSON array of active ads
 * 
 * Query Parameters:
 *  - zone: Filter by placement zone (dashboard_hero, dashboard_sidebar, login_page, global_banner)
 *  - tenant_id: Show ads for this tenant + global ads (NULL tenant_id)
 * 
 * Tracks unique views by IP (same IP won't increment view count twice)
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once '../config.php';

// Get client IP address
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';
}

try {
    if (!isset($pdo)) {
        throw new Exception("Database connection failed");
    }

    $zone = $_GET['zone'] ?? null;
    $tenantId = isset($_GET['tenant_id']) ? (int)$_GET['tenant_id'] : null;
    $clientIP = getClientIP();
    
    $sql = "
        SELECT id, title, image_path, link_url, placement, max_views, frequency_cap_hours, use_smart_algo 
        FROM server_ads 
        WHERE is_active = 1 
          AND start_date <= NOW() 
          AND end_date >= NOW()
          AND (max_views IS NULL OR max_views = 0 OR views < max_views)
    ";
    
    $params = [];
    
    if ($zone) {
        $sql .= " AND placement = ?";
        $params[] = $zone;
    }
    
    if ($tenantId) {
        $sql .= " AND (tenant_id IS NULL OR tenant_id = ?)";
        $params[] = $tenantId;
    } else {
        $sql .= " AND tenant_id IS NULL";
    }
    
    $sql .= " ORDER BY RAND()";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $ads = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // DEBUG LOGGING
    $debugLog = '../debug_ads.log';
    $logMsg = date('[Y-m-d H:i:s] ') . "IP: $clientIP | Zone: " . ($zone ?? 'ALL') . "\n";
    
    // Apply filtering logic (Smart Algo or Legacy Frequency Cap)
    $filteredAds = [];
    foreach ($ads as $ad) {
        $useSmartAlgo = (bool)($ad['use_smart_algo'] ?? 0);
        $freqCapHours = (int)($ad['frequency_cap_hours'] ?? 0);
        
        $logMsg .= "  > Check Ad #{$ad['id']} ({$ad['title']}) - Smart: " . ($useSmartAlgo ? 'ON' : 'OFF') . "\n";
        
        // --- SMART ALGORITHM LOGIC ---
        if ($useSmartAlgo) {
             try {
                /* 
                // [DEACTIVATED] User requested normal repetition
                // 1. Hard Anti-Spam: Block if seen in last 5 minutes
                $spamSql = "SELECT COUNT(*) FROM server_ads_stats 
                        WHERE ad_id = ? AND ip_address = ? AND action_type = 'view'
                        AND viewed_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)";
                
                $spamStmt = $pdo->prepare($spamSql);
                $spamStmt->execute([$ad['id'], $clientIP]);
                
                if ($spamStmt->fetchColumn() > 0) {
                    $logMsg .= "    -> BLOCKED (Smart Algo: Anti-Spam 5min)\n";
                    continue; // Skip this ad
                }
                
                // 2. Probabilistic Decay based on views in last 24h
                $decaySql = "SELECT COUNT(*) FROM server_ads_stats 
                        WHERE ad_id = ? AND ip_address = ? AND action_type = 'view'
                        AND viewed_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)";
                
                $decayStmt = $pdo->prepare($decaySql);
                $decayStmt->execute([$ad['id'], $clientIP]);
                $viewsToday = (int)$decayStmt->fetchColumn();
                
                $probability = 100;
                if ($viewsToday == 0) $probability = 100;
                elseif ($viewsToday <= 2) $probability = 60;
                elseif ($viewsToday <= 5) $probability = 30;
                else $probability = 10;
                
                $diceRoll = rand(1, 100);
                if ($diceRoll <= $probability) {
                    $filteredAds[] = $ad;
                }
                */

                // Normal Repetition: Always allow
                $filteredAds[] = $ad;
                $logMsg .= "    -> ALLOWED (Smart Algo: Forced Repetition)\n";
                
            } catch (PDOException $e) {
                $filteredAds[] = $ad;
                $logMsg .= "    -> ERROR in Algo: " . $e->getMessage() . "\n";
            }
            continue;
        }
        
        // --- LEGACY FREQUENCY CAP LOGIC (Fallback) ---
        /*
        // [DEACTIVATED] User requested normal repetition
        if ($freqCapHours === 0) {
            $filteredAds[] = $ad;
            $logMsg .= "    -> ALLOWED (Legacy: No Cap)\n";
            continue;
        }
        
        try {
            $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)";
                    
            $checkStmt = $pdo->prepare($sql);
            $checkStmt->execute([$ad['id'], $clientIP]);
            $recentViews = $checkStmt->fetchColumn();
            
            if ($recentViews == 0) {
                $filteredAds[] = $ad;
            }
        } catch (PDOException $e) {
            $filteredAds[] = $ad;
        }
        */
        
        // Normal Repetition: Always allow
        $filteredAds[] = $ad;
        $logMsg .= "    -> ALLOWED (Legacy: Forced Repetition)\n";
    }
    
    $ads = $filteredAds;
    $logMsg .= "  => Final Ads Returned: " . count($ads) . "\n-----------------------------------\n";
    file_put_contents($debugLog, $logMsg, FILE_APPEND);

    // Determine base URL dynamically (Schema + Host + Path)
    $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http");
    $host = $_SERVER['HTTP_HOST'];
    
    // We are in /api/, so go up one level to find root
    // Example: /license-server/api/get_ads.php -> /license-server/
    // Example: /api/get_ads.php -> /
    $path = dirname(dirname($_SERVER['SCRIPT_NAME']));
    
    // Ensure trailing slash
    $baseUrl = rtrim($protocol . "://" . $host . $path, '/\\') . '/';
    foreach ($ads as &$ad) {
        $ad['image_url'] = $baseUrl . $ad['image_path'];
        unset($ad['image_path']);
        unset($ad['max_views']);
        unset($ad['frequency_cap_hours']);
        
        // Track view and increment total UNIQUE views
        try {
            // IGNORE if already exists (Unique constraint on ad_id, ip_address, action_type)
            // But use ON DUPLICATE KEY to update viewed_at for "Last Seen" KPI
            $trackStmt = $pdo->prepare("
                INSERT INTO server_ads_stats (ad_id, ip_address, action_type, viewed_at) 
                VALUES (?, ?, 'view', NOW())
                ON DUPLICATE KEY UPDATE viewed_at = NOW()
            ");
            $trackStmt->execute([$ad['id'], $clientIP]);
            
            // Increment total view count ONLY if it's a NEW record (Unique IP)
            if ($trackStmt->rowCount() === 1) {
                $pdo->prepare("UPDATE server_ads SET views = views + 1 WHERE id = ?")->execute([$ad['id']]);
            }
        } catch (PDOException $e) {
            // Fallback for missing stats table
            $pdo->prepare("UPDATE server_ads SET views = views + 1 WHERE id = ?")->execute([$ad['id']]);
        }
    }

    echo json_encode(['success' => true, 'ads' => $ads]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
