<?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.                                                      *
        *****************************************************************************
    */

	$file = '';
	$error_message = ''; // Добавляем переменную для хранения сообщений об ошибках
	
	// Проверка загруженного файла
	if (isset($_FILES['file']) && $_FILES['file']['error'] == UPLOAD_ERR_OK) {
		$dir = 'uploads/files/' . $folder . '/' . date('Y') . '/' . date('m') . '/';
		$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/' . $dir;
	
		if (!is_dir($uploadDir)) {
			mkdir($uploadDir, 0777, true);
		}
	
		$file_count = count(scandir($uploadDir)) - 1;
		$fileName = $p_id . '_' . $file_count . '_' . basename($_FILES['file']['name']);
		$filePath = $uploadDir . $fileName;
	
		if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
			$file = $dir . $fileName;
		} else {
			$error_message = "Не удалось переместить загруженный файл.";
		}
	}
	
	// Если новый файл не загружен, используем текущее значение из БД (если оно есть)
	if (empty($file)) {
        $stmtfile = $db_connect->get($folder, "*", [
            "id" => $p_id,
        ]);
	
		if ($stmtfile === false) {
			$error_message = "MySQL prepare statement failed: " . $db_connect->error;
		} else {
			$resultfile = $stmtfile;

            if (!empty($resultfile["id"])) {
                $file = $resultfile["file_path"];
            }
		}
	}

    $stmtupdate = $db_connect->update($folder, ["file_path" => $file], ["id" => $p_id]);

	if ($stmtupdate === false) {
		$error_message = "MySQL prepare statement failed: " . $db_connect->error;
	}
	
	// Передаем сообщение об ошибке в Smarty
	$smarty->assign('error_message', $error_message);