<?php

namespace App\Http\Middleware;

use Closure;

class PhysicalGateDisplayKeyMiddleware
{
    /**
     * Only clients that know the display key may read the current gate code.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!config('physical_attendance_gate.enabled')) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Ciri kod kaunter fizikal tidak diaktifkan.',
            ], 404);
        }

        $expected = (string) config('physical_attendance_gate.display_key');
        if ($expected === '') {
            return response()->json([
                'status' => 'failed',
                'message' => 'Kod paparan kaunter belum dikonfigurasi.',
            ], 503);
        }

        $provided = (string) $request->header('X-Physical-Gate-Display-Key', '');
        if ($provided === '' && $request->bearerToken()) {
            $provided = (string) $request->bearerToken();
        }

        if ($provided === '' || !hash_equals($expected, $provided)) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Akses ditolak.',
            ], 403);
        }

        $service = app(\App\Services\PhysicalAttendanceGateCode::class);
        if (!$service->isConfigured()) {
            return response()->json([
                'status' => 'failed',
                'message' => 'PHYSICAL_ATTENDANCE_GATE_SECRET belum ditetapkan.',
            ], 503);
        }

        return $next($request);
    }
}
