<?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;
    header('Content-Type: application/json');

    $id = $_POST['id'] ?? null;

    if (!$id) {
        echo json_encode(['status' => 'error', 'message' => 'ID не указан']);
        exit;
    }

    // Опционально: удалить всех потомков рекурсивно
    function deleteLocationRecursive($db_connect, $id) {
        $children = $db_connect->select('locations', 'id', ['parent_id' => $id]);
        foreach ($children as $childId) {
            deleteLocationRecursive($db_connect, $childId);
        }
        $db_connect->delete('locations', ['id' => $id]);
    }

    // Если ID временный (new-*), то просто игнорируем
    if (strpos($id, 'loc-') === 0) {
        echo json_encode(['status' => 'success']);
        exit;
    }

    deleteLocationRecursive($db_connect, $id);

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