<?php
// Test just the validation logic
error_reporting(E_ALL);
ini_set('display_errors', 1);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-API-Key, User-Agent');

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

require_once 'security_config.php';

function validateApiAccess() {
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    if ($apiKey !== API_KEY) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Invalid API key']);
        exit;
    }
    
    // Check if user agent contains allowed patterns
    $validUserAgent = false;
    foreach (ALLOWED_USER_AGENTS as $allowedAgent) {
        if (strpos($userAgent, $allowedAgent) !== false) {
            $validUserAgent = true;
            break;
        }
    }
    
    if (!$validUserAgent) {
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'Invalid user agent']);
        exit;
    }
}

try {
    // Test validation
    validateApiAccess();
    
    echo json_encode([
        'success' => true,
        'message' => 'Validation passed successfully',
        'api_key' => $_SERVER['HTTP_X_API_KEY'] ?? 'not_set',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'not_set'
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Exception: ' . $e->getMessage()
    ]);
}
?>