<?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");
    require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/ws_config.php');

    session_start();

    global $db_connect, $ws_config;

    header('Content-Type: application/json');

    $name      = trim($_POST["name"]);
    $alt_name  = trim($_POST["alt_name"]);
    $language  = trim($_POST["language"]);
    $id        = isset($_POST["id"]) ? (int)$_POST["id"] : null;
    $parentid  = isset($_POST["parentid"]) ? (int)$_POST["parentid"] : null;
    $table     = $_POST["moduleName"] . "_categories";

    if (empty($parentid)) {
        $parentid = $db_connect->get($table, "parentid", [
           "id" => $id
        ]);
    }

    if ($id && $_POST["action"] == "edit") {
        // Существующая категория — обновляем
        $db_connect->update($table, [
            "name" => $name,
            "alt_name" => $alt_name,
            "language" => $language,
            "parentid" => $parentid
        ], ["id" => $id]);

        echo json_encode(["success" => true, "message" => "Категория обновлена"]);
    } else if ($_POST["action"] == "add-child") {
        // Новая категория — добавляем
        $db_connect->insert($table, [
            "name" => $name,
            "alt_name" => $alt_name,
            "language" => $language,
            "parentid" => $id
        ]);

        echo json_encode(["success" => true, "message" => "Категория добавлена"]);
    }
