<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CorsMiddleware
{
    /**
     * Daftar domain yang diizinkan (whitelist)
     * Bisa dipindahkan ke config/cors.php atau .env untuk fleksibilitas
     */
    protected array $allowedOrigins = [
        'http://localhost:3000',           // Next.js development
        'http://localhost:3001',           // Next.js preview
        'https://midhouse.id',     // Production frontend
        'https://midhouse.onrender.com', // Staging
        // Tambahkan domain lain sesuai kebutuhan
        'https://midhouseid.vercel.app',
    ];

    public function handle(Request $request, Closure $next): Response
    {
        $origin = $request->headers->get('Origin');

        // ✅ Cek apakah origin ada di whitelist
        $isAllowed = in_array($origin, $this->allowedOrigins, true);

        // 🔁 Handle preflight request (OPTIONS)
        if ($request->getMethod() === 'OPTIONS') {
            $response = new Response();

            if ($isAllowed) {
                $response->headers->set('Access-Control-Allow-Origin', $origin);
                $response->headers->set('Access-Control-Allow-Credentials', 'true'); // Penting untuk auth
            }

            $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
            $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-Router-IP, Authorization, X-Forwarded-For, Accept, X-CSRF-TOKEN');
            $response->headers->set('Access-Control-Max-Age', '86400');
            
            return $response;
        }

        // 🔄 Handle request biasa
        $response = $next($request);

        if ($isAllowed) {
            $response->headers->set('Access-Control-Allow-Origin', $origin);
            $response->headers->set('Access-Control-Allow-Credentials', 'true'); // Wajib untuk kirim cookies/auth header
        }

        return $response;
    }
}