<?php

namespace twa\ecomauth\middleware;

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

class TranslateToken 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)
    {

        if (!request()->header('token')) {
            return $this->APIDisplayCustomResponse(0, "error", "token is missing", "This API requires an authentication token in order to run properly", "");
        }

        if (substr(request()->header('token'), 0, 2) == "t_") {
            //the user is a temporary user
            $User = EComTemporaryUsersModel::where('token', request()->header('token'))->where('cancelled', 0)->first();
            $column = "ecom_users_temporary_id";
        } else {
            $User = (new EcomUsersRegistration())->tokentouser([ "token" =>  request()->header('token') ]);
            if (!$User || $User->getStatusCode() != 200) {
                $User = false;
            } else {
                $User = $User->getOriginalContent();
                $column = "ecom_users_id";
            }
        }
        if (!$User) {
            return $this->APIDisplayCustomResponse(0, "error", "invalid token", "The token provided is not valid", "");
        } else {
            $User = collect($User)->recursive();
        }
        unset($User->password);
        $return['user'] = $User;
        $return['column'] = $column;
        $request->user = collect($return)->recursive();
        return $next($request);
    }
}
