<div class="col-12">
    <div class="col-12">
        <button class="btn btn-dark mb-0" onclick="largeModal('refSettingsAddForm')">Добавить новую настройку</button>
    </div>

    {include file='main/datatable.tpl' tableTitle="Все настройки:"
    theads=[{$lang.datatable.uniq_id}, {$lang.datatable.group_name}, {$lang.datatable.ref_object_type}, {$lang.datatable.discount_percent}, {$lang.datatable.discount_sum}, {$lang.datatable.ref_operations}, {$lang.datatable.actions}]
    data=$referralSettings }


    <div id="refSettingsAddForm" class="hidden">
        <h5 class="mt-0">Новая настройка:</h5>
        <form method="POST">
            <input type="hidden" name="form_key" value="{$form_key}">
            <div class="row">
                <!-- Ваш селект -->
                <div class="col-6 mb-2" id="user_group_wrapper">
                    <label>Группа пользователей:</label>
                    <select class="form-select form-control" name="user_group_name" id="user_group_name">
                        <option value="" disabled selected>Не выбран</option>
                        {foreach $groups as $group}
                            <option value="{$group.id}">{$group.name}</option>
                        {/foreach}
                    </select>
                    <div class="text-danger small" id="error_user_group"></div>
                </div>

                <div class="col-6 mb-2" id="operation">
                    <label>При операции:</label>
                    <select class="form-select form-control" name="operation[]" id="operationSelect" multiple>
                        <option value="sale">Продажа</option>
                        <option value="pay_for_hidden_data">Оплата скрытых данных</option>
                        <option value="subscription">Подписка</option>
                    </select>
                    <div class="text-danger small" id="error_operation"></div>
                </div>

                <div class="col-6 mb-2">
                    <label>Реферральный процент:</label>
                    <input type="number" class="form-control" name="discount_percent" id="discount_percent">
                    <div class="text-danger small" id="error_percent"></div>
                </div>

                <div class="col-6 mb-2">
                    <label>Реферральная сумма:</label>
                    <input type="number" class="form-control" name="discount_sum" id="discount_sum">
                    <div class="text-danger small" id="error_sum"></div>
                </div>

                <div class="col-12">
                    <button type="submit" name="create_ref_settings" class="btn btn-success mt-4" id="submitButton">Добавить</button>
                </div>
            </div>
        </form>
    </div>

    <div id="refSettingsEditForm" class="hidden">
        <h5 class="mt-0">Редактирование настройки:</h5>
        <form method="POST">
            <input type="hidden" name="form_key" value="{$form_key}">
            <input type="hidden" id="refSettingsId" name="refSettingsId" value="">
            <div class="row">
                <!-- Ваш селект -->
                <div class="col-6 mb-2" id="user_group_wrapper">
                    <label>Группа пользователей:</label>
                    <select class="form-select form-control" name="user_group_name" id="user_group_name">
                        <option value="" disabled selected>Не выбран</option>
                        {foreach $groups as $group}
                            <option value="{$group.id}">{$group.name}</option>
                        {/foreach}
                    </select>
                </div>
                <div class="col-6 mb-2" id="operation">
                    <label>При операции:</label>
                    <select class="form-select form-control" name="operation[]" id="operation" multiple>
                        <option value="sale">Продажа</option>
                        <option value="pay_for_hidden_data">Оплата скрытых данных</option>
                        <option value="subscription">Подписка</option>
                    </select>
                </div>
                <div class="col-6 mb-2">
                    <label>Реферральный процент:</label>
                    <input type="number" class="form-control" name="discount_percent" id="discount_percent" placeholder="Введите процент">
                </div>
                <div class="col-6 mb-2">
                    <label>Реферральная сумма:</label>
                    <input type="number" class="form-control" name="discount_sum" id="discount_sum" placeholder="Введите сумму">
                </div>
                <div class="col-12">
                    <button type="submit" name="edit_ref_settings" class="btn btn-success mt-4" id="submitButton">Рекактировать</button>
                </div>
            </div>
        </form>
    </div>

</div>
<script>
    var currentLink = document.getElementById('referralSettings');
    currentLink.classList.add('active');
    $(document).ready(function () {

        $(".editRef").on("click", function () {
            var dataId = $(this).data("id");


            $.ajax({
                url: 'engine/ajax/lib/refSettings/get_ref_setting.php',
                type: 'POST',
                data: {
                    id: dataId
                },
                success: function (response) {
                    let data = JSON.parse(response);


                    $('#refSettingsEditForm #refSettingsId').val(data.id);
                    $('#refSettingsEditForm #user_group_name').val(data.object_id);
                    $('#refSettingsEditForm #operation').val(data.operations);
                    $('#refSettingsEditForm #discount_percent').val(data.discount_percent);
                    $('#refSettingsEditForm #discount_sum').val(data.discount_sum);

                },
                error: function (xhr, status, error) {
                    console.error('Ошибка:', error);
                }
            });

        })

        document.getElementById("submitButton").addEventListener("click", function(e) {
            let errors = 0;

            const user_group = document.getElementById("user_group_name");
            const operation = document.getElementById("operationSelect");
            const percent = document.getElementById("discount_percent");
            const sum = document.getElementById("discount_sum");

            document.getElementById("error_user_group").innerText = "";
            document.getElementById("error_operation").innerText = "";
            document.getElementById("error_percent").innerText = "";
            document.getElementById("error_sum").innerText = "";

            if (user_group.value === "") {
                document.getElementById("error_user_group").innerText = "Выберите группу";
                errors++;
            }

            if ([...operation.selectedOptions].length === 0) {
                document.getElementById("error_operation").innerText = "Выберите хотя бы одну операцию";
                errors++;
            }

            if (percent.value === "" && sum.value === "") {
                document.getElementById("error_percent").innerText = "Укажите процент или сумму";
                document.getElementById("error_sum").innerText = "Укажите процент или сумму";
                errors++;
            }

            if (percent.value !== "" && (percent.value < 0 || percent.value > 100)) {
                document.getElementById("error_percent").innerText = "Процент должен быть от 0 до 100";
                errors++;
            }

            if (sum.value !== "" && sum.value < 0) {
                document.getElementById("error_sum").innerText = "Сумма не может быть отрицательной";
                errors++;
            }

            if (errors > 0) {
                e.preventDefault();
            }
        });


    })
</script>