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

    // Путь к config.php относительно текущего файла
    require_once(ENGINE_DIR . '/data/config.php');
    $module_entity = 'auctions';

    // Сбрасываем счетчик автоинкремента к максимальному значению id
    require_once(ENGINE_DIR . '/mods/autoincrement.php');

        
    // Подключаем файл проверки зарезервированных URL и запрещённых символов
    require_once(SYSTEM_DIR . '/plugins/reserved_urls.php');

    // Получаем категории
    $categories = [];
    $result = $db_connect->select("auctions_categories", "*") ?? [];
    if (!empty($result["id"])) {
        $categories[] = $result;
    } else {
        foreach ($result as $row) {
            $categories[] = $row;
        }
    }

    $error_message = '';
    
    if (isset($_POST['addauction'])) {
        $folder = $_POST['folder'] ?? '';
        $p_id = (int)$db_connect->max("auctions", "id") + 1;

        $x_values = isset($_POST['x_value']) ? implode(', ', $_POST['x_value']) : '';
        $field_ids = $_POST['field_ids'] ?? [];
        $auctions_id = $p_id;


        $autor = isset($_POST['autor']) ? strip_tags(trim($_POST['autor'])) : '';
        $date = isset($_POST['date']) && !empty($_POST['date']) ? strip_tags(trim($_POST['date'])) : date($config['date_format']);
        $category = isset($_POST['category']) ? (is_array($_POST['category']) ? implode(', ', $_POST['category']) : $_POST['category']) : '';
        $language = isset($_POST['language']) ? (is_array($_POST['language']) ? implode(', ', $_POST['language']) : $_POST['language']) : '';
        $title = strip_tags(trim($_POST['title']));
        $alt_name = strip_tags(trim($_POST['alt_name']));
        $short_desc = htmlspecialchars($_POST['short_desc'], ENT_QUOTES);
		$full_desc = htmlspecialchars($_POST['full_desc'], ENT_QUOTES);
        
        $start_date = isset($_POST['start_at']) && !empty($_POST['start_at']) ? strip_tags(trim($_POST['start_at'])) : date($config['date_format']);
        $end_date = isset($_POST['end_at']) && !empty($_POST['end_at']) ? strip_tags(trim($_POST['end_at'])) : date($config['date_format']);
        $capacity = isset($_POST['capacity']) ? (is_array($_POST['capacity']) ? implode(', ', $_POST['capacity']) : $_POST['capacity']) : '';
        $status = isset($_POST['status']) ? (is_array($_POST['status']) ? implode(', ', $_POST['status']) : $_POST['status']) : '';

		$meta_desc = strip_tags(trim($_POST['meta_desc']));
		$meta_keys = strip_tags(trim($_POST['meta_keys']));
        $views = isset($_POST['views']) ? intval($_POST['views']) : 0;

        $result = $db_connect->insert("auctions", [
            "user_id" => $_SESSION["user_id"],
            "title" => $title,
            "short_desc" => $short_desc,
            "full_desc" => $full_desc,
            "start_price" => (int)$_POST['start_price'],
            "current_price" => (int)$_POST['current_price'],
            "buy_now_price" => (int)$_POST['buy_now_price'],
            "language" => $language == "" ? $_SESSION['lang'] : $language,
            "views" => $views,
            "meta_desc" => $meta_desc,
            "meta_keys" => $meta_keys,
            "status" => $status,
            "start_at" => $start_date,
            "end_at" => $end_date
        ]);

        $auctions_id = $db_connect->id();

        $image = null;
        if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
            $dir = 'uploads/images/auctions/' . date('Y') . '/' . date('m') . '/';
            $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/' . $dir;

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

           // $file_count = count(scandir($uploadDir)) - 1;
            $imageName = $p_id . '_'. basename($_FILES['image']['name']);
            $imagePath = $uploadDir . $imageName;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $imagePath)) {
                $image = $dir . $imageName;
            } else {
                $error_message = "Не удалось переместить загруженный файл.";
            }
        }


        if ($image) {
            $db_connect->insert("auction_images", [
                "auction_id" => $auctions_id,
                "img_path" => $image,
            ]);
        }


        if (!empty($_POST["category"])) {
            foreach ($_POST["category"] as $categoryId) {
                $db_connect->insert("auctions_cat_relations", [
                    "auctions_id" => (int)$auctions_id,
                    "category_id" => (int)$categoryId,
                ]);
            }
        }

        require_once ENGINE_DIR . '/mods/access_control.php';
        saveAccessSettings((int)$auctions_id, "auctions", $_POST["exclude_locations"] ?? [], $_POST["include_locations"] ?? [], $_POST["groups"]);

        if (!empty($field_ids)) {
            foreach ($field_ids as $field_id) {
                if (!empty($_POST['x_value'][$field_id])) {
                    $insertField = $db_connect->insert("auctions_field_values", [
                        "auctions_id" => $auctions_id,
                        "field_id" => $field_id,
                        "x_value" => $_POST['x_value'][$field_id]
                    ]);
                }
            }
        }
        if ($auctions_id) {
            header("Location: /admin?action=modules/auctions/list");
            exit();
        } else {
            $error_message .= "Ошибка при добавлении файла: " . $db_connect->error . "<br>";
        }

    }

    require_once(SYSTEM_DIR . '/plugins/extra_fields.php');

    $groups = $db_connect->select("roles", "*") ?? [];
    $smarty->assign('groups', $groups);

    $lastRow = $db_connect->get("auctions", ['id'], [
        "ORDER" => ["id" => "DESC"]
    ]);
    $yourData = array('title' => $lang['nav']['addauctions'] . ' - ' . $config['title']);
    $smarty->assign('data', $yourData);
    $smarty->assign('page_name', '
        <li class="breadcrumb-item active"><a href="/admin?action=auctions/list">' . $lang['topmenu']['auctions'] . '</a></li>
        <li class="breadcrumb-item active">' . $lang['nav']['addauctions'] . '</li>
    ');
    $smarty->assign('add_page', 'add_page');
	$smarty->assign('page_id', $lastRow["id"] ?? 0 + 1);
    $smarty->assign('max_id', 0 + 1);
    $smarty->assign('theme', SYSTEM_DIR);
    $smarty->assign('config', $config);
    $smarty->assign('categories', $categories);
    $smarty->assign('error_message', $error_message);