<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\ResourceLock as Entity;
use App\Models\User;
use Illuminate\Support\Facades\View;

class ResourceLock
{
    /**
     * @param $request
     * @param Closure $next
     * @param string $resourceType
     * @param mixed $resourceIdParam
     * @return mixed
     */
    public function handle($request, $next, $resourceType, $resourceIdParam = null)
    {
        //brisanje starih lockova
        Entity::garbageCollector();
        $resourceId = 0;

        //dohvatanje ID-ja po parametru
        if($resourceIdParam){
            //dovlacenje parametra iz rute
            $resourceEntity = $request->route($resourceIdParam);
            //provera model bindinga
            $resourceId =  is_object($resourceEntity) ? $resourceEntity->id : (int) $resourceEntity;
        }

        //priprema informacija o trenutnom Useru
        $userId = auth()->user()->id;
        $userName = auth()->user()->first_name . ' ' . auth()->user()->last_name;

        //dohvatanje locka
        $isLocked = Entity::where('resource_type', $resourceType)->where('resource_id', $resourceId)->first();

        //provera da li lock postoji
        if ($isLocked) {
            //provera da li je lock od usera koji pokusava da pristupi
            if ($isLocked->user_id == $userId) {
                //prosledjivanje varijabli za resource lock refresh
                View::share('callResourceLockRefresh', [
                    'resourceType' => $resourceType,
                    'resourceId' => $resourceId
                ]);
                return $next($request);
            } else {
                //u slucaju da nije
                return response()->view('_layout.partials.resource_lock', [
                    'lockedResource' => ucfirst($resourceType),
                    'userName' => $isLocked->user_name,
                    'userEmail' => User::find($isLocked->user_id)->email,
                    'userPhone' => User::find($isLocked->user_id)->phone
                ]);
            }
        } else {
            //ukoliko lock ne postoji - kreiraj nov

            Entity::create([
                'resource_type' => $resourceType,
                'resource_id' => $resourceId,
                'user_id' => $userId,
                'user_name' => $userName,
                'user_ip_address' => $request->getClientIp(),
                'user_agent' => $request->server('HTTP_USER_AGENT')
            ]);

            //prosledjivanje varijabli za resource lock refresh
            View::share('callResourceLockRefresh', [
                'resourceType' => $resourceType,
                'resourceId' => $resourceId
            ]);
            return $next($request);

        }
    }
}
