<?php

namespace twa\ecomauth\middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use twa\ecomauth\controllers\EcomUsersRegistration;
use twa\ecomcart\controllers\EcomCartController;
use twa\ecomcart\models\EcomCartItemsModel;

class AppendUserMiddleware
{
    /**
     * this middleware is inteded to return all of data required by each page of the website
     * such as the menus, the authentication status of the user, the favorite counts, the cart counts
     */


    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */


    private $url;

    public function __construct(UrlGenerator $url)
    {
        $this->url = $url;
    }


    public function handle(Request $request, Closure $next)
    {
        $menus = [];
        foreach (config('ecom.menus') as $menu) {
            foreach ($menu["parameters"] as $key => $row) {
                $menu["parameters"][$key] = str_replace(['{store_prefix}','{language_prefix}'], [$request->segment(1),$request->segment(2)], $row);
            }
            try {
                $value = (new \twa\ecomgeneral\controllers\FrontEndMenuBuilder())->renderAPI("html", $menu["parameters"]);
            } catch (\Throwable $e) {
                dd(["status" => "error", "request" => $menu, "error" => $e]);
            }
            try {
                $menus[$menu['name']] = $value['html'];
            } catch (\Throwable $e) {
                $menus[$menu['name']] = "could not parse menu";
            }
        }
        $request->menus = $menus;

        $userData = self::getUserObject($request);
        $request->user = $userData;

        return $next($request);

//        if (!$userData["login"] && isset($userData["user"]["token"]) && $userData["user"]["token"] != '' && $userData["user"]["token"] != false) {
//            setcookie('offlineToken_v2', $userData["user"]["token"], time()+60*24*60*3600, "/");
//            return $next($request);
//        } else {
//            return $next($request);
//        }
    }


    public function getUserObject($request)
    {
        $return = false;
        if (\twa\ecomauth\facades\EcomUsersFacade::loginCheck()) {
            $user = (new EcomUsersRegistration())->getProfile(session('login')->id);
            if (!$user) {
                Session::forget('login');
                Session::save();
                return redirect(ecom('url')->prefix());
            }
            $return["login"] = true;
            $return["user"] = $user;
            $return['wallet'] = \twa\ecomprofile\controllers\EcomUsersWalletController::get(session('login')->id, $request->store['id']);
            $return['loyalty'] = (new \twa\ecomprofile\controllers\EcomUsersLoyaltyController())->get([ "store" => $request->store['id'] ], session('login')->id);
            $return["token"] = $user['token'];
            $return["column"] = "ecom_users_id";
            //we need to get the default data for a logged in user
        } else {
            //we create a temporary session
            if (isset($_COOKIE['offlineToken_v2'])) {
//                dump($_COOKIE['offlineToken_v2']);
                $token = $_COOKIE['offlineToken_v2'];
                if (env('APP_DEBUG_TEMPORARY_TOKEN') == 1) {
                    dump($_COOKIE['offlineToken_v2']);
                }
//                try{
//                    $token = \Crypt::decrypt($_COOKIE['offlineToken_v2'], false);
//                }catch (\Throwable $e){
//                }
//                try{ $token = explode('|',$token)[1]; }catch (\Throwable $e){ }
            } else {
                $token = false;
            }
            $return["login"] = false;
            if (!$token || $token == '') {
                //we create a new token for this user
                $array = (new \twa\ecomauth\controllers\EcomTemporaryUsersController())->createTemporarySession();
                $return["user"] = $array;
                $return["token"] = $array['token'];
            } else {
                $User = \twa\ecomauth\controllers\EcomTemporaryUsersController::sessionToTemporaryUser($token);
                if (!$User || count($User)==0) {

                    twaSetCookie('offlineToken_v2', "", time()-3600);
                    $return["user"] = false;
                    $return["token"] = false;
                } else {
                    $return["user"] = $User;
                    $return["token"] = $return["user"]["token"];
                }
            }
            if ($return["user"]) {
                //we get the cart and favorites of this user
                $return["column"] = "ecom_users_temporary_id";
            } else {
                //we return zero
                $return['counts']['cart'] = 0;
                $return['counts']['favorites'] = 0;
            }
        }

        $return = self::applyCounts($return);
        return collect($return)->recursive();
    }


    public function applyPreferredFromStore($request)
    {
        if (isset($request->user['user']['ecom_currencies_id'])) {
            $preferredCurrencyOfTheUser = $request->user['user']['ecom_currencies_id'];
        } else {
            return $request;
        }
        foreach ($request->store['currencies'] as $key => $currency) {
            $request->store['currencies'][$key]["selected"] = 0;
            if ($currency->id == $request->user['user']['ecom_currencies_id']) {
                $request->store['preferred_currency'] = $currency;
                $request->store['currencies'][$key]["selected"] = 1;
                return $request;
            }
        }

        return $request;
    }



    public function applyCounts($return)
    {
        $return['counts']['cart'] = 0;
        $return['counts']['favorites'] = 0;
        return $return;
    }
}
