<?php

namespace App\Http\Middleware;

use Illuminate\Support\Str;
use App\Models\Generalsetting;
use Illuminate\Http\Request;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = [
        'payment/process',
        '/notify/paytm',
        '/notify/razorpay',
        '/notify/flutterwave',
        '/notify/instamojo',
        '/payment/process',
        '/notify/coingate',
        '/webhook/flutterwave',
        '/webhook/boldd/*',
    ];

    /**
     * Determine if the request should bypass CSRF verification.
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function shouldPassThrough(Request $request): bool
    {
        // Skip CSRF for requests expecting JSON or with ?api=true
        return $request->expectsJson() || $request->query('api') === 'true';
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        // Bypass CSRF verification for API requests
        if ($this->shouldPassThrough($request)) {
            return $next($request);
        }

        // Apply CSRF verification for web requests
        return parent::handle($request, $next);
    }
}