<?php

namespace App\Core\Permission;



use App\Core\Service\PermissionService;
use App\Core\Service\PermissionGroupService;
use App\Core\Service\PermissionGroupUserMappingService;
use App\Core\Service\UserService;
use Exception;

abstract class AbstractRelatedPermission
{
    protected $userData;
    protected $userService;
    protected $permissionGroupUserMappingService;

    protected $permissionGroupId = [];
    protected $permissionGroupService;
    protected $permissionService;

    public function __construct
    (
        UserService $userService,
        PermissionGroupUserMappingService $permissionGroupUserMappingService,
        PermissionGroupService $permissionGroupService,
        PermissionService $permissionService

    )
    {
        $this->userService = $userService;
        $this->permissionGroupUserMappingService = $permissionGroupUserMappingService;
        $this->permissionGroupService = $permissionGroupService;
        $this->permissionService = $permissionService;
    }

    protected function checkIfUserIdSet ()
    {
        if ($this->userData)
        {
            return $this->userData;
        }else
        {
            throw new Exception("You need to call  'setUser' function first");
        }
    }


    public function setUserWithPermissionId ( $userId,$propertyId,$permission_id )
    {
        $permission_id = $permission_id ? $permission_id : 0;
        return $this->setUserData ($userId,$propertyId,$permission_id );
    }


    private function setUserData ($userId,$propertyId,$permission_id )
    {
        $userCriteria =
            [
                "criteria"=>
                    [
                        ["field"=>"id","condition"=>"=","value"=>$userId],
                        ["field"=>"status","condition"=>"=","value"=>1]
                    ],
                "addAppends"=>["isPropertyAdmin"],
                "firstRow"=>true
            ];
        $userData = $this->userService->getUserList($userCriteria);
        if(!$userData)
        {
            throw new Exception("User Not Found");
        }


        $isUserRelatedActiveProperty = $this->userService->isUserRelatedActiveProperty($userId,$propertyId);
        if ( !$isUserRelatedActiveProperty)
        {
            throw new Exception("User : ".$userId." Has No Relation With Property : ".$propertyId);
        }

        $permissionCriteria =
            [
                "criteria"=>
                    [
                        ["field"=>"id","condition"=>"=","value"=>$permission_id]
                    ],
                "with"=>["permissionGroupMapping"],
                "firstRow"=>true
            ];

        $permissionData = $this->permissionService->findByCriteria($permissionCriteria);
        $permissionData = $permissionData ? $permissionData : [];

        if ( !$permissionData && (!$userData["isSuperUser"] && !$userData["isPropertyAdmin"]))
        {
            throw new Exception("PermissionId Has Not Found : ".json_encode($permission_id));
        }

        $permissionGroupInfo = fillOnUndefined($permissionData,"permission_group_mapping");

        $userData["property_id"] = $isUserRelatedActiveProperty["property_id"];
        $userData["property"] = $isUserRelatedActiveProperty["property"];

        $this->userData = $userData;
        $this->userData["relatedParameters"] = [];
        $this->userData["selectedGroupMapping"] = [];
        try
        {
            if ($this->userData[ "isSuperUser" ])
            {
                return false;
            }
            $this->userData["is_admin"] = false;
            $userRelatedParametersCriteria =
                [
                    "criteria"=>
                        [
                            ["field"=>"user_id","condition"=>"=","value"=>$userId],
                            ["field"=>"property_id","condition"=>"=","value"=>$propertyId],
                        ],
                    "with"=>["permissionGroup"],
                ];
            $userRelatedParams = $this->permissionGroupUserMappingService->findByCriteria($userRelatedParametersCriteria);
            $this->userData["userAllRelatedParams"] = $userRelatedParams;
            $this->userData["permission_group"] = [];
            foreach ($userRelatedParams as $perParam)
            {
                if ($perParam["permission_group"])
                {
                    $this->userData["permission_group"][] = $perParam["permission_group"];
                }

                if ($perParam["permission_group"]["is_admin"])
                {
                    $this->userData["is_admin"] = true;
                    $this->userData["selectedGroupMapping"] = $perParam;
                    return false;
                }

                if ($permissionGroupInfo && $perParam["permission_group"]["id"] == $permissionGroupInfo["permission_group_id"])
                {
                    $this->userData["relatedParameters"] = $perParam["relatedParametersArray"];
                    $this->userData["selectedGroupMapping"] = $perParam;
                }
            }

        } catch ( Exception $e )
        {
            return false;
        }
    }
}
