$(document).ready(function() {
    // Initialize form handlers
    initializeFormHandlers();
    
    // Load history table if on history page
    if ($('#sms_history_table').length) {
        loadSMSHistory();
    }
    
    // Load customer details if customer is pre-selected
    if ($('#customer_id').val()) {
        loadCustomerDetails();
    }
});

function initializeFormHandlers() {
    // Send SMS button click
    $('#send').click(function() {
        sendPromotionalSMS();
    });

    // Template change handler
    $('#template_id').change(function() {
        loadTemplate();
    });

    // Customer selection handlers
    $('#customer_id').change(function() {
        loadCustomerDetails();
    });

    $('#customer_ids').change(function() {
        updateSelectedCount();
    });

    // Message input handler for preview
    $('#message').on('input', function() {
        updatePreview();
    });
}

function toggleSendTypeOptions() {
    var sendType = $('#send_type').val();
    
    // Hide all option divs
    $('#single_customer_div, #bulk_customers_div, #all_customers_div').hide();
    
    // Show relevant div based on selection
    if (sendType === 'single') {
        $('#single_customer_div').show();
    } else if (sendType === 'bulk') {
        $('#bulk_customers_div').show();
    } else if (sendType === 'all') {
        $('#all_customers_div').show();
    }
}

function loadTemplate() {
    var templateId = $('#template_id').val();
    
    if (templateId) {
        $.ajax({
            url: base_url + 'sms_promotional/get_template_content_ajax',
            type: 'POST',
            data: { template_id: templateId },
            dataType: 'json',
            success: function(response) {
                if (response.status) {
                    $('#message').val(response.content);
                    updatePreview();
                }
            },
            error: function() {
                toastr.error('Error loading template');
            }
        });
    }
}

function loadCustomerDetails() {
    var customerId = $('#customer_id').val();
    
    if (customerId) {
        $.ajax({
            url: base_url + 'sms_promotional/get_customer_details_ajax',
            type: 'POST',
            data: { customer_id: customerId },
            dataType: 'json',
            success: function(response) {
                if (response.status) {
                    var details = '<p><strong>Name:</strong> ' + response.customer_name + '</p>';
                    details += '<p><strong>Mobile:</strong> ' + response.mobile + '</p>';
                    if (response.email) {
                        details += '<p><strong>Email:</strong> ' + response.email + '</p>';
                    }
                    if (response.address) {
                        details += '<p><strong>Address:</strong> ' + response.address + '</p>';
                    }
                    
                    $('#customer_details_content').html(details);
                    $('#customer_details_div').show();
                    updatePreview();
                }
            },
            error: function() {
                toastr.error('Error loading customer details');
            }
        });
    } else {
        $('#customer_details_div').hide();
    }
}

function updateSelectedCount() {
    var selectedCount = $('#customer_ids option:selected').length;
    $('#selected_count').text(selectedCount + ' customers selected');
    
    if (selectedCount > 0) {
        $('#selected_customers_div').show();
        updateSelectedCustomersList();
    } else {
        $('#selected_customers_div').hide();
    }
}

function updateSelectedCustomersList() {
    var selectedCustomers = [];
    $('#customer_ids option:selected').each(function() {
        selectedCustomers.push($(this).text());
    });
    
    var listHtml = '<ul class="list-unstyled">';
    selectedCustomers.forEach(function(customer) {
        listHtml += '<li><i class="fa fa-user"></i> ' + customer + '</li>';
    });
    listHtml += '</ul>';
    
    $('#selected_customers_list').html(listHtml);
}

function selectAllCustomers() {
    $('#customer_ids option').prop('selected', true);
    updateSelectedCount();
}

function clearAllCustomers() {
    $('#customer_ids option').prop('selected', false);
    updateSelectedCount();
}

function selectActiveCustomers() {
    // For now, select all customers (assuming all are active)
    // This can be enhanced to filter by status
    selectAllCustomers();
}

function updatePreview() {
    var message = $('#message').val();
    var sendType = $('input[name="send_type"]').val() || $('#send_type').val();
    
    if (message && sendType) {
        var preview = message;
        
        // Replace variables with sample data for preview
        preview = preview.replace(/\{\{customer_name\}\}/g, 'John Doe');
        preview = preview.replace(/\{\{customer_mobile\}\}/g, '1234567890');
        preview = preview.replace(/\{\{store_name\}\}/g, 'Your Store');
        preview = preview.replace(/\{\{store_mobile\}\}/g, '9876543210');
        preview = preview.replace(/\{\{store_address\}\}/g, 'Store Address');
        preview = preview.replace(/\{\{current_date\}\}/g, new Date().toLocaleDateString());
        preview = preview.replace(/\{\{current_time\}\}/g, new Date().toLocaleTimeString());
        
        $('#message_preview').text(preview);
        $('#preview_div').show();
    } else {
        $('#preview_div').hide();
    }
}

