<?php
// cors.php — Centralized CORS configuration (single source of truth)

/**
 * Default allowed origins (development-safe)
 * 👉 These remain here permanently
 */
function getDefaultAllowedOrigins(): array {
    return [
        'http://localhost',
        'http://localhost:5173',
        'http://localhost:8080',
        'http://127.0.0.1',
        'http://127.0.0.1:8080',
        'https://localhost',
        'https://localhost:8080',
        'https://portal.creativewebsolutions.co.ke'
    ];
}

/**
 * Get allowed origins
 * Defaults stay in this file
 */
function getAllowedOrigins(): array {
    return getDefaultAllowedOrigins();
}

/**
 * Check if an origin is allowed
 */
function isOriginAllowed(?string $origin = null): bool {
    if (!$origin) {
        return false;
    }

    // Exact match
    if (in_array($origin, getAllowedOrigins(), true)) {
        return true;
    }

    // Allow localhost / 127.0.0.1 on any port (dev convenience)
    $host = parse_url($origin, PHP_URL_HOST);
    return in_array($host, ['localhost', '127.0.0.1'], true);
}

/**
 * Apply CORS headers
 */
function configureCors(): void {
    if (!isset($_SERVER['HTTP_ORIGIN'])) {
        return; // Same-origin request
    }

    $origin = $_SERVER['HTTP_ORIGIN'];

    if (!isOriginAllowed($origin)) {
        error_log("CORS blocked origin: {$origin}");

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

    header("Access-Control-Allow-Origin: {$origin}");
    header('Access-Control-Allow-Credentials: true');
    header('Vary: Origin');

    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS');

        header(
            'Access-Control-Allow-Headers: ' .
            'Content-Type, Authorization, Accept, X-Requested-With, X-CSRF-Token, X-API-Key, X-Session-ID'
        );

        header('Access-Control-Max-Age: 86400');
        http_response_code(204);
        exit;
    }
}
