<?php

namespace App\Core\Permission;

use App\Core\Service\PermissionService;
use App\Core\Service\PermissionGroupUserMappingService;
use App\Core\Service\UserService;
use Illuminate\Http\Request;
use Illuminate\Route;
use Illuminate\Support\Facades\Log;
use Exception;

class RoutePermissionAuthorize
{


    private $permissionGroupUserMappingService;
    private $userService;
    private $permissionService;
    private $currentRoute;
    private $routePermissionData;
    private $request;

    public function __construct
    (
        PermissionGroupUserMappingService $permissionGroupUserMappingService,
        UserService $userService,
        PermissionService $permissionService,
        Request $request
    )
    {
        $this->permissionGroupUserMappingService = $permissionGroupUserMappingService;
        $this->userService = $userService;
        $this->permissionService = $permissionService;
        $this->request = $request;
        $this->currentRoute = $this->request->route();
    }


    public function setCurrentRoute ( Route $route )
    {
        $this->currentRoute = $route;
        $this->routePermissionData = $this->getRoutePermissionData();
    }

    protected function getRouteAliasName(){

        $url = collect($this->request->route());
        $getNameArray = $url->where('as' , '!=', null)->first();
        return fillOnUndefined($getNameArray, 'as');

    }

    protected function getRoutePermissionData ()
    {

        if ( !$this->currentRoute)
        {
            throw new Exception("Current Route is Null");
        }

        if ($this->routePermissionData)
        {
            return $this->routePermissionData;
        }

        $criteria =
            [
                "criteria" =>
                    [
                        [ "field" => "code", "condition" => "=", "value" => $this->getRouteAliasName() ]
                    ],
                "with"     => [ "permissionGroupMapping.permissionGroup"],
                "firstRow" => 1
            ];
        $result =   $this->permissionService->findByCriteria ( $criteria );
        return $result;
    }

    public function getRoutePermissionGroupId ()
    {
        return fillOnUndefined($this->getRoutePermissionData(),"permission_group_mapping.permission_group.id");
    }

    public function isUserAuthorizedForCurrentRoute ( $params )
    {
        try
        {
            $user_id = $params['user_id'] ;
            $property_id = $params['property_id'] ;

            $userCriteria =
                [
                    "criteria"=>
                        [
                            ["field"=>"id","condition"=>"=","value"=>$user_id],
                            ["field"=>"status","condition"=>"=","value"=>1]
                        ],
                    "firstRow"=>1
                ];

            $userData = $this->userService->select($userCriteria);

            if ( !$userData['data'] )
            {
                return false;
            }

            $userData = $userData['data'] ;


            if ($userData["user_type"] == 1)
            {
                return true;
            }

            $userGroupCriteria =
                [
                    "criteria" =>
                        [
                            ["field" => "user_id", "condition" => "=", "value" => $user_id],
                            ["field" => "property_id", "condition" => "=", "value" => $property_id],
                            ["field" => "status", "condition" => "=", "value" => 1]
                        ],
                    "with" => ["permissionGroup", "permissionGroupMapping"]
                ];

            $userGroups = $this->permissionGroupUserMappingService->findByCriteria($userGroupCriteria);


            if ( !$userGroups)
            {
                return false;
            }

            foreach ($userGroups as $perGroup)
            {
                if(isset($perGroup["permission_group"]["is_admin"]) && $perGroup["permission_group"]["is_admin"])
                {
                    return true;
                }
            }

            
            if ( !$routePermissionData = $this->getRoutePermissionData())
            {
                return false;
            }


            foreach ($userGroups as $perGroup)
            {
                foreach ($perGroup["permission_group_mapping"] as $perPermissionGroup)
                {
                    if($routePermissionData["id"] == $perPermissionGroup["permission_id"])
                    {
                        return true;
                    }
                }
            }
            return false;

        } catch ( Exception $e )
        {
            $message = $e->getFile()." ".$e->getLine()." ".$e->getMessage();
            Log::error($message);
            return false;
        }
    }

}