<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ApiKeyAndUserAgent
{
    public function handle(Request $request, Closure $next)
    {
        $userAgent = $request->header('User-Agent');

        if (empty($userAgent)) {
            return response()->json([
                'success' => false,
                'message' => 'User-Agent header is required',
            ], 400);
        }

        if (!str_contains($userAgent, 'SIKAPI-mobile')) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized client',
            ], 403);
        }

        $apiKey = $request->header('X-API-KEY');

        if (empty($apiKey)) {
            return response()->json([
                'success' => false,
                'message' => 'X-API-KEY header is required',
            ], 401);
        }

        if ($apiKey !== config('app.api_key')) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid API key',
            ], 403);
        }

        return $next($request);
    }
}

