<?php


namespace App\Http\Middleware;

use App\Core\Service\ServiceLogService;
use Closure;
use Exception;
use App\Models\User;
use App\Core\Repository\UserPropertyMapping\UserPropertyMappingRepository;
use Illuminate\Support\Facades\Route;

class PropertyMiddleware
{

    private $userPropertyMappingRepository;

    public function __construct(
        UserPropertyMappingRepository $userPropertyMappingRepository,
        ServiceLogService $serviceLogService
    )
    {
        $this->userPropertyMappingRepository = $userPropertyMappingRepository;
        $this->serviceLogService = $serviceLogService;
    }


    public function handle($request, Closure $next, $guard = null)
    {
        $userId = $request->credentials->user_id;

        $propertyId = $request->property_id ? $request->property_id : fillOnUndefined($request->params, 'property_id');
        if (!$propertyId) {
            return apiResponse(0, 'Property_id required.', null, 401);
        }
        $checkPropertyUserRequest = [
            'criteria' => [
                ['field' => 'user_id', 'condition' => '=', 'value' => $userId],
                ['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
                ['field' => 'status', 'condition' => '=', 'value' => 1],
            ],
            'with' => ['property'],
            'firstRow' => 1
        ];

        $checkPropertyUser = $this->userPropertyMappingRepository->findByCriteria($checkPropertyUserRequest);
        if (!$checkPropertyUser) {
            return apiResponse(0, 'User not matched this property.', null, 400);
        }

        if (!$checkPropertyUser['property']['status']) {
            return apiResponse(0, 'User not matched this property.', null, 400);
        }

        /** ServiceLog **/
        $request->serviceLogId = null;
        $request->serviceLogRequestTime = microtime(true);
        $selectedRoute = [
            //'Property.Dashboard',
            'Property.RoomRateMapping.RoomRateAvailabilityUpdate',
            'Property.RoomRateMapping.BulkUpdate',
            'RoomRateChannelPromotion.Update',
            'Property.Promotion.Update',
            'PA.Property.Quick-Pricing.Sync'
        ];
        $route = $request->route();
        $routeName = isset($route[1]['as']) ? $route[1]['as'] : null;
        $inputs = json_decode($request->getContent(), true);
        if (in_array($routeName, $selectedRoute)) {
            $serviceLogParam = [
                'property_id' => $propertyId,
                'user_id' => $userId,
                'service' => $routeName,
                'request' => json_encode($inputs),
                'ip_address' => $request->ip(),
                'status' => 2
            ];

            $serviceLog = $this->serviceLogService->create($serviceLogParam);

            if($serviceLog['status'] == 'success' && !empty($serviceLog['data'])) {
                $request->serviceLogId = $serviceLog['data']['id'];
            }

        }
        /** ServiceLog **/

        return $next($request);

    }


}
