<?php
require_once '../includes/constants.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

$code = $_GET['code'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

$code = htmlspecialchars($code);
$ip = htmlspecialchars($ip);
$userAgent = htmlspecialchars($userAgent);

if (!$code) {
    header("Location: " . TRACKING_SITE_URL . "/error.php");
    exit;
}

$url = getStealthRedirect($code);

if ($url) {
    // Log the redirect
    $sql = "INSERT INTO partners_stealth_log (cloaked_code, ip_address, user_agent, timestamp) VALUES (?, ?, ?, NOW())";
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$code, $ip, $userAgent]);
    } catch (PDOException $e) {
        error_log("Stealth redirect log error: " . $e->getMessage());
    }

    header("Location: $url");
    exit;
} else {
    header("Location: " . TRACKING_SITE_URL . "/invalid.php");
    exit;
}