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

    // Путь к config.php относительно текущего файла
    require_once(ENGINE_DIR . '/data/config.php');

// Получаем список всех групп


    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["create-group"])) {
        $last_id = $db_connect->max("roles", "id");

        $data = [
            "id" => $last_id + 1,
            "name" => $_POST['name'],
            "create" => isset($_POST['create']) == "on" ? 1 : 0,
            "read" => isset($_POST['read']) == "on" ? 1 : 0,
            "update" => isset($_POST['update']) == "on" ? 1 : 0,
            "del" => isset($_POST['delete']) == "on" ? 1 : 0,
            "vote" => isset($_POST['vote']) == "on" ? 1 : 0,
            "download" => isset($_POST['download']) == "on" ? 1 : 0,
            "mna" => isset($_POST['mna']) == "on" ? 1 : 0,
            "mnu" => isset($_POST['mnu']) == "on" ? 1 : 0,
            "mns" => isset($_POST['mns']) == "on" ? 1 : 0,
            "mnr" => isset($_POST['mnr']) == "on" ? 1 : 0,
            "view_in_registration" => isset($_POST['view_in_registration']) == "on" ? 1 : 0,

        ];
        $inserted = $db_connect->insert("roles", $data);

        header("Location: ".$_SERVER["HTTP_REFERER"]);

    }

    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST["update-group"])) {
        $uGroup = $db_connect->update("roles", [
            "name" => $_POST['name'],
            "create" => isset($_POST['create']) == "on" ? 1 : 0,
            "read" => isset($_POST['read']) == "on" ? 1 : 0,
            "update" => isset($_POST['update']) == "on" ? 1 : 0,
            "del" => isset($_POST['delete']) == "on" ? 1 : 0,
            "vote" => isset($_POST['vote']) == "on" ? 1 : 0,
            "download" => isset($_POST['download']) == "on" ? 1 : 0,
            "mna" => isset($_POST['mna']) == "on" ? 1 : 0,
            "mnu" => isset($_POST['mnu']) == "on" ? 1 : 0,
            "mns" => isset($_POST['mns']) == "on" ? 1 : 0,
            "mnr" => isset($_POST['mnr']) == "on" ? 1 : 0,
            "view_in_registration" => isset($_POST['view_in_registration']) == "on" ? 1 : 0,
        ], ["id" => $_POST["group_id"]]);

        header("Location: ".$_SERVER["HTTP_REFERER"]);
    }

/*    $groups = $db_connect->select("groups", "*");

// Для каждой группы получаем количество пользователей
    foreach ($groups as &$group) {
        $user_count = $db_connect->count("users", [
            "group" => $group["id"]
        ]);
        $group["users"] = $user_count;
    }
    $smarty->registerPlugin('modifier', 'json_encode', function($value) {
        return json_encode($value);
    });*/
  /*  foreach ($groups as $key => &$row) {
        $row['index'] = $key + 1;
        $row["CR"] = $row["create"] ? 1 : 0;
        $row["RE"] = $row["read"] ? 1 : 0;
        $row["UP"] = $row["update"] ? 1 : 0;
        $row["DE"] = $row["del"] ? 1 : 0;
        $row["VT"] = $row["vote"] ? 1 : 0;
        $row["DL"] = $row["download"] ? 1 : 0;
        $row["AP"] = $row["mna"] ? 1 : 0;
        $row["UM"] = $row["mnu"] ? 1 : 0;
        $row["SM"] = $row["mns"] ? 1 : 0;
        $row["RM"] = $row["mnr"] ? 1 : 0;
        $row["UC"] = $row["users"] ? 1 : 0;
    }*/



    $modules = $db_connect->select("permissions", ["module"], [
        "GROUP" => "module", "ORDER" => ["module" => "ASC"]
    ]);

    $roles = $db_connect->select("roles", ["id", "name"]);

    $rolePermissions = $db_connect->select("role_permissions", [
        "[>]permissions" => ["permission_id" => "id"]
    ], [
        "role_permissions.role_id",
        "permissions.module",
        "permissions.code"
    ]);

    $columns = [
        'C' => ['create'],
        'R' => ['view', 'read', 'access'],
        'U' => ['edit', 'update'],
        'D' => ['delete', 'del'],
        'P' => ['publish', 'approve'],
        'M' => ['manage', 'mna', 'mnu', 'mnr'],
        'A' => ['add'],
        'S' => ['settings', 'mns'],
        'G' => ['allmodules'],
    ];

    // Формируем матрицу по ролям
    $matrix = [];
    foreach ($rolePermissions as $rp) {
        $matrix[$rp['role_id']][$rp['module']][] = $rp['code'];
    }

    $smarty->assign('matrixJson', json_encode($matrix));

    $smarty->assign('roles', $roles);
    $smarty->assign('columns', array_keys($columns));
    $smarty->assign('matrix', $matrix);
    $smarty->assign('columnsKeys', $columns);
    $smarty->assign('modules', $modules);


// Устанавливаем массив переменных в Smarty
    $smarty->assign('rows', $groups);
    $yourData = array('title' => $lang['nav']['rolesandrights'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active">' . $lang['nav']['rolesandrights'] . '</li>
    ');
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);