function sendPromotionalSMS() {
    // Validate form
    if (!validateForm()) {
        return;
    }
    
    // Show loading
    $('#send').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Sending...');
    
    // Prepare form data
    var formData = new FormData();
    formData.append('send_type', $('input[name="send_type"]').val() || $('#send_type').val());
    formData.append('message', $('#message').val());
    formData.append('template_id', $('#template_id').val());
    
    // CSRF token is automatically added by $.ajaxSetup() in code_js.php
    
    if ($('input[name="send_type"]').val() === 'single' || $('#send_type').val() === 'single') {
        formData.append('customer_id', $('#customer_id').val());
    } else if ($('input[name="send_type"]').val() === 'bulk' || $('#send_type').val() === 'bulk') {
        var selectedIds = [];
        $('#customer_ids option:selected').each(function() {
            selectedIds.push($(this).val());
        });
        formData.append('customer_ids', selectedIds.join(','));
    }
    
    
    // Send AJAX request
    $.ajax({
        url: base_url + 'sms_promotional/send_message',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.status) {
                toastr.success(response.message);
                // Reset form
                resetForm();
            } else {
                toastr.error(response.message);
            }
        },
        error: function() {
            toastr.error('Error sending SMS. Please try again.');
        },
        complete: function() {
            // Reset button
            $('#send').prop('disabled', false).html('Send SMS');
        }
    });
}

function validateForm() {
    var isValid = true;
    
    // Clear previous error messages
    $('.text-danger').hide();
    
    // Validate send type
    var sendType = $('input[name="send_type"]').val() || $('#send_type').val();
    if (!sendType) {
        $('#send_type_msg').text('Please select a send type').show();
        isValid = false;
    }
    
    // Validate customer selection for single/bulk
    if (sendType === 'single') {
        if (!$('#customer_id').val()) {
            $('#customer_id_msg').text('Please select a customer').show();
            isValid = false;
        }
    } else if (sendType === 'bulk') {
        if ($('#customer_ids option:selected').length === 0) {
            $('#customer_ids_msg').text('Please select at least one customer').show();
            isValid = false;
        }
    }
    
    // Validate message
    if (!$('#message').val().trim()) {
        $('#message_msg').text('Please enter a message').show();
        isValid = false;
    }
    
    return isValid;
}

function resetForm() {
    $('#promotional-sms-form, #single-sms-form, #bulk-sms-form')[0].reset();
    $('#preview_div, #customer_details_div, #selected_customers_div').hide();
    $('.text-danger').hide();
}

function loadSMSHistory() {
    console.log('Loading SMS history...');
    console.log('Base URL:', base_url);
    console.log('AJAX URL:', base_url + "sms_promotional/ajax_history_list");
    
    $('#sms_history_table').DataTable({
        "processing": true,
        "serverSide": false,
        "ajax": {
            "url": base_url + "sms_promotional/ajax_history_list",
            "type": "POST",
            "dataSrc": function(json) {
                console.log('AJAX Response:', json);
                return json;
            },
            "error": function(xhr, error, thrown) {
                console.log('DataTables AJAX error:', xhr.responseText);
                console.log('Error details:', error, thrown);
                toastr.error('Error loading SMS history: ' + thrown);
            }
        },
        "columns": [
            { "data": "id" },
            { "data": "send_type" },
            { "data": "message" },
            { "data": "success_count" },
            { "data": "failed_count" },
            { "data": "created_date" },
            { "data": "created_time" },
            { "data": "created_by" },
            { 
                "data": null,
                "orderable": false,
                "render": function(data, type, row) {
                    return '<button class="btn btn-sm btn-info" onclick="viewSMSDetails(' + row.id + ')">View Details</button>';
                }
            }
        ],
        "order": [[0, "desc"]],
        "pageLength": 25
    });
}

function viewSMSDetails(id) {
    // This can be implemented to show detailed SMS information
    toastr.info('SMS Details for ID: ' + id);
}
