<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\User;
use Illuminate\Http\Request;

class API {
    public function handle(Request $request, Closure $next) {
        if (website_config('main')->is_website_under_maintenance) {
            return response()->json([
                'status'  => false,
                'data'    => [
                    'message' => 'Website sedang dalam masa pengembangan.'
                ]
            ], 403, [], JSON_PRETTY_PRINT);
        }
        if (isset($request->api_key) == false) {
            return response()->json([
                'status'  => false,
                'data'    => [
                    'message' => 'api_key tidak boleh kosong'
                ]
            ], 403, [], JSON_PRETTY_PRINT);
        }
        $check_user = User::where([['api_key', $request['api_key']]])->first();
        if ($check_user == false) {
            return response()->json([
                'status'  => false,
                'data'    => [
                    'message' => 'Pengguna tidak ditemukan.'
                ]
            ], 403, [], JSON_PRETTY_PRINT);
        }
        if ($check_user->username == 'demouser') {
            return response()->json([
                'status'  => false,
                'data'    => [
                    'message' => 'Aksi tidak diperbolehkan.'
                ]
            ], 403, [], JSON_PRETTY_PRINT);
        }
        $request->attributes->add(['user' => $check_user]);
        return $next($request);
    }
}
