<?php


namespace App\Http\Middleware;

use App\Core\Service\PropertyConfigService;
use Closure;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class ContentWizardMiddleware
{

    private $propertyConfigService;
    private $request;
    private $response;

    public function __construct(
        Request $request,
        Response $response,
        PropertyConfigService $propertyConfigService
    )
    {
        $this->propertyConfigService = $propertyConfigService;
        $this->request = $request;
        $this->response = $response;
    }


    public function handle($request, Closure $next, $guard = null)
    {
        $response = $next($request);
        if ($response->getData()->status == 200) {
            $params = $this->request->params;
            $url = collect($this->request->route());
            $getNameArray = $url->where('as', '!=', null)->first();
            $routeAlias = fillOnUndefined($getNameArray, 'as');

            if($routeAlias == 'Property.Contact.Update'){
                if(isset($params['contact']['address']) && isset($params['contact']['latitude']) && isset($params['contact']['longitude'])){
                    $routeAlias = 'Property.Location.Update' ;
                }
            }
            $rateParams = [
                'property_id' => fillOnUndefined($params, 'property_id'),
                'user_id' => $this->request->credentials->user_id,
                'property_rate_for' => $routeAlias,
            ];
            $this->propertyConfigService->rateProperty(array_merge($params, $rateParams));
        }
        return $response;
    }

}
