<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ValidateSignatureFlexible
{
    public function handle(Request $request, Closure $next)
    {
        $signature = $request->query('signature');

        if (! $signature) {
            abort(403);
        }

        // Pakai APP_URL, bukan request scheme
        $baseUrl = rtrim(config('app.url'), '/').'/'.ltrim($request->path(), '/');

        $query = collect($request->query())
            ->except('signature')
            ->map(fn ($value, $key) => $key.'='.$value)
            ->implode('&');

        $original = rtrim($baseUrl.'?'.$query, '?');

        $expected = hash_hmac('sha256', $original, config('app.key'));

        if (! hash_equals($expected, $signature)) {
            abort(403, 'Invalid signature.');
        }

        return $next($request);
    }
}
