<?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");

    global $db_connect;

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['zip_file'])) {
        $file = $_FILES['zip_file'];

        // Проверка на ошибки загрузки
        if ($file['error'] !== UPLOAD_ERR_OK) {
            die('Ошибка загрузки файла!');
        }

        // Директория для сохранения файла
        $uploadDir = $_SERVER["DOCUMENT_ROOT"] . '/uploads/versions/';

        // Создание папки, если её нет
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        $lastVersion = $db_connect->max("versions", "system_version");
        $lastVersion = $lastVersion == "" ? "0" : $lastVersion;

        $lastVersion += 0.0001;

        // Генерация уникального имени файла
        $fileName = date("Y-m-d")."-".$lastVersion."-".basename($file['name']);
        $filePath = $uploadDir . $fileName;

        $db_connect->update("versions", ["is_active" => 0], ["is_active" => 1]);

        $db_connect->insert("versions", [
            "system_version" => (float)$lastVersion,
            "release_date" => date("Y-m-d H:i:s"),
            "description" => "",
            "file_path" => "uploads/versions/$fileName",
            "is_active" => true
        ]);

        // Перемещение файла из временной директории
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            echo json_encode(['message' => 'Файл успешно загружен!', 'path' => $filePath]);
        } else {
            echo json_encode(['error' => 'Ошибка при сохранении файла!']);
        }
    } else {
        echo json_encode(['error' => 'Файл не передан!']);
    }