document.addEventListener('DOMContentLoaded', function() {
    const configForm = document.getElementById('configForm');
    const toastElement = document.getElementById('liveToast');
    const toast = new bootstrap.Toast(toastElement);
    const toastMessage = document.getElementById('toastMessage');

    function showToast(message, type = 'info') {
        toastMessage.textContent = message;
        toast.show();
    }

    if (configForm) {
        configForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(configForm);
            
            fetch('save_config.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Configuration saved successfully!', 'success');
                } else {
                    showToast('Error: ' + data.error, 'danger');
                }
            })
            .catch(error => {
                showToast('An error occurred while saving.', 'danger');
            });
        });
    }

    const btnTestSahur = document.getElementById('btnTestSahur');
    if (btnTestSahur) {
        btnTestSahur.addEventListener('click', function() {
            fetch('test_sahur.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Sahur test triggered! Check logs.', 'success');
                    setTimeout(() => location.reload(), 1500);
                }
            });
        });
    }

    const refreshLogs = document.getElementById('refreshLogs');
    if (refreshLogs) {
        refreshLogs.addEventListener('click', function() {
            location.reload();
        });
    }

    const btnStartBot = document.getElementById('btnStartBot');
    const btnStopBot = document.getElementById('btnStopBot');
    const btnRestartBot = document.getElementById('btnRestartBot');

    if (btnStartBot) {
        btnStartBot.addEventListener('click', () => manageBot('start'));
    }
    if (btnStopBot) {
        btnStopBot.addEventListener('click', () => manageBot('stop'));
    }
    if (btnRestartBot) {
        btnRestartBot.addEventListener('click', () => manageBot('restart'));
    }

    function manageBot(action) {
        fetch('manage_bot.php?action=' + action)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast('Bot ' + action + 'ed successfully!', 'success');
                setTimeout(() => location.reload(), 2000);
            } else {
                showToast('Error: ' + data.error, 'danger');
            }
        })
        .catch(error => {
            showToast('An error occurred.', 'danger');
        });
    }
});
