<?php
// Central CORS helper — include before outputting anything
// Remove any existing CORS headers then set a single authoritative set.
if (!headers_sent()) {
    // Remove common CORS headers to avoid duplicates
    header_remove('Access-Control-Allow-Origin');
    header_remove('Access-Control-Allow-Methods');
    header_remove('Access-Control-Allow-Headers');
    header_remove('Access-Control-Expose-Headers');
}

// CORS configuration - set your production domain
$isDev = in_array($_SERVER['HTTP_HOST'] ?? '', ['localhost', '127.0.0.1', 'website-project.test']) || 
         strpos($_SERVER['HTTP_HOST'] ?? '', '192.168.') === 0;

if ($isDev) {
    // Development: allow all origins
    header('Access-Control-Allow-Origin: *');
} else {
    // Production: all known frontend origins
    $allowedOrigins = [
        'https://tajdid.com.my',
        'https://www.tajdid.com.my',
        'http://tajdidcorporation.com.my',
        'https://tajdidcorporation.com.my',
        'http://www.tajdidcorporation.com.my',
        'https://www.tajdidcorporation.com.my',
    ];
    $origin = $_SERVER['HTTP_ORIGIN'] ?? '';
    if (in_array($origin, $allowedOrigins, true)) {
        header('Access-Control-Allow-Origin: ' . $origin);
        header('Access-Control-Allow-Credentials: true');
    }
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Admin-Key');
header('Access-Control-Expose-Headers: Retry-After');
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    // Short-circuit preflight requests
    http_response_code(204);
    exit;
}
