<?php


namespace App\Core\Service;


use App\Core\Repository\Permission\PermissionRepository;
use App\Core\Repository\PermissionGroupMapping\PermissionGroupMappingRepository;
use App\Core\Repository\PermissionGroupUserMapping\PermissionGroupUserMappingRepository;
use App\Core\Service\UserService;
use Exception;
use Illuminate\Support\Facades\Log;

class PermissionService
{

    private $permissionRepository;
    private $permissionGroupUserMappingRepository;
    private $permissionGroupMappingRepository;
    private $userService;

    public function __construct
    (
        PermissionRepository $permissionRepository,
        PermissionGroupUserMappingRepository $permissionGroupUserMappingRepository,
        PermissionGroupMappingRepository $permissionGroupMappingRepository,
        UserService $userService
    ) {
        $this->permissionRepository = $permissionRepository;
        $this->permissionGroupUserMappingRepository = $permissionGroupUserMappingRepository;
        $this->permissionGroupMappingRepository = $permissionGroupMappingRepository;
        $this->userService = $userService;
    }

    public function findByCriteria ( array $params )
    {
        return $this->permissionRepository->findByCriteria ( $params );
    }

    public function getPermissionMenuModelWithCriteria ( array $params )
    {
        return $this->permissionRepository->permissionMenuModelFindByCriteria ( $params );
    }

    public function getMenuTreeForUser ( $params)
    {
        try
        {

            $user_id = fillOnUndefined($params, 'user_id');
            $property_id = fillOnUndefined($params, 'property_id');
            $locale = fillOnUndefined($params,'locale', 'en');

            $isAdmin = false;
            $groupUserMappingCriteria =
                [
                    "criteria" =>
                        [
                            [ "field" => "user_id", "condition" => "=", "value" => $user_id ],
                            [ "field" => "property_id", "condition" => "=", "value" => $property_id ],
                            [ "field" => "status", "condition" => "=", "value" => 1 ]
                        ],
                    "with"     => [ "permissionGroup" ]
                ];
            $groupUserMapping = $this->permissionGroupUserMappingRepository->findByCriteria ( $groupUserMappingCriteria );
            $groupIds = pickItemFromArray ( "permission_group_id", $groupUserMapping );


            foreach ($groupUserMapping as $perMapping)
            {
                if ($perMapping[ "permission_group" ][ "is_admin" ])
                {
                    $isAdmin = true;
                    $groupIds = [ ];
                }
            }

            $permissionIds = [ ];
            if ($groupIds)
            {
                $groupMappingCriteria =
                    [
                        "whereIn" =>
                            [
                                [ "field" => "permission_group_id", "value" => $groupIds ]
                            ],
                    ];
                $groupMapping = $this->permissionGroupMappingRepository->findByCriteria ( $groupMappingCriteria );
                $permissionIds = pickItemFromArray ( "permission_id", $groupMapping );
            }

            $permissionMenuCriteria =
                [
                    "criteria"     =>
                        [
                            [ "field" => "parent_id", "condition" => "=", "value" => null ]
                        ],
                    "orderBy"      => [ [ "field" => "menu_order", "value" => "ASC" ] ],
                    "withCriteria" =>
                        [
                            [
                                "method"  => "children",
                                "whereIn" =>
                                    [
                                        [ "field" => "id", "value" => $permissionIds ]
                                    ],
                                "orderBy" =>
                                    [
                                        [ "field" => "menu_order", "value" => "ASC" ]
                                    ]
                            ]
                        ]
                ];


            if ($permissionIds)
            {
                $permissionMenuCriteria[ "whereIn" ] =
                    [
                        [ "field" => "id", "condition" => "=", "value" => $permissionIds ]
                    ];
            }
            else
            {
                $userInfo = $this->userService->findUser($user_id);
                if(!$userInfo["isSuperUser"] && !$isAdmin)
                {
                    return [];
                }
                $permissionMenuCriteria['withCriteria'][] =
                [
                    "method"  => "children",
                    "orderBy" =>
                        [
                            [ "field" => "menu_order", "value" => "ASC" ]
                        ]
                ];
            }

            $permissionMenu = $this->getPermissionMenuModelWithCriteria ( $permissionMenuCriteria );
            $reDesignMenu = [
                'permission_menu' => $permissionMenu,
                'locale' => $locale
            ];

           return $this->designPermissionMenu($reDesignMenu);

        } catch ( Exception $e )
        {
            return [ ];
        }
    }

    public  function designPermissionMenu($params){
        try{
            $return = [];
            $permissionMenu = fillOnUndefined($params , 'permission_menu', []);
            $locale = fillOnUndefined($params , 'locale');
            foreach ($permissionMenu as $param){
                $menu = collect($param);
                $filtered = $menu->only('id', 'name', 'code', 'children', 'component', 'menu_order','url')->toArray();
                if(!empty($filtered['children'])){
                    $reDesignMenu = [
                        'permission_menu' => $filtered['children'],
                        'locale' => $locale,
                    ];
                    $filtered['children'] = $this->designPermissionMenu($reDesignMenu);
                }


                $return[] = $filtered ;
            }
            return $return ;

        }catch ( Exception $e )
        {
            return [ ];
        }
    }

}
