<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Modules\User\Models\User;

class CheckApiSecret
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //dd(app()->getLocale());
        $secret = 'c303e42aa866fb87e88c055e4f923dw5';
        if (!$request->hasHeader('secret') || $secret != $request->header('secret')) {
            $message = "Auth Failed";
            return response()->json([
                'data' => null,
                'message' => $message,
                'errors' => []
            ], 401);
        }
        $token = $request->bearerToken() ?? $request->header('token');
        if($token){
            $user = User::where('api_token', $token)->whereIn('role', [4, 6])->first();
            if ($user) {
                request()->merge(['api_token' => $token]);
               Auth::login($user);
            }
        }
        

        $deviceId = strip_tags(trim($request->header('deviceId')));
        $deviceToken = strip_tags(trim($request->header('deviceToken')));
        $availableLocales = getAvailableLocales();
        $locale = $request->header('lang');
        $locale = in_array($locale, $availableLocales) ? $locale : app()->getLocale();

        if ($deviceId) {
            $request['device_id'] = $deviceId;
        }
        if ($deviceToken) {
            $request['device_token'] = $deviceToken;
        }
        //$request['locale'] = $locale; // $request->locale - $request->query('locale')

        app()->setLocale($locale);

        return $next($request);
    }
}
