<?php
/**
 * API: Track Ad Click
 * Increments the click count for an ad (unique per IP)
 * 
 * Query Parameters:
 *  - id: Ad ID to track click for
 */
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 {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    
    if (!$id) {
        throw new Exception("Ad ID required");
    }
    
    $clientIP = getClientIP();
    
    // Track unique click by IP (INSERT IGNORE = skip if already exists)
    try {
        $trackStmt = $pdo->prepare("INSERT IGNORE INTO server_ads_stats (ad_id, ip_address, action_type) VALUES (?, ?, 'click')");
        $trackStmt->execute([$id, $clientIP]);
        
        // Only increment if this was a new record
        if ($trackStmt->rowCount() > 0) {
            $pdo->prepare("UPDATE server_ads SET clicks = clicks + 1 WHERE id = ?")->execute([$id]);
            echo json_encode(['success' => true, 'message' => 'Click tracked']);
        } else {
            echo json_encode(['success' => true, 'message' => 'Click already tracked for this IP']);
        }
    } catch (PDOException $e) {
        // Table might not exist yet, fall back to old behavior
        $pdo->prepare("UPDATE server_ads SET clicks = clicks + 1 WHERE id = ?")->execute([$id]);
        echo json_encode(['success' => true, 'message' => 'Click tracked (legacy mode)']);
    }

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