
// Add this to the DOMContentLoaded event listener
document.addEventListener('DOMContentLoaded', function() {
    // Quick Send functionality
    document.querySelector('.sidebar-menu a[data-tab="quick-send"]')?.addEventListener('click', loadQuickSendData);
    document.getElementById('quick-send-template')?.addEventListener('change', updateQuickSendPreview);
    document.getElementById('quick-send-button')?.addEventListener('click', sendQuickMessages);
});

// Load templates and phone numbers for Quick Send
async function loadQuickSendData() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) return;

        // Load templates
        const templatesResponse = await fetch(`/api/get-templates?api_key=${apiKey}`);
        const templatesData = await templatesResponse.json();

        // Load phone number categories
        const numbersResponse = await fetch(`/api/get-phone-categories?api_key=${apiKey}`);
        const numbersData = await numbersResponse.json();

        if (templatesData.success && numbersData.success) {
            // Store templates globally
            templates = templatesData.templates;
            populateQuickSendTemplates(templatesData.templates);
            populateQuickSendNumbers(numbersData.categories);
        }
    } catch (error) {
        console.error('Error loading Quick Send data:', error);
        showAlert('Failed to load Quick Send data', 'error');
    }
}

function populateQuickSendTemplates(templates) {
    const templateSelect = document.getElementById('quick-send-template');
    templateSelect.innerHTML = '<option value="">-- Select Template --</option>';
    
    if (templates && templates.length > 0) {
        templates.forEach(template => {
            const option = document.createElement('option');
            option.value = template.id;
            option.textContent = template.name;
            templateSelect.appendChild(option);
        });
    }
}

function populateQuickSendNumbers(categories) {
    const numbersSelect = document.getElementById('quick-send-numbers');
    numbersSelect.innerHTML = '<option value="">-- Select Category --</option>';
    
    if (categories && categories.length > 0) {
        categories.forEach(category => {
            const option = document.createElement('option');
            option.value = category.category;
            option.textContent = `${category.category} (${category.count} numbers)`;
            numbersSelect.appendChild(option);
        });
    }
}

function updateQuickSendPreview() {
    const templateId = document.getElementById('quick-send-template').value;
    const previewDiv = document.getElementById('quick-send-preview');
    
    if (!templateId) {
        previewDiv.innerHTML = '<p>Select a template to preview the message</p>';
        return;
    }
    
    // Find the selected template
    const template = templates.find(t => t.id === templateId);
    if (template) {
        previewDiv.innerHTML = `
            <h4>${template.name}</h4>
            <div class="message-content">${template.message}</div>
            ${template.attachment ? '<p><i class="fas fa-paperclip"></i> Includes attachment</p>' : ''}
        `;
    }
}

async function sendQuickMessages() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        const templateId = document.getElementById('quick-send-template').value;
        const category = document.getElementById('quick-send-numbers').value;
        
        if (!templateId || !category) {
            showAlert('Please select both a template and a phone number category', 'error');
            return;
        }

        // Get the template details
        const template = templates.find(t => t.id === templateId);
        if (!template) {
            showAlert('Selected template not found', 'error');
            return;
        }

        // Get the phone numbers for the selected category
        const numbersResponse = await fetch(`/api/get-phone-numbers?api_key=${apiKey}&category=${encodeURIComponent(category)}`);
        const numbersData = await numbersResponse.json();

        if (!numbersData.success || !numbersData.numbers || numbersData.numbers.length === 0) {
            showAlert('No phone numbers found in selected category', 'error');
            return;
        }

        // Create a CSV file in memory with the numbers
        const csvContent = "phone\n" + numbersData.numbers.join("\n");
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const file = new File([blob], `${category}.csv`, { type: 'text/csv' });

        // Prepare form data for bulk sending
        const formData = new FormData();
        formData.append('api_key', apiKey);
        formData.append('message', template.message);
        formData.append('contacts', file);

        // Add attachment if template has one
        if (template.attachment) {
            try {
                // Get the attachment data from the server
                const attachmentResponse = await fetch(`/api/template-attachment/${templateId}?api_key=${apiKey}`);
                
                if (attachmentResponse.ok) {
                    const attachmentBlob = await attachmentResponse.blob();
                    const attachmentFile = new File([attachmentBlob], 
                        template.attachment.originalname || 'attachment', {
                        type: template.attachment.mimetype || 'application/octet-stream'
                    });
                    formData.append('attachment', attachmentFile);
                }
            } catch (error) {
                console.error('Error loading template attachment:', error);
                showAlert('Message will be sent without attachment due to loading error', 'warning');
            }
        }

        // Show sending progress
        const sendButton = document.getElementById('quick-send-button');
        sendButton.disabled = true;
        sendButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';

        // Send request
        const response = await fetch('/api/send-bulk-messages', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.success) {
            showAlert(`Successfully sent ${data.sent} of ${data.total} messages`, 'success');
        } else {
            throw new Error(data.message || 'Failed to send messages');
        }
    } catch (error) {
        console.error('Error sending quick messages:', error);
        showAlert(`Failed to send messages: ${error.message}`, 'error');
    } finally {
        const sendButton = document.getElementById('quick-send-button');
        if (sendButton) {
            sendButton.disabled = false;
            sendButton.innerHTML = '<i class="fas fa-paper-plane"></i> Send Now';
        }
    }
}

// Add this to the DOMContentLoaded event listener
document.addEventListener('DOMContentLoaded', function() {
    // Phone numbers functionality
    document.querySelector('.sidebar-menu a[data-tab="phone-numbers"]')?.addEventListener('click', loadPhoneCategories);
    document.getElementById('save-phone-numbers')?.addEventListener('click', savePhoneNumbers);
    document.getElementById('phone-numbers-file')?.addEventListener('change', function() {
        updateFileNameDisplay('phone-numbers-file', 'phone-numbers-file-name');
    });
});

function updateFileNameDisplay(inputId, displayId) {
    const fileInput = document.getElementById(inputId);
    const fileNameDisplay = document.getElementById(displayId);
    
    if (fileInput.files.length > 0) {
        fileNameDisplay.querySelector('span').textContent = fileInput.files[0].name;
        fileNameDisplay.style.display = 'flex';
    } else {
        fileNameDisplay.style.display = 'none';
    }
}

async function loadPhoneCategories() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) return;

        const response = await fetch(`/api/get-phone-categories?api_key=${apiKey}`);
        const data = await response.json();

        if (data.success) {
            renderPhoneCategories(data.categories);
        }
    } catch (error) {
        console.error('Error loading phone categories:', error);
        showAlert('Failed to load phone categories', 'error');
    }
}

