// WhatsApp Module JavaScript Functions

// Initialize WhatsApp settings
$(document).ready(function() {
    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();
    
    // Initialize character counter for message textarea
    $('.message-textarea').on('input', function() {
        updateCharacterCount($(this));
    });
});

// Update character count for textareas
function updateCharacterCount(element) {
    var count = element.val().length;
    var maxLength = element.attr('maxlength') || 1000;
    var counterId = element.attr('id') + '_count';
    
    $('#' + counterId).text(count + '/' + maxLength);
    
    // Change color based on length
    if(count > maxLength * 0.9) {
        $('#' + counterId).addClass('text-danger').removeClass('text-warning text-success');
    } else if(count > maxLength * 0.7) {
        $('#' + counterId).addClass('text-warning').removeClass('text-danger text-success');
    } else {
        $('#' + counterId).addClass('text-success').removeClass('text-danger text-warning');
    }
}

// Format phone number input
function formatPhoneNumber(input) {
    var value = input.value.replace(/\D/g, '');
    
    // Add country code if not present (assuming India +91)
    if(value.length === 10) {
        value = '91' + value;
    }
    
    input.value = value;
}

// Validate phone number
function validatePhoneNumber(phone) {
    // Remove all non-numeric characters
    var cleaned = phone.replace(/\D/g, '');
    
    // Check if it's a valid length (10-15 digits)
    if(cleaned.length < 10 || cleaned.length > 15) {
        return false;
    }
    
    return true;
}

// Show loading state
function showLoading(element, text = 'Loading...') {
    element.html('<i class="fa fa-spinner fa-spin"></i> ' + text);
    element.prop('disabled', true);
}

// Hide loading state
function hideLoading(element, originalText) {
    element.html(originalText);
    element.prop('disabled', false);
}

// Send quick message function
function sendQuickMessage(phone, message, type = 'manual') {
    var base_url = $("#base_url").val();
    
    if(!validatePhoneNumber(phone)) {
        toastr["error"]("Invalid phone number format!");
        return;
    }
    
    $.ajax({
        type: 'POST',
        url: base_url + 'whatsapp/send_message',
        data: {
            phone_number: phone,
            message: message,
            message_type: type
        },
        dataType: 'json',
        success: function(result) {
            if(result.status == "success") {
                toastr["success"]("Message sent successfully!");
            } else {
                toastr["error"](result.message || "Failed to send message!");
            }
        },
        error: function() {
            toastr["error"]("An error occurred while sending message!");
        }
    });
}

// Preview template with variables
function previewTemplate(templateContent, variables = {}) {
    var preview = templateContent;
    
    // Default variables
    var defaultVars = {
        'BUSINESS_NAME': 'Your Business',
        'CUSTOMER_NAME': 'Customer Name',
        'INVOICE_NO': 'INV001',
        'TOTAL_AMOUNT': '1000.00',
        'INVOICE_DATE': new Date().toLocaleDateString(),
        'DUE_DATE': new Date().toLocaleDateString()
    };
    
    // Merge with provided variables
    var allVars = Object.assign(defaultVars, variables);
    
    // Replace variables
    for(var key in allVars) {
        var regex = new RegExp('{' + key + '}', 'g');
        preview = preview.replace(regex, allVars[key]);
    }
    
    return preview;
}

// Copy to clipboard function
function copyToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    
    toastr["success"]("Copied to clipboard!");
}

// Format message for WhatsApp (add line breaks, etc.)
function formatMessageForWhatsApp(message) {
    // Replace \n with actual line breaks
    return message.replace(/\\n/g, '\n');
}

// Bulk operations helper
function processBulkOperation(operation, items, callback) {
    var completed = 0;
    var total = items.length;
    var results = [];
    
    function processNext() {
        if(completed >= total) {
            callback(results);
            return;
        }
        
        var item = items[completed];
        operation(item, function(result) {
            results.push(result);
            completed++;
            
            // Update progress if there's a progress bar
            var progress = Math.round((completed / total) * 100);
            $('.bulk-progress-bar').css('width', progress + '%');
            $('.bulk-progress-text').text(completed + ' of ' + total + ' completed');
            
            // Process next item after a small delay
            setTimeout(processNext, 100);
        });
    }
    
    processNext();
}

// Template variable insertion helper
function insertTemplateVariable(textareaId, variable) {
    var textarea = document.getElementById(textareaId);
    var cursorPos = textarea.selectionStart;
    var textBefore = textarea.value.substring(0, cursorPos);
    var textAfter = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
    
    textarea.value = textBefore + '{' + variable + '}' + textAfter;
    textarea.focus();
    textarea.setSelectionRange(cursorPos + variable.length + 2, cursorPos + variable.length + 2);
    
    // Trigger input event to update character count
    $(textarea).trigger('input');
}

