<?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;
    $raw = file_get_contents("php://input");
    $locations = json_decode($raw, true); // получаем массив PHP

    if (!empty($locations)) {

        $mapNewIds = []; // временный ID -> реальный ID

        foreach ($locations as $loc) {
            $tempId = $loc['id'];
            $parent_id = $loc['parent_id'] ?? null;

            // Если parent тоже новый, заменяем на реальный ID
            if ($parent_id && strpos($parent_id, 'loc-') === 0) {
                $parent_id = $mapNewIds[$parent_id] ?? null;
            }

            $exists = false;

            if (strpos($tempId, 'loc-') === 0) {
                // Новая локация
                $db_connect->insert('locations', [
                    'type' => $loc['type'] == "null" ? "" : $loc['type'],
                    'parent_id' => $parent_id,
                    'slug' => $loc['slug'] == "null" ? "" : $loc['slug'],
                ]);
                $newId = $db_connect->id();
                $mapNewIds[$tempId] = $newId;

                // Добавляем перевод
                if ($exists) {
                    $db_connect->update('location_translations', [
                        'name' => $loc["name"]
                    ], [
                        'location_id'   => $newId,
                        'language_code' => $loc['lang']
                    ]);
                } else {
                    $db_connect->insert('location_translations', [
                        'location_id'   => $newId,
                        'language_code' => $loc['lang'],
                        'name'          => $loc["name"],
                    ]);
                }

            } else {
                // Обновление существующей локации
                $locationLangAssoc = $db_connect->get('location_translations', "*", ["location_id" => $tempId]);

                $db_connect->update('locations', [
                    'type' => $loc['type'] == "null" ? "" : $loc['type'],
                    'parent_id' => $parent_id,
                    'slug' => $loc['slug'] == "null" ? "" : $loc['slug'],
                ], ['id' => $tempId]);

                // Добавляем или обновляем перевод для нового языка
                $exists = $db_connect->has('location_translations', [
                    'location_id' => $tempId,
                    'language_code' => $locationLangAssoc['language_code']
                ]);

                if ($exists) {
                  /*  $db_connect->update('location_translations', [
                        'name' => $loc['name']
                    ], [
                        'location_id' => $tempId,
                        'language_code' => $loc['lang']
                    ]);*/
                } else {
                    $db_connect->insert('location_translations', [
                        'location_id' => $tempId,
                        'language_code' => $loc['lang'],
                        'name' => $loc['name']
                    ]);
                }
            }
        }


        echo json_encode(['status' => 'success', 'mapNewIds' => $mapNewIds]);


    }


   /* echo json_encode([
        "ws_config" => $ws_config,
        "token" => $db_connect->get("tokens", "token", ["user_id" => $_SESSION['user_id']]) ?? null
    ]);*/