<?php

require_once "core.php";

$getCode = clearGetData(getCode());

if(empty($getCode) && !isset($getCode)){
    header('Location: '. $urlPath->home());
    exit;
}else{
    $coupon_id = intval($getCode);
    
    $statement = $connect->prepare("SELECT * FROM coupons WHERE coupon_id = :coupon_id LIMIT 1");
    $statement->execute(array(':coupon_id' => $coupon_id));
    $result = $statement->fetch();
  
    if ($result != false) {
        
        // Track the click
        $ip_address = $_SERVER['REMOTE_ADDR'];
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip_address = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        
        // Check if IP is banned
        try {
            $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 not banned, track the click
                
                $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
                $referer = $_SERVER['HTTP_REFERER'] ?? '';
                
                // Detect device type
                if (preg_match('/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i', $user_agent)) {
                    $device_type = 'tablet';
                } elseif (preg_match('/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/', $user_agent)) {
                    $device_type = 'mobile';
                } else {
                    $device_type = 'desktop';
                }
                
                // Detect browser
                if (strpos($user_agent, 'Edge') !== false) {
                    $browser = 'Edge';
                } elseif (strpos($user_agent, 'Chrome') !== false) {
                    $browser = 'Chrome';
                } elseif (strpos($user_agent, 'Safari') !== false) {
                    $browser = 'Safari';
                } elseif (strpos($user_agent, 'Firefox') !== false) {
                    $browser = 'Firefox';
                } elseif (strpos($user_agent, 'MSIE') !== false || strpos($user_agent, 'Trident') !== false) {
                    $browser = 'Internet Explorer';
                } elseif (strpos($user_agent, 'Opera') !== false) {
                    $browser = 'Opera';
                } else {
                    $browser = 'Unknown';
                }
                
                // Detect OS
                if (strpos($user_agent, 'Windows') !== false) {
                    $os = 'Windows';
                } elseif (strpos($user_agent, 'Mac') !== false) {
                    $os = 'Mac OS';
                } elseif (strpos($user_agent, 'Linux') !== false) {
                    $os = 'Linux';
                } elseif (strpos($user_agent, 'Android') !== false) {
                    $os = 'Android';
                } elseif (strpos($user_agent, 'iOS') !== false || strpos($user_agent, 'iPhone') !== false || strpos($user_agent, 'iPad') !== false) {
                    $os = 'iOS';
                } else {
                    $os = 'Unknown';
                }
                
                $user_id = isLogged() ? $userInfo['user_id'] : null;
                $store_id = $result['coupon_store'];
                
                // Insert click tracking
                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)");
                    
                    $insert->execute([
                        ':coupon_id' => $coupon_id,
                        ':store_id' => $store_id,
                        ':user_id' => $user_id,
                        ':ip' => $ip_address,
                        ':ua' => $user_agent,
                        ':ref' => $referer,
                        ':device' => $device_type,
                        ':browser' => $browser,
                        ':os' => $os
                    ]);
                    
                    // 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()) {
                        $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 {
                        $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
                    error_log('Tracking error: ' . $e->getMessage());
                }
            }
        } catch (Exception $e) {
            // Log error but continue
            error_log('Ban check error: ' . $e->getMessage());
        }
        
        // Redirect to affiliate link
        header('Location: '. $result['coupon_link']);
        exit;

    }else{
        header('Location: '. $urlPath->home());
        exit;
    }
}

?>