<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $exception)
    {
        $response = parent::render($request, $exception);

        // Always add CORS to API/sanctum so browser never sees "CORS Missing Allow Origin"
        if ($request->is('api/*') || $request->is('sanctum/*')) {
            $origin = $request->headers->get('Origin');
            $originNormalized = $origin ? rtrim($origin, '/') : null;
            $allowedOrigins = [
                'http://localhost:3000',
                'http://localhost:5173',
                'http://127.0.0.1:3000',
                'http://127.0.0.1:5173',
                'http://localhost:8000',
                'http://127.0.0.1:8000',
                'http://pandamarts.co.uk',
                'https://pandamarts.co.uk',
                'http://www.pandamarts.co.uk',
                'https://www.pandamarts.co.uk',
                'http://demo.pandamarts.co.uk',
                'https://demo.pandamarts.co.uk',
            ];
            $allowOrigin = null;
            if ($originNormalized) {
                if (in_array($originNormalized, $allowedOrigins)) {
                    $allowOrigin = $originNormalized;
                } elseif (preg_match('/^https?:\/\/(www\.|demo\.)?pandamarts\.co\.uk(:\d+)?\/?$/i', $originNormalized)) {
                    $allowOrigin = $originNormalized;
                }
            }
            // Always set an origin so the header is never missing (fallback for proxy/stripped Origin)
            $response->headers->set('Access-Control-Allow-Origin', $allowOrigin ?? 'https://pandamarts.co.uk');
            $response->headers->set('Access-Control-Allow-Credentials', 'true');
            $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
            $response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With, X-CSRF-TOKEN, X-XSRF-TOKEN, X-Branch-Id');
            $response->headers->set('Vary', 'Origin');
        }

        return $response;
    }
}

