<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WhatsMasterGRM - Принудительное обновление базы</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/notyf/notyf.min.css">
</head>
<body>
    <h1>WhatsMasterGRM - Принудительное обновление базы</h1>

    <div class="container">
        <div class="block">
            <h2>Тильда - Таблица CSV</h2>
            <form id="uploadForm" enctype="multipart/form-data" method="post">
                <div class="input-row">
                    <input type="file" name="file" accept=".csv" required>
                </div>
                <div class="input-row">
                    <label class="container-checkbox">
                        Наличие WhatsApp
                        <input type="checkbox" name="verify_phone" value="1">
                        <span class="checkmark"></span>
                    </label>
                    <label class="container-checkbox">
                        Добавлять менеджера
                        <input type="checkbox" name="add_curator" value="1">
                        <span class="checkmark"></span>
                    </label>
                </div>
                <input id="uploadButton" type="submit" value="Загрузить пользователей">
            </form>
            <div id="result"></div>
        </div>

        <div class="block">
            <h2>Бизон 365 - API</h2>
            <div class="form-group">
                <label for="tokenInput">API-токен администратора Бизон 365:</label>
                <input type="text" id="tokenInput" placeholder="Введите токен">
            </div>
            <div class="form-group">
                <label for="dateInput">Крайняя дата выборки комнат:</label>
                <input type="date" id="dateInput">
            </div>
            <div class="form-group">
                <label for="typeSelect">Выбор формата вебинара:</label>
                <select id="typeSelect">
                    <option value="AutoWebinars">Автовебинарные комнаты</option>
                    <option value="LiveWebinars">Вебинарные комнаты</option>
                </select>
            </div>
            <button id="sendRequestButton">Получить список комнат Бизон 365</button>
            <div id="dropdown-container"></div>
            <button id="sendGetRequestButton">Обновить базу WhatsMasterGRM</button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/notyf/notyf.min.js"></script>
    <script>
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault();
            const form = new FormData(this);
            const notyf = new Notyf({
                duration: 5000,
                position: { x: 'right', y: 'top' }
            });
            notyf.open({
                type: 'info',
                message: 'Загрузка началась, пожалуйста, подождите'
            });
            fetch('/upload_csv', {
                method: 'POST',
                body: form
            })
            .then(response => response.json())
            .then(data => {
                notyf.open({
                    type: 'success',
                    message: data.message
                });
            })
            .catch(error => {
                console.error('Error:', error);
                notyf.open({
                    type: 'error',
                    message: 'Произошла ошибка при загрузке файла.'
                });
            });
        });

        document.getElementById('sendRequestButton').addEventListener('click', function() {
            const token = document.getElementById('tokenInput').value;
            const minDate = document.getElementById('dateInput').value;
            const type = document.getElementById('typeSelect').value;
            const url = '/send_request';
            fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ token, minDate, type }).toString()
            })
            .then(response => response.json())
            .then(data => {
                createDropdown(data);
            })
            .catch(error => {
                console.error('Error:', error);
                new Notyf().error('Ошибка: ' + error.message);
            });
        });

        function createDropdown(data) {
            const container = document.getElementById('dropdown-container');
            container.innerHTML = '';
            const select = document.createElement('select');
            select.id = 'dropdown';
            select.classList.add('form-group');
            data.forEach(item => {
                const option = document.createElement('option');
                option.value = item;
                option.text = item;
                select.appendChild(option);
            });
            container.appendChild(select);
            const sendGetRequestButton = document.getElementById('sendGetRequestButton');
            sendGetRequestButton.addEventListener('click', handleGetRequest);
        }

        function handleGetRequest() {
            const selectedValue = document.getElementById('dropdown').value;
            const token = document.getElementById('tokenInput').value;
            const getUrl = `/send_get_request?token=${encodeURIComponent(token)}&webinarId=${encodeURIComponent(selectedValue)}`;
            fetch(getUrl, { method: 'GET' })
            .then(response => response.json())
            .then(data => {
                new Notyf().success('Пользователи добавлены в базу данных WhatsMasterGRM');
            })
            .catch(error => {
                console.error('Error:', error);
                new Notyf().error('Ошибка: ' + error.message);
            });
        }
    </script>
</body>
</html>