<?php

namespace twa\ecomauth\middleware;

use twa\ecomauth\controllers\EcomUsersRegistration;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
use Closure;
use twa\apilibs\traits\APITrait;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use twa\ecomauth\models\EComTemporaryUsersModel;

class TranslateTokenWeb extends Middleware
{
    /**
     * The URIs that should be reachable while maintenance mode is enabled.
     *
     * @var array
     */
    use APITrait;
    protected $except = [
        //
    ];

    public function handle($request, Closure $next)
    {
        /*
         * Ultimately by the end of this Middleware, we are aiming to return an Collection of User info
         * This colleciton got the following structure
         * |-- user => The user information object, for both temporary users and registered users
         * |-- token => The token of the user
         * |-- column => can be either ecom_users_id or ecom_users_temporary_id depending on the type of the user
         *
         * on a side note, if the user is not registered and no temporary session is there, we return NULL for all thos information
         */
        $User = false;
        $return['column'] = null;
        $return['user'] = null;
        $return['token'] = null;

        if (request()->input('t')){
            Session::forget('login');
            Session::save();
            if (substr(request()->input('t'), 0, 2) == "t_") {
                //the user is a temporary user
                $User = EComTemporaryUsersModel::where('token', request()->input('t'))->where('cancelled', 0)->first();
                $return['column'] = "ecom_users_temporary_id";
                $return['user'] = $User;
                $return['token'] = $User["token"];
                $column = "ecom_users_temporary_id";
            }else{
                $User = (new EcomUsersRegistration())->tokentouser([ "token" => request()->input('t') ]);

                if ($User && $User->getStatusCode() == 200) {
                    Session::put("login", (new \twa\ecomauth\repositories\AuthenticateRepository())->getProfile($User->getOriginalContent()));
                    Session::put("challenge", null);
                    Session::save();
                }
            }

        }

        if (\twa\ecomauth\facades\EcomUsersFacade::loginCheck()) {
            $User = (new EcomUsersRegistration())->tokentouser([ "token" =>  session('login')->token ]);
            if (!$User || $User->getStatusCode() != 200) {
                Session::forget('login');
                Session::save();
                $return['column'] = null;
                $return['user'] = null;
                $return['token'] = null;
            } else {
                $User = $User->getOriginalContent();
                $return['column'] = "ecom_users_id";
                $return['user'] = $User;
                $return['token'] = $User["token"];
                $column = "ecom_users_id";
            }
        }
        if (!$User) {
            $User = \twa\ecomauth\facades\EcomUsersFacade::checkOfflineToken($request);
            $return['column'] = "ecom_users_temporary_id";
            $return['user'] = $User;
            $return['token'] = $User["token"];
            $column = "ecom_users_temporary_id";
        }
        unset($User->password);
        $request->user = collect($return)->recursive();
        if(!isset($column)){ return redirect('/'); }

        if ($column == "ecom_users_temporary_id") {
            twaSetCookie('offlineToken_v2', $User['token'], time()+60*24*60*3600);
            return $next($request);
        } else {
            return $next($request);
        }
    }
}