function renderPhoneCategories(categories) {
    const container = document.getElementById('phone-numbers-categories');
    container.innerHTML = '';

    if (!categories || categories.length === 0) {
        container.innerHTML = '<p class="no-data">No categories saved yet</p>';
        return;
    }

    const table = document.createElement('table');
    table.className = 'categories-table';
    table.innerHTML = `
        <thead>
            <tr>
                <th>Category</th>
                <th>Numbers</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody></tbody>
    `;

    const tbody = table.querySelector('tbody');
    
    categories.forEach(category => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${category.category}</td>
            <td>${category.count}</td>
            <td>${new Date(category.createdAt).toLocaleDateString()}</td>
            <td>
                <button class="button small use-category" data-category="${category.category}">
                    <i class="fas fa-paper-plane"></i> Use
                </button>
                <button class="button small danger delete-category" data-category="${category.category}">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });

    container.appendChild(table);

    // Add event listeners
    document.querySelectorAll('.use-category').forEach(btn => {
        btn.addEventListener('click', () => usePhoneCategory(btn.dataset.category));
    });

    document.querySelectorAll('.delete-category').forEach(btn => {
        btn.addEventListener('click', () => deletePhoneCategory(btn.dataset.category));
    });
}

async function savePhoneNumbers() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        const categoryName = document.getElementById('category-name').value.trim();
        const numbersFile = document.getElementById('phone-numbers-file').files[0];

        if (!categoryName || !numbersFile) {
            showAlert('Please enter a category name and select a file', 'error');
            return;
        }

        const formData = new FormData();
        formData.append('api_key', apiKey);
        formData.append('category_name', categoryName);
        formData.append('numbers', numbersFile);

        const response = await fetch('/api/save-phone-numbers', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.success) {
            showAlert(`Saved ${data.count} phone numbers in "${categoryName}"`, 'success');
            document.getElementById('category-name').value = '';
            document.getElementById('phone-numbers-file').value = '';
            document.getElementById('phone-numbers-file-name').style.display = 'none';
            loadPhoneCategories();
        } else {
            throw new Error(data.message || 'Failed to save phone numbers');
        }
    } catch (error) {
        console.error('Error saving phone numbers:', error);
        showAlert(`Failed to save phone numbers: ${error.message}`, 'error');
    }
}

async function usePhoneCategory(category) {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        // Switch to bulk messaging tab
        document.querySelectorAll('.sidebar-menu a').forEach(tab => tab.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
        
        document.querySelector('.sidebar-menu a[data-tab="bulk"]').classList.add('active');
        document.getElementById('bulk-tab').classList.add('active');

        // Get the numbers from this category
        const response = await fetch(`/api/get-phone-numbers?api_key=${apiKey}&category=${encodeURIComponent(category)}`);
        const data = await response.json();

        if (data.success) {
            // Create a CSV file in memory with the numbers
            const csvContent = "phone\n" + data.numbers.join("\n");
            const blob = new Blob([csvContent], { type: 'text/csv' });
            const file = new File([blob], `${category}.csv`, { type: 'text/csv' });

            // Create a fake file input event to set the file
            const fileInput = document.getElementById('contacts-file');
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(file);
            fileInput.files = dataTransfer.files;

            // Update the UI to show the file is selected
            updateFileNameDisplay('contacts-file', 'contacts-file-name');

            showAlert(`Loaded ${data.numbers.length} numbers from "${category}"`, 'success');
        } else {
            throw new Error(data.message || 'Failed to load phone numbers');
        }
    } catch (error) {
        console.error('Error using phone category:', error);
        showAlert(`Failed to use category: ${error.message}`, 'error');
    }
}

async function deletePhoneCategory(category) {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        if (!confirm(`Are you sure you want to delete the "${category}" category?`)) {
            return;
        }

        const response = await fetch(`/api/delete-phone-category?api_key=${apiKey}&category=${encodeURIComponent(category)}`, {
            method: 'DELETE'
        });

        const data = await response.json();

        if (data.success) {
            showAlert(`Deleted "${category}" category`, 'success');
            loadPhoneCategories();
        } else {
            throw new Error(data.message || 'Failed to delete category');
        }
    } catch (error) {
        console.error('Error deleting phone category:', error);
        showAlert(`Failed to delete category: ${error.message}`, 'error');
    }
}

// Add these functions to ui.js
async function loadAIStatus() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) return;

        const response = await fetch(`/api/get-openai-config?api_key=${apiKey}`);
        const data = await response.json();

        if (data.success) {
            const isEnabled = data.config?.enabled !== false; // Default to true if not set
            document.getElementById('ai-enabled').checked = isEnabled;
            document.getElementById('ai-status-text').textContent = 
                isEnabled ? 'AI Chatbot is Active' : 'AI Chatbot is Inactive';
        }
    } catch (error) {
        console.error('Error loading AI status:', error);
        document.getElementById('ai-status-text').textContent = 'Error loading status';
    }
}

async function toggleAIStatus() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        const checkbox = document.getElementById('ai-enabled');
        const isEnabled = checkbox.checked;

        const response = await fetch('/api/toggle-ai', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                api_key: apiKey,
                enabled: isEnabled
            })
        });

        const data = await response.json();

        if (data.success) {
            document.getElementById('ai-status-text').textContent = 
                isEnabled ? 'AI Chatbot is Active' : 'AI Chatbot is Inactive';
            showAlert(`AI Chatbot ${isEnabled ? 'enabled' : 'disabled'} successfully!`, 'success');
        } else {
            // Revert checkbox if failed
            checkbox.checked = !isEnabled;
            throw new Error(data.message || 'Failed to toggle AI status');
        }
    } catch (error) {
        console.error('Error toggling AI status:', error);
        showAlert(`Failed to toggle AI status: ${error.message}`, 'error');
    }
}

document.getElementById('reset-session').addEventListener('click', async function () {
    if (!confirm("Are you sure you want to reset your WhatsApp session?")) return;

    const apiKey = getApiKey();
    if (!apiKey) {
        alert("Missing API key");
        return;
    }

    try {
        const res = await fetch(`/api/reset-session?api_key=${apiKey}`, {
            method: 'DELETE'
        });

        const data = await res.json();

        if (data.success) {
            alert("✅ You have reset your WhatsApp session.");
            socket.emit('requestQR', apiKey);
        } else {
            alert("❌ Reset failed: " + (data.message || "Unknown error"));
        }
    } catch (err) {
        console.error("Reset session error:", err);
        alert("❌ Unexpected error resetting session");
    }
});



