<?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.                                                      *
    *****************************************************************************
*/

require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

$sourceList = $_POST['selectedData'] ?? '';

foreach ($sourceList as $sourceAssoc) {
    $source = $_SERVER["DOCUMENT_ROOT"] . "/" . $sourceAssoc["dataPath"];

    $read = isset($_POST['read']) == "on";
    $write = isset($_POST['write']) == "on";
    $execute = isset($_POST['execute']) == "on";
    $perms = isset($_POST['perms']) == "" ? null : (int)$_POST['perms'];

    try {
        if (setCustomPermissions($source, $read, $write, $execute, $perms)) {
            echo json_encode([
                "status" => true,
                "message" => "Права для '$source' успешно установлены."
            ]);
        } else {
            echo json_encode([
                "status" => false,
                "message" => "Не удалось установить права для '$source'."
            ]);
        }
    } catch (Exception $e) {
        echo json_encode([
            "status" => false,
            "message" => "Ошибка: " . $e->getMessage()
        ]);
    }
}

function setCustomPermissions(string $path, bool $read = true, bool $write = false, bool $execute = false, ?int $numericPermissions = null): bool
{
    if (!file_exists($path)) {
        throw new InvalidArgumentException("Путь не найден: $path");
    }

    if ($numericPermissions !== null) {
        // Устанавливаем права напрямую из числового формата
        if (!chmod($path, $numericPermissions)) {
            echo json_encode([
                "status" => false,
                "message" => "Не удалось установить права в числовом формате для: $path"
            ]);
            exit();
        }
        return true;
    }

    // Формируем права для владельца, группы и остальных
    $owner = ($read ? 4 : 0) + ($write ? 2 : 0) + ($execute ? 1 : 0);
    $group = ($read ? 4 : 0) + ($write ? 2 : 0) + ($execute ? 1 : 0);
    $others = ($read ? 4 : 0) + ($write ? 2 : 0) + ($execute ? 1 : 0);

    // Преобразуем права в восьмеричный формат
    $permissions = intval("{$owner}{$group}{$others}", 8);

    if (!chmod($path, $permissions)) {
        echo json_encode([
            "status" => false,
            "message" => "Не удалось установить права для: $path"
        ]);
        exit();
    }

    return true;
}
