<?php

require './core.php';

// Get parameters
$coupon_id = isset($_GET['c']) ? intval($_GET['c']) : 0;
$store_id = isset($_GET['s']) ? intval($_GET['s']) : 0;

// Get IP address
function getClientIP() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

$ip_address = getClientIP();

// Check if IP is banned
$ban_check = $connect->prepare("SELECT ban_id FROM banned_ips WHERE ip_address = :ip AND (is_permanent = 1 OR expires_at > NOW())");
$ban_check->execute([':ip' => $ip_address]);

if ($ban_check->fetch()) {
    // IP is banned, redirect to home
    header('Location: ' . SITE_URL);
    exit;
}

// Get user agent details
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? '';

// Detect device type
function getDeviceType($user_agent) {
    if (preg_match('/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i', $user_agent)) {
        return 'tablet';
    }
    if (preg_match('/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/', $user_agent)) {
        return 'mobile';
    }
    return 'desktop';
}

// Detect browser
function getBrowser($user_agent) {
    if (strpos($user_agent, 'Edge') !== false) return 'Edge';
    if (strpos($user_agent, 'Chrome') !== false) return 'Chrome';
    if (strpos($user_agent, 'Safari') !== false) return 'Safari';
    if (strpos($user_agent, 'Firefox') !== false) return 'Firefox';
    if (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Trident') !== false) return 'Internet Explorer';
    if (strpos($user_agent, 'Opera') !== false) return 'Opera';
    return 'Unknown';
}

// Detect OS
function getOS($user_agent) {
    if (strpos($user_agent, 'Windows') !== false) return 'Windows';
    if (strpos($user_agent, 'Mac') !== false) return 'Mac OS';
    if (strpos($user_agent, 'Linux') !== false) return 'Linux';
    if (strpos($user_agent, 'Android') !== false) return 'Android';
    if (strpos($user_agent, 'iOS') !== false || strpos($user_agent, 'iPhone') !== false || strpos($user_agent, 'iPad') !== false) return 'iOS';
    return 'Unknown';
}

$device_type = getDeviceType($user_agent);
$browser = getBrowser($user_agent);
$os = getOS($user_agent);
$user_id = isLogged() ? $userInfo['user_id'] : null;

// Get redirect URL
$redirect_url = '';

if ($coupon_id > 0) {
    // Get coupon details
    $coupon_query = $connect->prepare("SELECT coupon_link, coupon_store FROM coupons WHERE coupon_id = :id AND coupon_status = 1");
    $coupon_query->execute([':id' => $coupon_id]);
    $coupon = $coupon_query->fetch(PDO::FETCH_ASSOC);
    
    if ($coupon) {
        $redirect_url = $coupon['coupon_link'];
        $store_id = $coupon['coupon_store'];
    }
} elseif ($store_id > 0) {
    // Get store details
    $store_query = $connect->prepare("SELECT store_link FROM stores WHERE store_id = :id AND store_status = 1");
    $store_query->execute([':id' => $store_id]);
    $store = $store_query->fetch(PDO::FETCH_ASSOC);
    
    if ($store) {
        $redirect_url = $store['store_link'];
    }
}

// If no valid URL, redirect to home
if (empty($redirect_url)) {
    header('Location: ' . SITE_URL);
    exit;
}

// Track the click
try {
    $insert = $connect->prepare("INSERT INTO link_clicks 
        (coupon_id, store_id, user_id, ip_address, user_agent, referer, device_type, browser, os) 
        VALUES (:coupon_id, :store_id, :user_id, :ip, :ua, :ref, :device, :browser, :os)");
    
    $result = $insert->execute([
        ':coupon_id' => $coupon_id > 0 ? $coupon_id : null,
        ':store_id' => $store_id,
        ':user_id' => $user_id,
        ':ip' => $ip_address,
        ':ua' => $user_agent,
        ':ref' => $referer,
        ':device' => $device_type,
        ':browser' => $browser,
        ':os' => $os
    ]);
    
    // Debug: Log the insert result
    if (!$result) {
        error_log('Failed to insert click tracking: ' . print_r($insert->errorInfo(), true));
    }
    
    // Update statistics
    $today = date('Y-m-d');
    $stat_check = $connect->prepare("SELECT stat_id FROM click_statistics WHERE store_id = :store_id AND date = :date");
    $stat_check->execute([':store_id' => $store_id, ':date' => $today]);
    
    if ($stat_check->fetch()) {
        // Update existing stat
        $connect->prepare("UPDATE click_statistics SET total_clicks = total_clicks + 1 WHERE store_id = :store_id AND date = :date")
            ->execute([':store_id' => $store_id, ':date' => $today]);
    } else {
        // Create new stat
        $connect->prepare("INSERT INTO click_statistics (store_id, date, total_clicks, unique_clicks) VALUES (:store_id, :date, 1, 1)")
            ->execute([':store_id' => $store_id, ':date' => $today]);
    }
    
} catch (Exception $e) {
    // Log error but continue to redirect
    error_log('Link tracking error: ' . $e->getMessage());
}

// Redirect to affiliate link
header('Location: ' . $redirect_url);
exit;

?>
