<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if($_SESSION['svt_si']!=session_id()) {
    die();
}
require_once("../../db/connection.php");
require_once("../functions.php");
$id_user = $_SESSION['id_user'];
session_write_close();
$id_virtualtour = (int)$_POST['id_virtualtour'];
$language = strip_tags($_POST['language']);
if(get_user_role($id_user)=='administrator') {
    $where_user = "";
} else {
    $where_user = " AND v.id_user = $id_user ";
}
$settings = get_settings();
$default_language = $settings['language'];
$virtual_tour = get_virtual_tour($id_virtualtour,$id_user);
$vt_language = $virtual_tour['language'];
if(empty($vt_language)) $vt_language=$default_language;
$array = [];
if(empty($language) || $language==$vt_language) {
    $query = "SELECT r.id, r.name FROM svt_rooms as r 
              JOIN svt_virtualtours as v ON v.id = r.id_virtualtour
              WHERE v.id = $id_virtualtour $where_user
              GROUP BY r.id, r.priority
              ORDER BY r.priority ASC, r.id ASC";
} else {
    $query = "SELECT r.id, COALESCE(rl.name, r.name) as name FROM svt_rooms as r 
              JOIN svt_virtualtours as v ON v.id = r.id_virtualtour
              LEFT JOIN svt_rooms_lang as rl ON rl.id_room = r.id AND rl.language = '$language'
              WHERE v.id = $id_virtualtour $where_user
              GROUP BY r.id, r.priority
              ORDER BY r.priority ASC, r.id ASC";
}
$result = $mysqli->query($query);
if($result && $result->num_rows > 0) {
    while($row = $result->fetch_array(MYSQLI_ASSOC)) {
        $array[$row['id']] = $row['name'];
    }
}
$array2 = [];
$array_id_rooms = [];
$query = "SELECT list_alt FROM svt_virtualtours WHERE id=$id_virtualtour LIMIT 1;";
$result = $mysqli->query($query);
if($result && $result->num_rows == 1) {
    $row = $result->fetch_array(MYSQLI_ASSOC);
    $list_alt = $row['list_alt'];
    $list_alt_lang = '';
    if(!empty($language) && $language!=$vt_language) {
        $query_l = "SELECT list_alt FROM svt_virtualtours_lang WHERE id_virtualtour = $id_virtualtour AND language = '$language' LIMIT 1;";
        $result_l = $mysqli->query($query_l);
        if($result_l && $result_l->num_rows == 1) {
            $row_l = $result_l->fetch_array(MYSQLI_ASSOC);
            $list_alt_lang = $row_l['list_alt'];
        }
    }
    if(!empty($list_alt_lang)) {
        $list_alt = merge_json_rooms_list($list_alt, $list_alt_lang);
    }
    if(empty($list_alt)) {
        foreach($array as $id => $name) {
            $array2[] = ["id" => $id, "type" => "room", "hide" => 0, "name" => $name];
        }
    } else {
        $list_alt_array = json_decode($list_alt, true);
        foreach ($list_alt_array as $item) {
            $array2[] = parse_item_recursive($item, $array, $array_id_rooms);
        }
        foreach ($array as $id => $name) {
            if (!in_array($id, $array_id_rooms)) {
                $array2[] = ["id" => $id, "type" => "room", "hide" => 0, "name" => $name];
            }
        }
    }
}
ob_end_clean();
echo json_encode($array2);

function parse_item_recursive($item, &$room_names, &$array_id_rooms) {
    if ($item['type'] === 'room') {
        if (array_key_exists($item['id'], $room_names)) {
            $array_id_rooms[] = $item['id'];
            return [
                "id" => $item['id'],
                "type" => "room",
                "hide" => $item['hide'],
                "name" => $room_names[$item['id']]
            ];
        }
    } elseif ($item['type'] === 'category') {
        $childrens = [];
        if (!empty($item['children'])) {
            foreach ($item['children'] as $child) {
                $parsed_child = parse_item_recursive($child, $room_names, $array_id_rooms);
                if ($parsed_child !== null) {
                    $childrens[] = $parsed_child;
                }
            }
        }
        return [
            "id" => $item['id'],
            "type" => "category",
            "name" => $item['cat'],
            "childrens" => $childrens
        ];
    }
    return null;
}

function merge_json_rooms_list($json1, $json2) {
    $array1 = json_decode($json1, true);
    $array2 = json_decode($json2, true);
    if (empty($array2)) return json_encode($array1);
    $categoryMap = [];
    build_category_map($array2, $categoryMap);
    apply_category_map($array1, $categoryMap);
    return json_encode($array1);
}

function build_category_map($categories, &$map) {
    foreach ($categories as $cat) {
        if (isset($cat['type']) && $cat['type'] === 'category') {
            $map[$cat['id']] = $cat['cat'];
            if (!empty($cat['children']) && is_array($cat['children'])) {
                build_category_map($cat['children'], $map);
            }
        }
    }
}

function apply_category_map(&$categories, $map) {
    foreach ($categories as &$item) {
        if (isset($item['type']) && $item['type'] === 'category') {
            if (isset($map[$item['id']])) {
                $item['cat'] = $map[$item['id']];
            }
            if (!empty($item['children']) && is_array($item['children'])) {
                apply_category_map($item['children'], $map);
            }
        }
    }
}