// Add this to your ui.js
document.addEventListener('DOMContentLoaded', function() {
    // AI Bot functionality
    const aiTab = document.querySelector('.sidebar-menu a[data-tab="ai-bot"]');
    if (aiTab) {
        aiTab.addEventListener('click', loadAIConfig);
    }

    document.getElementById('save-ai-config')?.addEventListener('click', saveAIConfig);
    document.getElementById('test-ai')?.addEventListener('click', toggleAITest);
    document.getElementById('send-test')?.addEventListener('click', sendTestMessage);
	// Add this event listener in the DOMContentLoaded section
document.getElementById('ai-enabled')?.addEventListener('change', toggleAIStatus);

// Call loadAIStatus when the AI tab is clicked
document.querySelector('.sidebar-menu a[data-tab="ai-bot"]')?.addEventListener('click', loadAIStatus);
});

async function loadAIConfig() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) return;

        const response = await fetch(`/api/get-openai-config?api_key=${apiKey}`);
        const data = await response.json();

        if (data.success && data.config) {
            document.getElementById('openai-key').value = data.config.openai_key || '';
            document.getElementById('ai-model').value = data.config.model || 'gpt-3.5-turbo';
            document.getElementById('ai-prompt').value = data.config.prompt || '';
        }
    } catch (error) {
        console.error('Error loading AI config:', error);
        showAlert('Failed to load AI configuration', 'error');
    }
}

async function saveAIConfig() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        const openaiKey = document.getElementById('openai-key').value.trim();
        const model = document.getElementById('ai-model').value;
        const prompt = document.getElementById('ai-prompt').value.trim();

        if (!openaiKey) {
            showAlert('OpenAI API key is required', 'error');
            return;
        }

        const response = await fetch('/api/save-openai-config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                api_key: apiKey,
                openai_key: openaiKey,
                model,
                prompt
            })
        });

        const data = await response.json();

        if (data.success) {
            showAlert('AI configuration saved successfully!', 'success');
        } else {
            throw new Error(data.message || 'Failed to save configuration');
        }
    } catch (error) {
        console.error('Error saving AI config:', error);
        showAlert(`Failed to save AI configuration: ${error.message}`, 'error');
    }
}

function toggleAITest() {
    const testContainer = document.getElementById('ai-test-container');
    if (testContainer.style.display === 'none') {
        testContainer.style.display = 'block';
    } else {
        testContainer.style.display = 'none';
    }
}

