<?php

namespace Modules\HospitalPortal\Http\Middleware;
use Modules\HospitalPortal\Helpers\ApiResponse;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\App;

class Authentication
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $acceptHeader = $request->header('Accept');
        $contentType = $request->header('Content-Type');
        $locale = $request->header('Accept-Language');

        // Add language
        if(!$locale)
        {
            return ApiResponse::apiResponse('Unauthorized', null, trans('validation.required', ['attribute' => 'Accept-Language']), 401);
        }
        if($locale !== 'en-US' && $locale !== 'id-ID')
        {
            return ApiResponse::apiResponse('Bad Request', null, trans('validation.invalid', ['attribute' => 'Accept-Language']), 400);
        }
        if ($locale === 'en-US')
        {
            App::setLocale('en');
        } elseif ($locale === 'id-ID')
        {
            App::setLocale('id');
        } else
        {
            App::setLocale('en');
        }
        
        // Validate type accept & content type
        if (!$acceptHeader)
        {
            return ApiResponse::apiResponse('Unauthorized', null, trans('validation.required', ['attribute' => 'Accept']), 401);
        }
        if (!$contentType)
        {
            return ApiResponse::apiResponse('Unauthorized', null, trans('validation.required', ['attribute' => 'Content-Type']), 401);
        }
        if ($acceptHeader !== 'application/json')
        {
            return ApiResponse::apiResponse('Bad Request', null, trans('validation.invalid', ['attribute' => 'Accept']), 400);
        }
        if($contentType !== 'application/json')
        {
            return ApiResponse::apiResponse('Bad Request', null, trans('validation.invalid', ['attribute' => 'Content-Type']), 400);
        }
        return $next($request);
    }
}
