<?php

namespace App\Http\Middleware;

use App\Models\BirzhaUser;
use Closure;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Throwable;

class CheckOctoberSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // For Admin's session
        if(\Auth::check()) {
            return $next($request);
        }
        
        // For Birzha User's session
        try{
            if(env('APP_ENV') == 'production'
                && isset(preg_split("/[\s\[\]\",]+/", \Cookie::get('user_auth'))[1])) {
                    
                $userId = preg_split("/[\s\[\]\",]+/", \Cookie::get('user_auth'))[1];

                $user = BirzhaUser::find($userId);

                if(is_null($user)) {
                    return redirect()->away(env('PARENT_APP'));
                } else {
                    return $next($request);
                }
            } else {
                return redirect()->away(env('PARENT_APP'));
            } 
        } catch(Throwable $th) {
            \Log::info($th);
            return redirect()->away(env('PARENT_APP'));
        }
               
    }
}
