<?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;

class AuthenticationRequiredToken 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)
    {
        $session_token = false;
        if (session('login') && is_object(session('login')) && property_exists(session('login'), "token")) {
            $session_token = session('login')->token;
        }
        $token = request()->header('token', $session_token);


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

        $User = (new EcomUsersRegistration())->tokentouser([ "token" =>  $token ]);
        if (!$User || $User->getStatusCode() != 200) {
            return $this->APIDisplayCustomResponse(0, "error", "invalid token", "The token provided is not valid", "");
        }
        $User = $User->getOriginalContent();

        unset($User->password);
        $return['column'] = "ecom_users_id";
        $return['user'] = $User;
        $return['token'] = $User["token"];
        $request->user = collect($return)->recursive();
        return $next($request);
    }
}
