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

    session_start();
    global $db_connect;

    $userId = $_SESSION['user_id'] ?? 0;
    if (!$userId) {
        echo json_encode(['success' => 0, 'error' => 'Необходимо авторизоваться']);
        exit;
    }

    $co_buying_id = intval($_POST['co_id'] ?? 0);
    $paid_amount = floatval($_POST['amount'] ?? 0);
    if ($co_buying_id <= 0 || $paid_amount <= 0) {
        echo json_encode(['success' => 0, 'error' => 'Некорректные данные']);
        exit;
    }

    // Получаем СП
    $co_buying = $db_connect->get("co_buyings", "*", ["id" => $co_buying_id, "status" => "active"]);
    if (!$co_buying) {
        echo json_encode(['success' => 0, 'error' => 'СП не найдено или не активно']);
        exit;
    }

    // Проверка лимитов
    $current_participants = $db_connect->count("co_buyings_participants", ["co_buying_id" => $co_buying_id]);
    if ($co_buying['max_participants'] && $current_participants >= $co_buying['max_participants']) {
        echo json_encode(['success' => 0, 'error' => 'Достигнут максимум участников']);
        exit;
    }

    // Проверка участия пользователя
    $alreadyJoined = $db_connect->get("co_buyings_participants", "*", ["co_buying_id" => $co_buying_id, "user_id" => $userId]);
    if ($alreadyJoined) {
        echo json_encode(['success' => 0, 'error' => 'Вы уже участвуете']);
        exit;
    }

    // Вставка участия
    $db_connect->insert("co_buyings_participants", [
        "co_buying_id" => $co_buying_id,
        "user_id" => $userId,
        "paid_amount" => $paid_amount,
        "date_paid" => date("Y-m-d H:i:s")
    ]);

    // Обновление текущей суммы
    $db_connect->update("co_buyings", [
        "current_amount[+]" => $paid_amount
    ], ["id" => $co_buying_id]);

    echo json_encode(['success' => 1, 'message' => 'Вы успешно присоединились к СП']);