async function sendTestMessage() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        const testMessage = document.getElementById('test-message').value.trim();
        if (!testMessage) {
            showAlert('Please enter a test message', 'error');
            return;
        }

        const response = await fetch('/api/test-ai-message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                api_key: apiKey,
                message: testMessage
            })
        });

        const data = await response.json();

        if (data.success) {
            document.getElementById('ai-response').textContent = data.response;
        } else {
            throw new Error(data.message || 'Failed to get AI response');
        }
    } catch (error) {
        console.error('Error testing AI:', error);
        document.getElementById('ai-response').textContent = `Error: ${error.message}`;
    }
}
// Chatbot functionality
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const apiKey = urlParams.get('apiKey');
    let currentRules = [];
    let editingRuleIndex = -1;

    // Load rules from server
    async function loadChatbotRules() {
        if (!apiKey) return;
        
        try {
            const response = await fetch(`/api/get-chatbot-rules?api_key=${apiKey}`);
            const data = await response.json();
            
            if (data.success) {
                currentRules = data.rules || [];
                renderRulesList();
            }
        } catch (error) {
            console.error('Error loading chatbot rules:', error);
        }
    }

    // Render rules list
    function renderRulesList() {
        const rulesList = document.getElementById('rules-list');
        const noRules = document.getElementById('no-rules');
        
        if (currentRules.length === 0) {
            rulesList.style.display = 'none';
            noRules.style.display = 'block';
            return;
        }
        
        noRules.style.display = 'none';
        rulesList.style.display = 'block';
        rulesList.innerHTML = '';
        
        currentRules.forEach((rule, index) => {
            const ruleElement = document.createElement('div');
            ruleElement.className = 'rule-item';
            ruleElement.innerHTML = `
                <div class="rule-content">
                    <div class="rule-trigger"><strong>Trigger:</strong> ${rule.trigger}</div>
                    <div class="rule-response"><strong>Response:</strong> ${rule.response}</div>
                </div>
                <div class="rule-actions">
                    <button class="button small edit-rule" data-index="${index}">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="button small danger delete-rule" data-index="${index}">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            
            rulesList.appendChild(ruleElement);
        });
        
        // Add event listeners to edit/delete buttons
        document.querySelectorAll('.edit-rule').forEach(btn => {
            btn.addEventListener('click', (e) => {
                editingRuleIndex = parseInt(e.currentTarget.getAttribute('data-index'));
                showRuleForm(currentRules[editingRuleIndex]);
            });
        });
        
        document.querySelectorAll('.delete-rule').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.getAttribute('data-index'));
                currentRules.splice(index, 1);
                renderRulesList();
            });
        });
    }

    // Show rule form
    function showRuleForm(rule = null) {
        const form = document.getElementById('rule-form');
        const triggerInput = document.getElementById('rule-trigger');
        const responseInput = document.getElementById('rule-response');
        
        if (rule) {
            triggerInput.value = rule.trigger;
            responseInput.value = rule.response;
        } else {
            triggerInput.value = '';
            responseInput.value = '';
        }
        
        document.getElementById('chatbot-rules-container').style.display = 'none';
        form.style.display = 'block';
    }

    // Hide rule form
    function hideRuleForm() {
        document.getElementById('rule-form').style.display = 'none';
        document.getElementById('chatbot-rules-container').style.display = 'block';
        editingRuleIndex = -1;
    }

    // Save rule
    function saveRule() {
        const trigger = document.getElementById('rule-trigger').value.trim();
        const response = document.getElementById('rule-response').value.trim();
        
        if (!trigger || !response) {
            alert('Both trigger phrase and response are required');
            return;
        }
        
        const newRule = { trigger, response };
        
        if (editingRuleIndex >= 0) {
            currentRules[editingRuleIndex] = newRule;
        } else {
            currentRules.push(newRule);
        }
        
        hideRuleForm();
        renderRulesList();
    }

    // Save all rules to server
// In ui.js, modify the saveAllRules function:
async function saveAllRules() {
    if (!apiKey) return;
    
    try {
        const response = await fetch('/api/save-chatbot-rules', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                api_key: apiKey,
                rules: currentRules
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('Chatbot rules saved successfully!');
        } else {
            alert('Failed to save rules: ' + (data.message || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error saving rules:', error);
        alert('Failed to save rules. Please try again.');
    }
}

    // Event listeners
    document.getElementById('add-rule-btn').addEventListener('click', () => {
        editingRuleIndex = -1;
        showRuleForm();
    });
    
    document.getElementById('save-rule').addEventListener('click', saveRule);
    document.getElementById('cancel-rule').addEventListener('click', hideRuleForm);
    document.getElementById('save-all-rules').addEventListener('click', saveAllRules);

    // Initial load
    loadChatbotRules();
});

// Scheduled Messages Tab Functionality
document.addEventListener('DOMContentLoaded', function() {
    // Show/hide form
    const newScheduledBtn = document.getElementById('new-scheduled-btn');
    const scheduledForm = document.getElementById('scheduled-form');
    
    if (newScheduledBtn && scheduledForm) {
        newScheduledBtn.addEventListener('click', function() {
            scheduledForm.style.display = 'block';
            document.getElementById('scheduled-list').style.display = 'none';
        });
        
        document.getElementById('cancel-schedule').addEventListener('click', function() {
            scheduledForm.style.display = 'none';
            document.getElementById('scheduled-list').style.display = 'block';
        });
    }
    
    // File input handling for scheduled messages
    setupFileInput('scheduled-contacts', 'scheduled-contacts-name');
    setupFileInput('scheduled-attachment', 'scheduled-attachment-name');
    
    // Schedule messages
    const scheduleMessagesBtn = document.getElementById('schedule-messages');
    if (scheduleMessagesBtn) {
        scheduleMessagesBtn.addEventListener('click', scheduleMessages);
    }
    
    // Load scheduled messages
    loadScheduledMessages();
});

function setupFileInput(inputId, displayId) {
    const fileInput = document.getElementById(inputId);
    const fileNameDisplay = document.getElementById(displayId);
    
    if (fileInput && fileNameDisplay) {
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                fileNameDisplay.querySelector('span').textContent = this.files[0].name;
                fileNameDisplay.style.display = 'flex';
            } else {
                fileNameDisplay.style.display = 'none';
            }
        });
    }
}

async function scheduleMessages() {
    const contactsFile = document.getElementById('scheduled-contacts').files[0];
    const message = document.getElementById('scheduled-message').value;
    const attachment = document.getElementById('scheduled-attachment').files[0];
    const scheduledTime = document.getElementById('scheduled-time').value;
    
    if (!contactsFile || !message || !scheduledTime) {
        alert('Please fill all required fields');
        return;
    }
    
    const urlParams = new URLSearchParams(window.location.search);
    const apiKey = urlParams.get('apiKey');
    
    if (!apiKey) {
        alert('API key is missing');
        return;
    }
    
    const formData = new FormData();
    formData.append('api_key', apiKey);
    formData.append('message', message);
    formData.append('scheduled_time', scheduledTime);
    formData.append('contacts', contactsFile);
    
    if (attachment) {
        formData.append('attachment', attachment);
    }
    
    try {
        const response = await fetch('/api/schedule-bulk-messages', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('Messages scheduled successfully');
            document.getElementById('scheduled-form').style.display = 'none';
            document.getElementById('scheduled-list').style.display = 'block';
            loadScheduledMessages();
        } else {
            alert('Failed to schedule messages: ' + (data.message || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error scheduling messages:', error);
        alert('Failed to schedule messages. Please try again.');
    }
}

async function loadScheduledMessages() {
    const urlParams = new URLSearchParams(window.location.search);
    const apiKey = urlParams.get('apiKey');
    
    if (!apiKey) {
        return;
    }
    
    const loader = document.getElementById('scheduled-loader');
    const noData = document.getElementById('no-scheduled');
    const table = document.getElementById('scheduled-table');
    
    loader.style.display = 'block';
    noData.style.display = 'none';
    table.style.display = 'none';
    
    try {
        const response = await fetch(`/api/get-scheduled-messages?api_key=${apiKey}`);
        const data = await response.json();
        
        loader.style.display = 'none';
        
        if (data.success && data.messages.length > 0) {
            const tbody = document.getElementById('scheduled-messages');
            tbody.innerHTML = '';
            
            data.messages.forEach(msg => {
                const row = document.createElement('tr');
                
                // Shorten message for display
                const shortMessage = msg.message.length > 50 
                    ? msg.message.substring(0, 50) + '...' 
                    : msg.message;
                
                // Format dates
                const scheduledDate = new Date(msg.scheduled_time).toLocaleString();
                const createdDate = new Date(msg.created_at).toLocaleString();
                
                // Status badge
                let statusClass = '';
                switch(msg.status) {
                    case 'pending': statusClass = 'status-pending'; break;
                    case 'processing': statusClass = 'status-processing'; break;
                    case 'completed': statusClass = 'status-completed'; break;
                    case 'failed': statusClass = 'status-failed'; break;
                }
                
                row.innerHTML = `
                    <td title="${msg.message}">${shortMessage}</td>
                    <td>${scheduledDate}</td>
                    <td><span class="status-badge ${statusClass}">${msg.status}</span></td>
                    <td>${createdDate}</td>
                    <td>
                        ${msg.status === 'pending' ? 
                            `<button class="button small cancel-btn" data-id="${msg.id}">
                                <i class="fas fa-times"></i> Cancel
                            </button>` : 
                            ''}
                    </td>
                `;
                
                tbody.appendChild(row);
            });
            
            // Add event listeners to cancel buttons
            document.querySelectorAll('.cancel-btn').forEach(btn => {
                btn.addEventListener('click', cancelScheduledMessage);
            });
            
            table.style.display = 'table';
        } else {
            noData.style.display = 'flex';
        }
    } catch (error) {
        console.error('Error loading scheduled messages:', error);
        loader.style.display = 'none';
        noData.style.display = 'flex';
    }
}

async function cancelScheduledMessage(event) {
    const messageId = event.currentTarget.getAttribute('data-id');
    const urlParams = new URLSearchParams(window.location.search);
    const apiKey = urlParams.get('apiKey');
    
    if (!confirm('Are you sure you want to cancel this scheduled message?')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/cancel-scheduled-message/${messageId}?api_key=${apiKey}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('Scheduled message canceled successfully');
            loadScheduledMessages();
        } else {
            alert('Failed to cancel scheduled message: ' + (data.message || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error canceling scheduled message:', error);
        alert('Failed to cancel scheduled message. Please try again.');
    }
}

// Template management functionality
document.addEventListener('DOMContentLoaded', function() {
    const createTemplateBtn = document.getElementById('create-template-btn');
    const templateForm = document.getElementById('template-form');
    const templatesList = document.getElementById('templates-list');
    const saveTemplateBtn = document.getElementById('save-template');
    const cancelTemplateBtn = document.getElementById('cancel-template');
    
    if (createTemplateBtn) {
        createTemplateBtn.addEventListener('click', showTemplateForm);
    }
    
    if (saveTemplateBtn) {
        saveTemplateBtn.addEventListener('click', saveTemplate);
    }
    
    if (cancelTemplateBtn) {
        cancelTemplateBtn.addEventListener('click', hideTemplateForm);
    }
    
    // Load templates when tab is clicked
    document.querySelectorAll('.sidebar-menu a').forEach(tab => {
        tab.addEventListener('click', function() {
            if (this.dataset.tab === 'templates') {
                loadTemplates();
            }
        });
    });
});

let templates = [];
let currentTemplateAttachment = null; // Store the current template attachment

function showTemplateForm() {
    document.getElementById('template-form').style.display = 'block';
    document.getElementById('templates-grid').style.display = 'none';
    document.getElementById('no-templates').style.display = 'none';
}

function hideTemplateForm() {
    document.getElementById('template-form').style.display = 'none';
    document.getElementById('template-name').value = '';
    document.getElementById('template-message').value = '';
    document.getElementById('template-attachment').value = '';
    document.getElementById('template-attachment-name').style.display = 'none';
    loadTemplates();
}

async function loadTemplates() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) return;
        
        document.getElementById('templates-loader').style.display = 'block';
        document.getElementById('templates-grid').style.display = 'none';
        document.getElementById('no-templates').style.display = 'none';
        
        const response = await fetch(`/api/get-templates?api_key=${apiKey}`);
        const data = await response.json();
        
        document.getElementById('templates-loader').style.display = 'none';
        
        if (data.success && data.templates.length > 0) {
            templates = data.templates;
            renderTemplates(data.templates);
            document.getElementById('templates-grid').style.display = 'grid';
        } else {
            document.getElementById('no-templates').style.display = 'block';
        }
    } catch (error) {
        console.error('Error loading templates:', error);
        document.getElementById('templates-loader').style.display = 'none';
        showAlert('Failed to load templates', 'error');
    }
}

function renderTemplates(templates) {
    const grid = document.getElementById('templates-grid');
    grid.innerHTML = '';
    
    templates.forEach(template => {
        const templateCard = document.createElement('div');
        templateCard.className = 'template-card';
        
        const hasAttachment = template.attachment ? '<i class="fas fa-paperclip"></i>' : '';
        
        templateCard.innerHTML = `
            <div class="template-header">
                <h3>${template.name}</h3>
                <div class="template-actions">
                    <button class="template-use-btn" data-id="${template.id}">
                        <i class="fas fa-paper-plane"></i> Use
                    </button>
                    <button class="template-delete-btn" data-id="${template.id}">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
            <div class="template-content">
                <p>${template.message.substring(0, 100)}${template.message.length > 100 ? '...' : ''}</p>
                ${hasAttachment}
            </div>
            <div class="template-footer">
                <small>Created: ${new Date(template.createdAt).toLocaleDateString()}</small>
            </div>
        `;
        
        grid.appendChild(templateCard);
    });
    
    // Add event listeners for template actions
    document.querySelectorAll('.template-use-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            useTemplate(this.dataset.id);
        });
    });
    
    document.querySelectorAll('.template-delete-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            deleteTemplate(this.dataset.id);
        });
    });
}

async function useTemplate(templateId) {
    const template = templates.find(t => t.id === templateId);
    if (!template) return;
    
    // Switch to bulk messaging tab
    document.querySelectorAll('.sidebar-menu a').forEach(tab => tab.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
    
    document.querySelector('.sidebar-menu a[data-tab="bulk"]').classList.add('active');
    document.getElementById('bulk-tab').classList.add('active');
    
    // Fill in the bulk messaging form
    document.getElementById('message-text').value = template.message;
    
    // Clear any existing attachment first
    currentTemplateAttachment = null;
    document.getElementById('attachment').value = '';
    removeAttachment();
    
    // Handle attachment if template has one
    if (template.attachment) {
        try {
            // Get the attachment data from the server
            const apiKey = getApiKey();
            const response = await fetch(`/api/template-attachment/${templateId}?api_key=${apiKey}`);
            
            if (response.ok) {
                const blob = await response.blob();
                
                // Create a new File object from the blob with proper type information
                const file = new File([blob], template.attachment.originalname || 'attachment', {
                    type: template.attachment.mimetype || 'application/octet-stream'
                });
                
                // Store the file globally so bulk messaging can access it
                currentTemplateAttachment = file; // Store the File object directly
                
                // Show attachment preview
                showAttachmentPreview(file);
                showAlert('Template loaded with attachment successfully!', 'success');
            } else {
                showAlert('Template loaded, but attachment could not be retrieved. Please upload the attachment again.', 'warning');
            }
        } catch (error) {
            console.error('Error loading template attachment:', error);
            showAlert('Template loaded, but there was an error with the attachment. Please upload it again.', 'warning');
        }
    } else {
        showAlert('Template loaded successfully!', 'success');
    }
}
async function deleteTemplate(templateId) {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        // Confirm deletion
        const confirmed = confirm('Are you sure you want to delete this template?');
        if (!confirmed) return;

        const response = await fetch(`/api/delete-template/${templateId}?api_key=${apiKey}`, {
            method: 'DELETE'
        });

        const data = await response.json();

        if (data.success) {
            showAlert('Template deleted successfully', 'success');
            loadTemplates(); // Refresh the templates list
        } else {
            throw new Error(data.message || 'Failed to delete template');
        }
    } catch (error) {
        console.error('Error deleting template:', error);
        showAlert(`Failed to delete template: ${error.message}`, 'error');
    }
}
// Add attachment preview functionality
function showAttachmentPreview(file) {
    let previewContainer = document.getElementById('attachment-preview');
    if (!previewContainer) {
        // Create preview container if it doesn't exist
        const container = document.createElement('div');
        container.id = 'attachment-preview';
        container.className = 'attachment-preview';
        container.innerHTML = `
            <div class="attachment-info">
                <i class="fas fa-paperclip"></i>
                <span class="attachment-name"></span>
                <button type="button" class="remove-attachment" onclick="removeAttachment()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `;
        
        // Insert after the attachment input
        const attachmentInput = document.getElementById('attachment');
        attachmentInput.parentNode.insertBefore(container, attachmentInput.nextSibling);
        previewContainer = container;
    }
    
    const attachmentName = previewContainer.querySelector('.attachment-name');
    attachmentName.textContent = file.name;
    previewContainer.style.display = 'block';
}

// Add remove attachment functionality
function removeAttachment() {
    document.getElementById('attachment').value = '';
    currentTemplateAttachment = null; // Clear the stored template attachment
    const previewContainer = document.getElementById('attachment-preview');
    if (previewContainer) {
        previewContainer.style.display = 'none';
    }
}

async function saveTemplate() {
    try {
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }
        
        const name = document.getElementById('template-name').value.trim();
        const message = document.getElementById('template-message').value.trim();
        const attachment = document.getElementById('template-attachment').files[0];
        
        if (!name) {
            showAlert('Please enter a template name', 'error');
            return;
        }
        
        if (!message) {
            showAlert('Please enter a message', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('api_key', apiKey);
        formData.append('template_name', name);
        formData.append('message_text', message);
        
        if (attachment) {
            formData.append('attachment', attachment);
        }
        
        document.getElementById('save-template').disabled = true;
        
        const response = await fetch('/api/save-template', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('Template saved successfully', 'success');
            hideTemplateForm();
        } else {
            throw new Error(data.message || 'Failed to save template');
        }
    } catch (error) {
        console.error('Error saving template:', error);
        showAlert(`Failed to save template: ${error.message}`, 'error');
    } finally {
        document.getElementById('save-template').disabled = false;
    }
}

// Helper function to get API key from URL parameters
function getApiKey() {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get('apiKey');
} 

// Alert functions
function showAlert(message, type = 'success') {
    // Remove any existing alerts first
    hideAlert();
    
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type}`;
    alertDiv.innerHTML = `
        <span>${message}</span>
        <button class="alert-close">&times;</button>
    `;
    
    // Add to the top of the main content
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.insertBefore(alertDiv, mainContent.firstChild);
    } else {
        document.body.prepend(alertDiv);
    }
    
    // Add click handler for close button
    alertDiv.querySelector('.alert-close').addEventListener('click', hideAlert);
    
    // Auto-hide after 5 seconds
    setTimeout(hideAlert, 50000);
}

function hideAlert() {
    const existingAlert = document.querySelector('.alert');
    if (existingAlert) {
        existingAlert.remove();
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // Get URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const apiKey = urlParams.get('apiKey');
    const serverUrl = urlParams.get('serverUrl');
    
    let socket;
    let connected = false;
    let messagesChart = null;
    
    // Tab functionality
    const tabs = document.querySelectorAll('.sidebar-menu a');
    tabs.forEach(tab => {
        tab.addEventListener('click', (e) => {
            e.preventDefault();
            
            // Remove active class from all tabs and tab contents
            document.querySelectorAll('.sidebar-menu a').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
            
            // Add active class to clicked tab and corresponding content
            tab.classList.add('active');
            document.getElementById(`${tab.dataset.tab}-tab`).classList.add('active');
            
            // Load statistics if statistics tab is clicked
            if (tab.dataset.tab === 'statistics') {
                loadUserStatistics();
            }
        });
    });
    
    // Update the UI with the parameters
    if (apiKey) {
        document.getElementById('apiKey').textContent = apiKey;
    } else {
        document.getElementById('apiKey').textContent = 'Not available';
    }
    
    if (serverUrl) {
        document.getElementById('serverUrl').textContent = serverUrl;
    } else {
        document.getElementById('serverUrl').textContent = 'Not available';
    }
    
    // Check WhatsApp connection status
    function checkConnectionStatus() {
        fetch(`/api/connection-status?api_key=${apiKey}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateConnectionStatus(data.connected);
            }
        })
        .catch(error => {
            console.error('Error checking connection status:', error);
            updateConnectionStatus(false);
        });
    }
    
    function updateConnectionStatus(isConnected) {
        const statusElement = document.getElementById('whatsapp-status');
        connected = isConnected;
        
        if (isConnected) {
            statusElement.className = 'whatsapp-status connected';
            statusElement.innerHTML = '<i class="fas fa-circle-check"></i> WhatsApp Connected Successfully';
            document.getElementById('qr-container').style.display = 'none';
            document.getElementById('connect-whatsapp').innerHTML = '<i class="fas fa-sync"></i> Reconnect WhatsApp';
        } else {
            statusElement.className = 'whatsapp-status disconnected';
            statusElement.innerHTML = '<i class="fas fa-circle-exclamation"></i> WhatsApp Not Connected';
            document.getElementById('connect-whatsapp').innerHTML = '<i class="fab fa-whatsapp"></i> Connect WhatsApp';
        }
    }
    
    // Initialize socket connection
    function initSocketConnection() {
        socket = io();
        
        socket.on('connect', () => {
            console.log('Socket connected');
            // Check current status when socket connects
            socket.emit('checkStatus', apiKey);
        });
        
        // Fixed QR code handler
        socket.on('qr', (data) => {
            console.log('Received QR code data:', data);
            // Make sure we have the data attribute we need
            if (data && data.qrcode) {
                document.getElementById('loading').style.display = 'none';
                const qrImg = document.getElementById('qrcode');
                qrImg.src = data.qrcode;
                qrImg.style.display = 'block';
                document.getElementById('qr-container').style.display = 'block';
            } else {
                console.error('Received invalid QR code data:', data);
                showAlert('Error loading QR code', 'error');
                document.getElementById('loading').style.display = 'none';
            }
        });
        
        socket.on('connected', () => {
            updateConnectionStatus(true);
            document.getElementById('qr-container').style.display = 'none';
        });
        
        socket.on('disconnected', () => {
            updateConnectionStatus(false);
        });
        
        socket.on('sessionReady', () => {
            updateConnectionStatus(true);
            document.getElementById('qr-container').style.display = 'none';
        });
        
        socket.on('statusUpdate', (data) => {
            updateConnectionStatus(data.connected);
        });
        
        // Listen for specific status updates for this API key
        socket.on(`status-${apiKey}`, (data) => {
            updateConnectionStatus(data.connected);
        });
        
        socket.on('error', (data) => {
            if (typeof data === 'object' && data.message) {
                showAlert(`Error: ${data.message}`, 'error');
            } else {
                showAlert('An error occurred', 'error');
            }
            document.getElementById('loading').style.display = 'none';
        });
    }
    
    // Load user statistics
    function loadUserStatistics() {
        document.getElementById('chart-loader').style.display = 'block';
        document.getElementById('messages-loader').style.display = 'block';
        document.getElementById('recent-messages-table').style.display = 'none';
        document.getElementById('no-messages').style.display = 'none';
        
        fetch(`/api/user-statistics?api_key=${apiKey}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updateStatistics(data.statistics);
            } else {
                showAlert('Failed to load statistics: ' + data.message, 'error');
            }
            document.getElementById('chart-loader').style.display = 'none';
            document.getElementById('messages-loader').style.display = 'none';
        })
        .catch(error => {
            console.error('Error loading statistics:', error);
            document.getElementById('chart-loader').style.display = 'none';
            document.getElementById('messages-loader').style.display = 'none';
            showAlert('Failed to load statistics. Please try again later.', 'error');
        });
    }
    
    function updateStatistics(statistics) {
        // Update counter cards
        document.getElementById('total-messages').textContent = statistics.totalMessages;
        
        // Find order confirmations and abandoned carts
        let orderConfirmations = 0;
        let abandonedCarts = 0;
        
        statistics.messagesByType.forEach(type => {
            if (type.type === 'order_confirmation') {
                orderConfirmations = type.count;
            } else if (type.type === 'abandoned_cart') {
                abandonedCarts = type.count;
            }
        });
        
        document.getElementById('order-confirmations').textContent = orderConfirmations;
        document.getElementById('abandoned-carts').textContent = abandonedCarts;
        
        // Update recent messages table
        const recentMessages = statistics.recentMessages;
        const tableBody = document.getElementById('recent-messages');
        tableBody.innerHTML = '';
        
        if (recentMessages && recentMessages.length > 0) {
            document.getElementById('recent-messages-table').style.display = 'table';
            document.getElementById('no-messages').style.display = 'none';
            
            recentMessages.forEach(msg => {
                const row = document.createElement('tr');
                
                // Format phone number for privacy
                const phoneNumber = msg.phone_number;
                const formattedPhone = phoneNumber.length > 4 ? 
                    '***' + phoneNumber.substring(phoneNumber.length - 4) : 
                    phoneNumber;
                
                // Format message type for display
                const messageType = msg.type === 'order_confirmation' ? 
                    'Order Confirmation' : 
                    msg.type === 'abandoned_cart' ? 
                    'Abandoned Cart' : 
                    msg.type;
                
                // Format date
                const date = new Date(msg.created_at);
                const formattedDate = date.toLocaleString();
                
                // Generate status badge
                let statusBadge = '';
                if (msg.status === 'delivered') {
                    statusBadge = '<span class="status-badge delivered">Delivered</span>';
                } else if (msg.status === 'pending') {
                    statusBadge = '<span class="status-badge pending">Pending</span>';
                } else if (msg.status === 'failed') {
                    statusBadge = '<span class="status-badge failed">Failed</span>';
                }

                // Create table row
                row.innerHTML = `
                    <td>${formattedPhone}</td>
                    <td>${messageType}</td>
                    <td>${statusBadge}</td>
                    <td>${formattedDate}</td>
                `;
                tableBody.appendChild(row);
            });
        } else {
            document.getElementById('recent-messages-table').style.display = 'none';
            document.getElementById('no-messages').style.display = 'block';
        }
        
        // Update chart with message activity
        updateMessageChart(statistics.messagesByDate);
    }
    
    function updateMessageChart(messagesByDate) {
        const ctx = document.getElementById('messages-chart').getContext('2d');
        
        // Destroy existing chart if it exists
        if (messagesChart !== null) {
            messagesChart.destroy();
        }
        
        // Prepare data for chart
        const dates = [];
        const counts = [];
        
        // Check if messagesByDate exists and is an array before using forEach
        if (messagesByDate && Array.isArray(messagesByDate)) {
            messagesByDate.forEach(item => {
                dates.push(new Date(item.date).toLocaleDateString());
                counts.push(item.count);
            });
        } else {
            // Add default empty data if no data is available
            const today = new Date();
            for (let i = 6; i >= 0; i--) {
                const date = new Date(today);
                date.setDate(today.getDate() - i);
                dates.push(date.toLocaleDateString());
                counts.push(0);
            }
        }
        
        // Create new chart
        messagesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: dates,
                datasets: [{
                    label: 'Messages Sent',
                    data: counts,
                    backgroundColor: 'rgba(37, 211, 102, 0.2)',
                    borderColor: '#25D366',
                    borderWidth: 2,
                    pointBackgroundColor: '#25D366',
                    pointBorderColor: '#ffffff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.7)',
                        padding: 10,
                        cornerRadius: 6,
                        displayColors: false
                    }
                },
                scales: {
                    x: {
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0
                        }
                    }
                }
            }
        });
    }
    
    // Connect WhatsApp button click handler
    document.getElementById('connect-whatsapp').addEventListener('click', function() {
        document.getElementById('loading').style.display = 'block';
        document.getElementById('qrcode').style.display = 'none';
        document.getElementById('qr-container').style.display = 'block';
        
        // First request a new QR code via socket
        if (socket && socket.connected) {
            console.log('Requesting QR code for API key:', apiKey);
            socket.emit('requestQR', apiKey);
        } else {
            console.error('Socket not connected');
            showAlert('Connection error. Please refresh the page and try again.', 'error');
            document.getElementById('loading').style.display = 'none';
        }

        // Then make the API call
        fetch(`/api/connect-whatsapp?api_key=${apiKey}`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                showAlert(`Failed to initiate connection: ${data.message}`, 'error');
                document.getElementById('loading').style.display = 'none';
            }
        })
        .catch(error => {
            console.error('Error initiating connection:', error);
            showAlert('Failed to initiate connection. Please try again later.', 'error');
            document.getElementById('loading').style.display = 'none';
        });
    });

    
    // Initialize connection
    checkConnectionStatus();
    initSocketConnection();
    
    // Auto-load statistics if statistics tab is active
    if (document.querySelector('.sidebar-menu a.active').dataset.tab === 'statistics') {
        loadUserStatistics();
    }
});

// Bulk messaging functionality
document.addEventListener('DOMContentLoaded', function() {
    const sendBulkBtn = document.getElementById('send-bulk-messages');
    if (sendBulkBtn) {
        sendBulkBtn.addEventListener('click', sendBulkMessages);
    }
    
    const downloadResultsBtn = document.getElementById('download-results');
    if (downloadResultsBtn) {
        downloadResultsBtn.addEventListener('click', downloadResults);
    }
    
    // Add event listener for regular attachment input to clear template attachment
    const attachmentInput = document.getElementById('attachment');
    if (attachmentInput) {
        attachmentInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                // User selected a new file, clear the template attachment
                currentTemplateAttachment = null;
            }
        });
    }
});

let bulkResults = [];

async function sendBulkMessages() {
    try {
        // Get required elements
        const contactsFileInput = document.getElementById('contacts-file');
        const messageText = document.getElementById('message-text').value;
        const attachmentInput = document.getElementById('attachment');
        const progressBar = document.getElementById('bulk-progress');
        const resultsContainer = document.getElementById('bulk-results');
        const sendButton = document.getElementById('send-bulk-messages');
        
        // Get API key
        const apiKey = getApiKey();
        if (!apiKey) {
            showAlert('API key is missing. Please reload the page.', 'error');
            return;
        }

        // Validate inputs
        if (!contactsFileInput.files || contactsFileInput.files.length === 0) {
            showAlert('Please select a contacts file', 'error');
            return;
        }
        
        if (!messageText.trim()) {
            showAlert('Please enter a message', 'error');
            return;
        }

        // Check file types
        const contactsFile = contactsFileInput.files[0];
        const validContactTypes = ['text/csv', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
        if (!validContactTypes.includes(contactsFile.type)) {
            showAlert('Invalid contacts file type. Please upload CSV or Excel file.', 'error');
            return;
        }

        // Determine which attachment to use - prioritize file input over template attachment
       let attachment = null;
        if (attachmentInput.files && attachmentInput.files.length > 0) {
            // User uploaded a new file
            attachment = attachmentInput.files[0];
        } else if (currentTemplateAttachment) {
            // Use template attachment if no new file was uploaded
            attachment = currentTemplateAttachment;
        }

        // Check attachment if provided
        if (attachment) {
            const validAttachmentTypes = [
                'image/jpeg',
                'image/jpg',
                'image/png',
                'image/webp',
                'video/mp4',
                'application/pdf',
                'image/gif'
            ];
            
            // Get the type from the File object
            const attachmentType = attachment.type.toLowerCase();
            
            if (!validAttachmentTypes.includes(attachmentType)) {
                showAlert('Invalid attachment type. Supported types: JPG, PNG, WebP, MP4, PDF, GIF', 'error');
                return;
            }

            if (attachment.size > 15 * 1024 * 1024) { // 15MB limit
                showAlert('Attachment too large. Maximum size is 15MB.', 'error');
                return;
            }
        }

        // Prepare UI for sending
        progressBar.style.display = 'block';
        resultsContainer.style.display = 'none';
        sendButton.disabled = true;
        updateProgress(0, 1); // Initialize progress

        // Prepare form data
        const formData = new FormData();
        formData.append('api_key', apiKey);
        formData.append('message', messageText);
        formData.append('contacts', contactsFile);
        
        if (attachment) {
            formData.append('attachment', attachment);
            console.log('Sending attachment:', attachment.name, 'Type:', attachment.type, 'Size:', attachment.size);
        }

        // Send request
        const response = await fetch('/api/send-bulk-messages', {
            method: 'POST',
            body: formData
        });

        // Handle response
        if (!response.ok) {
            throw new Error(`Server returned ${response.status}: ${response.statusText}`);
        }

        const data = await response.json();
        
        if (data.success) {
            bulkResults = data.results;
            showBulkResults(data);
            showAlert(`Successfully sent ${data.sent} of ${data.total} messages`, 'success');
        } else {
            throw new Error(data.message || 'Failed to send bulk messages');
        }
    } catch (error) {
        console.error('Error sending bulk messages:', error);
        showAlert(`Failed to send bulk messages: ${error.message}`, 'error');
        
        // Log error to server for debugging
        try {
            await fetch('/api/log-error', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    error: error.message,
                    stack: error.stack,
                    timestamp: new Date().toISOString()
                })
            });
        } catch (logError) {
            console.error('Failed to log error:', logError);
        }
    } finally {
        // Reset UI
        document.getElementById('send-bulk-messages').disabled = false;
        document.getElementById('bulk-progress').style.display = 'none';
    }
}

// Helper function to update progress
function updateProgress(current, total) {
    const percent = Math.round((current / total) * 100);
    const progressText = document.getElementById('progress-text');
    const progressFill = document.getElementById('progress-bar-fill');
    
    if (progressText && progressFill) {
        progressText.textContent = `${percent}% (${current}/${total})`;
        progressFill.style.width = `${percent}%`;
    }
}



function showBulkResults(data) {
    document.getElementById('bulk-results').style.display = 'block';
    document.getElementById('total-contacts').textContent = data.total;
    document.getElementById('sent-contacts').textContent = data.sent;
    document.getElementById('failed-contacts').textContent = data.failed;
    
    const resultsBody = document.getElementById('results-table-body');
    resultsBody.innerHTML = '';
    
    bulkResults.forEach(result => {
        const row = document.createElement('tr');
        
        const phoneCell = document.createElement('td');
        phoneCell.textContent = result.phone;
        row.appendChild(phoneCell);
        
        const statusCell = document.createElement('td');
        const statusSpan = document.createElement('span');
        statusSpan.className = result.success ? 'status-success' : 'status-error';
        statusSpan.textContent = result.success ? 'Success' : 'Failed';
        statusCell.appendChild(statusSpan);
        row.appendChild(statusCell);
        
        const detailsCell = document.createElement('td');
        detailsCell.textContent = result.error || 'Message sent successfully';
        row.appendChild(detailsCell);
        
        resultsBody.appendChild(row);
    });
}

function downloadResults() {
    if (bulkResults.length === 0) return;
    
    let csvContent = "Phone Number,Status,Details\n";
    
    bulkResults.forEach(result => {
        const row = [
            result.phone,
            result.success ? 'Success' : 'Failed',
            result.error || 'Message sent successfully'
        ].map(field => `"${field.replace(/"/g, '""')}"`).join(',');
        csvContent += row + "\n";
    });
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', 'bulk_message_results.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