// Export message logs to CSV
function exportMessageLogs() {
    var base_url = $("#base_url").val();
    window.open(base_url + 'whatsapp/export_logs?format=csv', '_blank');
}

// Real-time message status checker
function checkMessageStatus(messageId) {
    var base_url = $("#base_url").val();
    
    $.ajax({
        type: 'GET',
        url: base_url + 'whatsapp/check_status/' + messageId,
        dataType: 'json',
        success: function(result) {
            if(result.status) {
                // Update status in the UI
                $('#message_' + messageId + '_status').html(
                    '<span class="label ' + getStatusClass(result.status) + '">' + 
                    result.status.charAt(0).toUpperCase() + result.status.slice(1) + 
                    '</span>'
                );
            }
        }
    });
}

// Get status CSS class
function getStatusClass(status) {
    switch(status) {
        case 'sent': return 'label-success';
        case 'delivered': return 'label-primary';
        case 'read': return 'label-info';
        case 'failed': return 'label-danger';
        case 'pending': return 'label-warning';
        default: return 'label-default';
    }
}

// Auto-resize textarea
function autoResizeTextarea(element) {
    element.style.height = 'auto';
    element.style.height = element.scrollHeight + 'px';
}

// WhatsApp number formatter
function formatWhatsAppNumber(number) {
    // Remove all non-numeric characters
    var cleaned = number.replace(/\D/g, '');
    
    // Add country code if not present
    if(cleaned.length === 10) {
        cleaned = '91' + cleaned; // Assuming India
    }
    
    return cleaned;
}

// Check WhatsApp connection status
function checkWhatsAppConnection() {
    var base_url = $("#base_url").val();
    
    $.ajax({
        type: 'POST',
        url: base_url + 'whatsapp/test_connection',
        dataType: 'json',
        success: function(result) {
            var statusElement = $('#whatsapp_connection_status');
            
            if(result.status == "success") {
                statusElement.html('<i class="fa fa-circle text-green"></i> Connected');
                statusElement.attr('title', 'WhatsApp API is connected and working');
            } else {
                statusElement.html('<i class="fa fa-circle text-red"></i> Disconnected');
                statusElement.attr('title', result.message);
            }
        },
        error: function() {
            $('#whatsapp_connection_status').html('<i class="fa fa-circle text-red"></i> Error');
        }
    });
}

// Initialize connection status check on page load
$(document).ready(function() {
    if($('#whatsapp_connection_status').length) {
        checkWhatsAppConnection();
        
        // Check every 5 minutes
        setInterval(checkWhatsAppConnection, 300000);
    }
});

// Message scheduling helper
function scheduleMessage(phone, message, scheduledTime) {
    var base_url = $("#base_url").val();
    
    $.ajax({
        type: 'POST',
        url: base_url + 'whatsapp/schedule_message',
        data: {
            phone_number: phone,
            message: message,
            scheduled_time: scheduledTime
        },
        dataType: 'json',
        success: function(result) {
            if(result.status == "success") {
                toastr["success"]("Message scheduled successfully!");
            } else {
                toastr["error"](result.message || "Failed to schedule message!");
            }
        },
        error: function() {
            toastr["error"]("An error occurred while scheduling message!");
        }
    });
}

// Input validation helpers
function validateMessageForm(formId) {
    var form = $('#' + formId);
    var isValid = true;
    var errors = [];
    
    // Check phone number
    var phone = form.find('input[name="phone_number"]').val();
    if(!phone || !validatePhoneNumber(phone)) {
        errors.push('Valid phone number is required');
        isValid = false;
    }
    
    // Check message content
    var message = form.find('textarea[name="message"]').val();
    if(!message || message.trim().length === 0) {
        errors.push('Message content is required');
        isValid = false;
    }
    
    // Display errors
    if(!isValid) {
        toastr["error"](errors.join('<br>'));
    }
    
    return isValid;
}

// Emoji picker integration (if needed)
function initEmojiPicker(textareaId) {
    // This can be expanded with a proper emoji picker library
    var commonEmojis = ['😊', '👍', '❤️', '😂', '🔥', '💯', '🎉', '👏', '🙏', '💪'];
    
    var picker = '<div class="emoji-picker">';
    commonEmojis.forEach(function(emoji) {
        picker += '<span class="emoji-option" onclick="insertEmoji(\'' + textareaId + '\', \'' + emoji + '\')">' + emoji + '</span>';
    });
    picker += '</div>';
    
    $('#' + textareaId).after(picker);
}

function insertEmoji(textareaId, emoji) {
    var textarea = document.getElementById(textareaId);
    var cursorPos = textarea.selectionStart;
    var textBefore = textarea.value.substring(0, cursorPos);
    var textAfter = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
    
    textarea.value = textBefore + emoji + textAfter;
    textarea.focus();
    textarea.setSelectionRange(cursorPos + emoji.length, cursorPos + emoji.length);
    
    $(textarea).trigger('input');
}
