<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */

    function saveAccessSettings($resourceId, $resourceType, $excludedList, $includedList, $groups)
    {
        global $db_connect;

        $excludedList = array_unique($excludedList);
        $includedList = array_unique($includedList);

        // 1. Чистим старые настройки для ресурса
        $db_connect->delete('access_control', [
            "resource_id"   => $resourceId,
            "resource_type" => $resourceType
        ]);

        // 2. Сохраняем группы
        foreach ($groups as $group) {
            $db_connect->insert('access_control', [
                "group_id"      => $group,
                "resource_id"   => $resourceId,
                "resource_type" => $resourceType,
            ]);
        }

        // 3. Сохраняем include locations
        foreach ($includedList as $included) {
            $parentId = $db_connect->get("locations", "parent_id", [
                "id" => $included,
            ]);

            if ($parentId) {
                $db_connect->insert('access_control', [
                    "resource_id"   => $resourceId,
                    "resource_type" => $resourceType,
                    "location_id"   => (int)$parentId,
                    "list_type"   => 'include' // <-- чтобы отличать include/exclude
                ]);
            }

            $db_connect->insert('access_control', [
                "resource_id"   => $resourceId,
                "resource_type" => $resourceType,
                "location_id"   => (int)$included,
                "list_type"   => 'include'
            ]);
        }

        // 4. Сохраняем exclude locations
        foreach ($excludedList as $excluded) {
            $db_connect->insert('access_control', [
                "resource_id"   => $resourceId,
                "resource_type" => $resourceType,
                "location_id"   => (int)$excluded,
                "list_type"   => 'exclude'
            ]);
        }
    }

    function checkAssess($resourceId, $resourceType)
    {
        global $db_connect;
        $existsPermission = false;

        $hasAccessControl = $db_connect->has("access_control", [
            "resource_id"   => $resourceId,
            "resource_type" => $resourceType
        ]);

        if (!$hasAccessControl) {
            return true;
        }

        if (!empty($resourceId) && !empty($resourceType) && !empty($_SESSION["user_id"])) {
            $userLocation = $db_connect->get("location_list", "*", [
                "user_id" => $_SESSION["user_id"],
            ]);

            $detectedLocationId = $db_connect->get("users", "detected_location_id", ["id" => $_SESSION["user_id"]]);

            // 1. Если для detectedLocationId есть exclude → сразу запрещаем
            if (!empty($detectedLocationId)) {
                $isExcluded = $db_connect->has("access_control", [
                    "location_id"   => $detectedLocationId,
                    "resource_id"   => $resourceId,
                    "resource_type" => $resourceType,
                    "list_type"     => 'exclude'
                ]);

                if ($isExcluded) {
                    return false;
                }
            }

            // 2. Проверяем только userLocation (только include)
            if (!empty($userLocation)) {
                $existsPermission = $db_connect->has("access_control", [
                    "location_id"   => $userLocation["location_id"],
                    "resource_id"   => $resourceId,
                    "resource_type" => $resourceType,
                    "list_type"     => 'include'
                ]);

                if (!$existsPermission) {
                    return false; // если нет доступа по локации — сразу стоп
                }
            }

            // 3. Если дошли сюда → доступ разрешён
            return true;
        }

        return false;
    }
