<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send Messages with Image</title>
    <style>
body {
    font-family: Arial, sans-serif;
    text-align: center;
    background-color: #f0f0f0;
    margin: 0;
    padding: 0;
    max-height: 250px; /* Устанавливаем максимальную высоту страницы */
}
h1 {
    background-color: #4CAF50;
    color: white;
    padding: 20px;
    margin: 0;
    border-bottom: 2px solid #388E3C;
}
.input-row {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
}
.input-row input, .input-row textarea {
    padding: 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 5px;
}
#messageInput {
    width: 80%;
    margin-top: 20px;
    height: 60px; /* Устанавливаем высоту поля ввода текста */
}
#progressBarContainer {
    width: 80%;
    margin: 20px auto;
}
#progressBar {
    width: 100%;
    background-color: #ddd;
}
#progress {
    width: 0%;
    height: 30px;
    background-color: #4CAF50;
    text-align: center;
    line-height: 30px;
    color: white;
}
#sendButton {
    color: white;
    background-color: #4CAF50;
    border: none;
    cursor: pointer;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 5px;
    margin-top: 20px;
}
#sendButton:hover {
    background-color: #388E3C;
}
    </style>
</head>
<body>
    <h1></h1>
    <div class="input-row">
        <input type="text" id="apiKeyInput" placeholder="Введите API ключ">
        <input type="number" id="minDelayInput" placeholder="Min Delay (ms)" value="500">
        <input type="number" id="maxDelayInput" placeholder="Max Delay (ms)" value="1000">
    </div>
    <textarea id="messageInput" placeholder="Введите текст сообщения с вариантами в фигурных скобках, например: {Привет|Hello|Hola}, (отправка ссылок на сторонние ресурсы поддерживается, показа превью ссылки в этом типе отправки нет)."></textarea>
    <div id="progressBarContainer">
        <div id="progressBar">
            <div id="progress">0%</div>
        </div>
    </div>
    <input type="file" id="fileInput" accept=".txt">
    <button id="sendButton">Запустить рассылку</button>

    <script>
        document.getElementById('sendButton').addEventListener('click', function() {
            const apiKey = document.getElementById('apiKeyInput').value;
            const urlFile = localStorage.getItem('fileUrl');
            const fileName = localStorage.getItem('filename');
            const messageTemplate = document.getElementById('messageInput').value;
            const minDelay = parseInt(document.getElementById('minDelayInput').value) || 500;
            const maxDelay = parseInt(document.getElementById('maxDelayInput').value) || 10000;
            if (!apiKey) {
                alert('Please enter your API key.');
                return;
            }
            if (!urlFile) {
                alert('URL of the file is not found in local storage.');
                return;
            }
            if (!fileName) {
                alert('File name is not found in local storage.');
                return;
            }
            if (!messageTemplate) {
                alert('Please enter a message template.');
                return;
            }
            if (minDelay >= maxDelay) {
                alert('Min delay must be less than max delay.');
                return;
            }
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                alert('Please select a file.');
                return;
            }
            console.log('URL файла:', urlFile);
            console.log('Имя файла:', fileName);
            const reader = new FileReader();
            reader.onload = function(event) {
                const text = event.target.result;
                const phones = text.split('\n').map(phone => phone.trim()).filter(phone => phone);
                sendMessages(phones, apiKey, urlFile, fileName, messageTemplate, minDelay, maxDelay);
            };
            reader.readAsText(file);
        });

        function randomizeMessage(template) {
            return template.replace(/\{([^}]+)\}/g, (match, p1) => {
                const choices = p1.split('|');
                return choices[Math.floor(Math.random() * choices.length)];
            });
        }

        async function sendMessages(phones, apiKey, urlFile, fileName, messageTemplate, minDelay, maxDelay) {
            const totalPhones = phones.length;
            const progressBar = document.getElementById('progress');
            for (let i = 0; i < totalPhones; i++) {
                const phone = phones[i];
                const message = randomizeMessage(messageTemplate);
                try {
                    const response = await fetch(`https://api.green-api.com/waInstance1101952913/sendFileByUrl/${apiKey}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            chatId: `${phone}@c.us`,
                            urlFile: urlFile,
                            fileName: fileName,
                            caption: message
                        })
                    });
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();
                    console.log(`Message sent to ${phone}:`, data);
                } catch (error) {
                    console.error(`Error sending message to ${phone}:`, error);
                }
                const progress = ((i + 1) / totalPhones) * 100;
                progressBar.style.width = `${progress}%`;
                progressBar.textContent = `${progress.toFixed(2)}%`;
                if (i < totalPhones - 1) {
                    const randomDelay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
                    await new Promise(resolve => setTimeout(resolve, randomDelay));
                }
            }
        }
    </script>
</body>
</html>