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

define('ENGINE_DIR', $_SERVER['DOCUMENT_ROOT'] . '/engine');
require_once($_SERVER["DOCUMENT_ROOT"] . '/engine/data/config.php');
require_once($_SERVER["DOCUMENT_ROOT"] . "/engine/data/dbconfig.php");

$placesLeft = "";
$participationWidget = [];
$progress = "";
$winnerExists = false;
$settings = [
    "rgb_first" => null,
    "rgb_second" => null,
];
session_start();

$session_lang_key = $config['lang_union'] ? 'lang' : 'language';

$lang_code = isset($_SESSION[$session_lang_key]) ? $_SESSION[$session_lang_key] : $config['default_lang'];

// Преобразуем язык в нижний регистр
$lang_code = strtolower($lang_code);

// Загружаем языковой файл
$lang = load_language($lang_code);

$parentWidgetText = "";
$existsParent = false;
if (!empty($_POST["uniq_name"])) {
    $uniqName = $_POST["uniq_name"];

    $participationWidget = $db_connect->get("participations", "*", ["uniq_name" => $uniqName]);
    if (!empty($participationWidget)) {
        $participationUsers = $db_connect->select("participation_users", "*", ["participation_id" => $participationWidget["id"]]) ?? [];
        $placesLeft = $participationWidget["max_user_count"] - count($participationUsers);

        $settings = json_decode($participationWidget["settings"], true);

        $existsParent = !empty($settings["parent_widget_id"]) ? $settings["parent_widget_id"] : false;
        if (!empty($existsParent)) {
            if ($db_connect->get("participation_users", "id", ["participation_id" => $existsParent, "winned" => 1])) {
                $existsParent = false;
            } else {
                $parentWidget = $db_connect->get("participations", "*", ["id" => $existsParent]);
                $parentWidgetText = "{$lang["widgets"]["openafter"]} (" . $parentWidget["name"] . ")";
            }
        }

        $maxUsers = $participationWidget["max_user_count"];
        $currentUsers = count($participationUsers);

        $progress = ($currentUsers / $maxUsers) * 100;
        $progress = min(100, max(0, $progress)); // Ограничиваем от 0 до 100

        $progress = round($progress, 2) . "%";

        if ($placesLeft == 0) {
            $userWinner = $db_connect->get("participation_users", "*", [
                "participation_id" => $participationWidget["id"],
                "winned" => 1
            ]);
            if (empty($userWinner)) {
                $winner = $db_connect->query("SELECT user_id FROM `participation_users` ORDER BY RAND() LIMIT 1")->fetch();
                if ($winner) {
                    $userName = $db_connect->get("users", "name", ["id" => $winner]);


                    if (!$userWinner) {
                        $db_connect->update("participation_users", [
                            "winned" => 1,
                        ], [
                            "participation_id" => $participationWidget["id"],
                            "user_id" => $winner
                        ]);
                    }

                    $placesLeftText =  "{$lang["widgets"]["winner"]} ".$userName;
                    $winnerExists = true;
                }
            } else {
                $userName = $db_connect->get("users", "name", ["id" => $userWinner["user_id"]]);
                $placesLeftText =  "{$lang["widgets"]["winner"]} ".$userName;
                $winnerExists = true;
            }

        } else {
            $placesLeftText = "{$lang["widgets"]["leftpositions"]} ".$placesLeft." из ".$maxUsers;
        }

    }
}

function load_language($lang_code) {
    // Путь к основному языковому файлу
    $lang_file = ENGINE_DIR . "/lang/{$lang_code}/website.lng"; // Путь к языковому файлу для админки
    $fields_file = ENGINE_DIR . "/lang/{$lang_code}/fields.lng"; // Путь к языковому файлу для полей

    // Загружаем основной языковой файл
    if (file_exists($lang_file)) {
        $lang = include $lang_file; // Возвращаем массив
    } else {
        // Если язык не найден, используем язык по умолчанию (например, русский)
        $lang = include ENGINE_DIR . "/lang/russian/website.lng"; // Путь к русскому файлу
    }

    // Загружаем файл для полей, если он существует
    if (file_exists($fields_file)) {
        $fields = include $fields_file; // Возвращаем массив полей
        // Объединяем массивы
        $lang = array_merge($lang, $fields);
    } else {
        // Если файл для полей не найден, используем данные по умолчанию
        $fields_default = include ENGINE_DIR . "/lang/russian/fields.lng";
        $lang = array_merge($lang, $fields_default);
    }
    return $lang;
}

echo json_encode([
   "parentWidgetText" => $parentWidgetText,
   "existsParent" => $existsParent,
   "settings" => $settings,
   "placesLeftText" => $placesLeftText ?? "",
   "placesLeft" => $placesLeft,
   "participationWidget" => $participationWidget,
   "progress" => $progress,
   "winnerExists" => $winnerExists
]);
