<?php

namespace twa\ecomauth\middleware;

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

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

    public function handle($request, Closure $next)
    {
        $TokenCheck = EComTemporaryUsersModel::where('token', $request->header('token'))->where('cancelled', 0)->first();
        if (!$TokenCheck) {
            return $this->APIDisplayCustomResponse(0, "error", "Session not found", "We couldnt not locate the temporary session", "");
        } else {
            if (!str_contains($TokenCheck->ip, request()->ip())) {
                $TokenCheck->ip = $TokenCheck->ip.','.request()->ip();
                $TokenCheck->save();
            }

            unset($TokenCheck->id);
            unset($TokenCheck->ip);
            $request->TemporaryUser = $TokenCheck;
            return $next($request);
        }
    }
}
