<?php
/**
 * Secure CORS Configuration
 * Restricts API access to trusted domains only
 */

require_once 'config_manager.php';

class CORSManager {
    
    /**
     * Get allowed origins from environment configuration
     */
    private static function getAllowedOrigins() {
        // Get from environment variable (comma-separated list)
        $corsOrigins = getConfig('CORS_ALLOWED_ORIGINS', '');
        
        if (empty($corsOrigins)) {
            // Fallback to detecting current domain for same-origin requests
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
            return [$protocol . '://' . $host];
        }
        
        // Parse comma-separated origins
        $origins = array_map('trim', explode(',', $corsOrigins));
        return array_filter($origins); // Remove empty values
    }
    
    /**
     * Validate if the request origin is allowed
     */
    private static function isOriginAllowed($origin) {
        if (empty($origin)) {
            return false;
        }
        
        $allowedOrigins = self::getAllowedOrigins();
        
        // Exact match check
        if (in_array($origin, $allowedOrigins)) {
            return true;
        }
        
        // For development, allow localhost variations
        if (getConfig('APP_ENV', 'production') === 'development') {
            if (preg_match('/^https?:\/\/(localhost|127\.0\.0\.1|.*\.local)(:\d+)?$/', $origin)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Set secure CORS headers
     */
    public static function setSecureCORSHeaders() {
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
        
        if (self::isOriginAllowed($origin)) {
            // Allow the specific origin
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Credentials: true');
        } else {
            // Log suspicious requests
            error_log("CORS: Blocked request from unauthorized origin: " . $origin);
            
            // Don't set CORS headers for unauthorized origins
            // This will cause CORS errors in browsers for cross-origin requests
        }
        
        // Set other CORS headers
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        header('Access-Control-Max-Age: 86400'); // Cache preflight for 24 hours
        
        // Security headers
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header('X-XSS-Protection: 1; mode=block');
        
        // Content Security Policy
        $csp = "default-src 'self'; " .
               "script-src 'self' 'unsafe-inline' https://js.stripe.com; " .
               "style-src 'self' 'unsafe-inline'; " .
               "img-src 'self' data: https:; " .
               "connect-src 'self' https://api.stripe.com; " .
               "frame-src https://js.stripe.com;";
        header('Content-Security-Policy: ' . $csp);
    }
    
    /**
     * Handle preflight OPTIONS requests securely
     */
    public static function handlePreflightRequest() {
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            self::setSecureCORSHeaders();
            
            // Log preflight requests for monitoring
            $origin = $_SERVER['HTTP_ORIGIN'] ?? 'unknown';
            error_log("CORS: Preflight request from: " . $origin);
            
            http_response_code(200);
            exit(0);
        }
    }
    
    /**
     * Get CORS configuration summary for diagnostics
     */
    public static function getDiagnosticInfo() {
        return [
            'allowed_origins' => self::getAllowedOrigins(),
            'current_origin' => $_SERVER['HTTP_ORIGIN'] ?? null,
            'is_development' => getConfig('APP_ENV', 'production') === 'development',
            'request_method' => $_SERVER['REQUEST_METHOD'] ?? null
        ];
    }
}

/**
 * Quick function to apply secure CORS headers
 */
function applySecureCORS() {
    CORSManager::setSecureCORSHeaders();
    CORSManager::handlePreflightRequest();
}
?>
