
/*Email validation code end*/
$('#send').on("click",function (e) {
	var base_url=$("#base_url").val();
    /*Initially flag set true*/
    var flag=true;

    function check_field(id)
    {

      if(!$("#"+id).val() ) //Also check Others????
        {

            $('#'+id+'_msg').fadeIn(200).show().html('Required Field').addClass('required');
            $('#'+id).css({'background-color' : '#E8E2E9'});
            flag=false;
        }
        else
        {
             $('#'+id+'_msg').fadeOut(200).hide();
             $('#'+id).css({'background-color' : '#FFFFFF'});    //White color
        }
    }


    //Validate Input box or selection box should not be blank or empty
	check_field("mobile");
	check_field("message");
	

    
	if(flag==false)
    {
		toastr["warning"]("You have Missed Something to Fillup!")
		return;
    }

    var this_id=this.id;

    

			//swal({ title: "Are you sure?",icon: "warning",buttons: true,dangerMode: true,}).then((sure) => {
	if(confirm("Are you sure ?")) {//confirmation start
				$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
				$("#"+this_id).attr('disabled',true);  //Enable Save or Update button
				e.preventDefault();
				data = new FormData($('#sms-form')[0]);//form name
				$.ajax({
				type: 'POST',
				url: base_url+'sms/send_message',
				data: data,
				cache: false,
				contentType: false,
				processData: false,
				success: function(result){
     // alert(result);//return;
     			result=result;
					if(result=="success")
					{
						toastr["success"]("SMS Sent Successfully!");
						$("#mobile,#message").val('');
						//return;
					}
					else if(result=="failed")
					{
					   toastr["error"]("Sorry! Failed to Send SMS.Try again!");
					}
					else
					{
						toastr["error"](result);
					}
					$("#"+this_id).attr('disabled',false);  //Enable Save or Update button
					$(".overlay").remove();
			   }
			   });
		} //confirmation sure
	//}); //confirmation end


   

});


//On Enter Move the cursor to desigtation Id
function shift_cursor(kevent,target){

    if(kevent.keyCode==13){
		$("#"+target).focus();
    }
	
}

$('#update').on("click",function (e) {
	var base_url=$("#base_url").val();
    var this_id=this.id;
    
    // Validate SMS API configuration
    if(!validateSmsApiConfig()) {
        return false;
    }
    
	if(confirm("Are you sure you want to save the SMS API configuration?")) {
		$(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
		$("#"+this_id).attr('disabled',true);
		e.preventDefault();
		data = new FormData($('#api-form')[0]);
		$.ajax({
			type: 'POST',
			url: base_url+'sms/api_update',
			data: data,
			cache: false,
			contentType: false,
			processData: false,
			success: function(result){
				if(result=="success")
				{
					toastr['success']("SMS API configuration saved successfully!");
					setTimeout(function() {
						location.reload();
					}, 1500);
				}
				else if(result=="failed")
				{
				   toastr['error']("Sorry! Failed to save configuration. Please try again.");
				}
				else
				{
					toastr['error'](result);
				}
				
				$("#"+this_id).attr('disabled',false);
				$(".overlay").remove();
		   },
		   error: function() {
			   toastr['error']("Network error. Please check your connection and try again.");
			   $("#"+this_id).attr('disabled',false);
			   $(".overlay").remove();
		   }
	   });
	}
});

// SMS API Configuration Validation
function validateSmsApiConfig() {
    var isValid = true;
    var errors = [];
    
    // Check if SMS status is selected
    var smsStatus = $("#sms_status").val();
    if(!smsStatus) {
        errors.push("Please select an SMS provider (HTTP/URL API, Twilio, or FiveMojo WhatsApp API)");
        isValid = false;
    }
    
    // If SMS is disabled (0), no need to validate further - return true
    if(smsStatus == '0') {
        return true;
    }
    
    // If HTTP/URL API is selected, validate required fields
    if(smsStatus == '1') {
        var hasUrl = false;
        var hasMobileKey = false;
        var hasMessageKey = false;
        
        // Check existing rows
        $("#api_table tbody tr").each(function() {
            var info = $(this).find('input[id^="info_"]').val();
            var key = $(this).find('input[id^="key_"]').val();
            var keyValue = $(this).find('input[id^="key_val_"]').val();
            
            if(info == 'url') {
                if(keyValue && keyValue.trim() !== '') {
                    hasUrl = true;
                    // Validate URL format - check the key_value field, not the key field
                    if(!isValidUrl(keyValue)) {
                        var errorMsg = getUrlValidationError(keyValue);
                        errors.push("URL Error: " + errorMsg + ". Example: https://api.africastalking.com/restless/send");
                        isValid = false;
                    }
                } else {
                    errors.push("Please enter a URL for your SMS provider");
                    isValid = false;
                }
            }
            if(info == 'mobile' && key) {
                hasMobileKey = true;
            }
            if(info == 'message' && key) {
                hasMessageKey = true;
            }
        });
        
        if(!hasUrl) {
            errors.push("Please add a URL for your SMS provider");
            isValid = false;
        }
        if(!hasMobileKey) {
            errors.push("Please add a Mobile Key (parameter name for phone numbers)");
            isValid = false;
        }
        if(!hasMessageKey) {
            errors.push("Please add a Message Key (parameter name for message content)");
            isValid = false;
        }
    }
    
    // If Twilio is selected, validate Twilio fields
    if(smsStatus == '2') {
        var accountSid = $("#account_sid").val();
        var authToken = $("#auth_token").val();
        var twilioPhone = $("#twilio_phone").val();
        
        if(!accountSid) {
            errors.push("Please enter your Twilio Account SID");
            isValid = false;
        }
        if(!authToken) {
            errors.push("Please enter your Twilio Auth Token");
            isValid = false;
        }
        if(!twilioPhone) {
            errors.push("Please enter your Twilio Phone Number");
            isValid = false;
        }
    }
    
    // If FiveMojo WhatsApp is selected, validate FiveMojo fields
    if(smsStatus == '3') {
        var instanceId = $("#whatsAppInstanceId").val();
        var token = $("#whatsAppToken").val();
        
        if(!instanceId) {
            errors.push("Please enter your FiveMojo Instance ID");
            isValid = false;
        }
        if(!token) {
            errors.push("Please enter your FiveMojo Token");
            isValid = false;
        }
    }
    
    // Display errors
    if(!isValid) {
        var errorMessage = "Please fix the following errors:\n\n" + errors.join("\n");
        toastr['error'](errorMessage);
    }
    
    return isValid;
}

// URL validation helper - more flexible validation
function isValidUrl(string) {
    // Check if string is empty or null
    if (!string || string.trim() === '') {
        return false;
    }
    
    // Remove any leading/trailing whitespace
    string = string.trim();
    
    // Basic URL pattern check - must start with http:// or https://
    var urlPattern = /^https?:\/\/.+/i;
    
    // Check if it matches the basic pattern
    if (!urlPattern.test(string)) {
        return false;
    }
    
    // Additional checks for common URL issues
    // Must not contain spaces
    if (string.indexOf(' ') !== -1) {
        return false;
    }
    
    // Must have a domain (at least one dot after the protocol)
    var withoutProtocol = string.replace(/^https?:\/\//, '');
    if (withoutProtocol.indexOf('.') === -1) {
        return false;
    }
    
    return true;
}

// Get detailed URL validation error message
function getUrlValidationError(url) {
    if (!url || url.trim() === '') {
        return "URL cannot be empty";
    }
    
    url = url.trim();
    
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        return "URL must start with http:// or https://";
    }
    
    if (url.indexOf(' ') !== -1) {
        return "URL cannot contain spaces";
    }
    
    var withoutProtocol = url.replace(/^https?:\/\//, '');
    if (withoutProtocol.indexOf('.') === -1) {
        return "URL must contain a domain name (e.g., api.example.com)";
    }
    
    return "Invalid URL format";
}

// Auto-populate Africa's Talking example (Default/Recommended)
function populateAfricasTalkingExample() {
    // Clear existing rows
    $("#api_table tbody").empty();
    
    // Reset row count
    $("#hidden_rowcount").val(0);
    
    // Add URL row
    addRowWithData('url', 'weblink', 'https://api.africastalking.com/restless/send');
    
    // Add Mobile Key row
    addRowWithData('mobile', 'to', '');
    
    // Add Message Key row
    addRowWithData('message', 'message', '');
    
    // Add Username row
    addRowWithData('username', 'username', 'YOUR_USERNAME');
    
    // Add API Key row
    addRowWithData('apikey', 'Apikey', 'YOUR_API_KEY');
    
    toastr['success']("Africa's Talking template loaded! Please update with your actual credentials.");
}

// Auto-populate Twilio example
function populateTwilioExample() {
    // Clear existing rows
    $("#api_table tbody").empty();
    
    // Reset row count
    $("#hidden_rowcount").val(0);
    
    // Add URL row
    addRowWithData('url', 'weblink', 'https://api.twilio.com/2010-04-01/Accounts/YOUR_ACCOUNT_SID/Messages.json');
    
    // Add Mobile Key row
    addRowWithData('mobile', 'To', '');
    
    // Add Message Key row
    addRowWithData('message', 'Body', '');
    
    // Add Account SID row
    addRowWithData('account_sid', 'AccountSid', 'YOUR_ACCOUNT_SID');
    
    // Add Auth Token row
    addRowWithData('auth_token', 'AuthToken', 'YOUR_AUTH_TOKEN');
    
    // Add From Phone row
    addRowWithData('from_phone', 'From', 'YOUR_TWILIO_PHONE');
    
    toastr['success']("Twilio template loaded! Please update with your actual credentials.");
}

// Auto-populate Generic SMS API example
function populateGenericExample() {
    // Clear existing rows
    $("#api_table tbody").empty();
    
    // Reset row count
    $("#hidden_rowcount").val(0);
    
    // Add URL row
    addRowWithData('url', 'weblink', 'https://your-sms-provider.com/api/send');
    
    // Add Mobile Key row
    addRowWithData('mobile', 'mobiles', '');
    
    // Add Message Key row
    addRowWithData('message', 'message', '');
    
    // Add API Key row
    addRowWithData('api_key', 'APIKey', 'YOUR_API_KEY');
    
    // Add Sender ID row
    addRowWithData('sender_id', 'senderid', 'YOUR_SENDER_ID');
    
    // Add Username row
    addRowWithData('username', 'username', 'YOUR_USERNAME');
    
    // Add Password row
    addRowWithData('password', 'password', 'YOUR_PASSWORD');
    
    toastr['success']("Generic SMS API template loaded! Please update with your actual credentials.");
}

// Auto-populate TextLocal example
function populateTextLocalExample() {
    // Clear existing rows
    $("#api_table tbody").empty();
    
    // Reset row count
    $("#hidden_rowcount").val(0);
    
    // Add URL row
    addRowWithData('url', 'weblink', 'https://api.textlocal.in/send/');
    
    // Add Mobile Key row
    addRowWithData('mobile', 'numbers', '');
    
    // Add Message Key row
    addRowWithData('message', 'message', '');
    
    // Add API Key row
    addRowWithData('api_key', 'apikey', 'YOUR_API_KEY');
    
    // Add Sender ID row
    addRowWithData('sender_id', 'sender', 'YOUR_SENDER_ID');
    
    // Add Username row
    addRowWithData('username', 'username', 'YOUR_USERNAME');
    
    // Add Hash row
    addRowWithData('hash', 'hash', 'YOUR_HASH');
    
    toastr['success']("TextLocal template loaded! Please update with your actual credentials.");
}

// Auto-populate MSG91 example
function populateMsg91Example() {
    // Clear existing rows
    $("#api_table tbody").empty();
    
    // Reset row count
    $("#hidden_rowcount").val(0);
    
    // Add URL row
    addRowWithData('url', 'weblink', 'https://api.msg91.com/api/v2/sendsms');
    
    // Add Mobile Key row
    addRowWithData('mobile', 'mobiles', '');
    
    // Add Message Key row
    addRowWithData('message', 'message', '');
    
    // Add Auth Key row
    addRowWithData('auth_key', 'authkey', 'YOUR_AUTH_KEY');
    
    // Add Sender ID row
    addRowWithData('sender_id', 'sender', 'YOUR_SENDER_ID');
    
    // Add Route row
    addRowWithData('route', 'route', '4');
    
    // Add Country row
    addRowWithData('country', 'country', '91');
    
    toastr['success']("MSG91 template loaded! Please update with your actual credentials.");
}

// Helper function to add row with data
function addRowWithData(info, key, keyValue) {
    var rowcount = parseInt($("#hidden_rowcount").val()) + 1;
    $("#hidden_rowcount").val(rowcount);
    
    var str = '<tr id="row_' + rowcount + '" data-row="' + rowcount + '">';
    
    // Special handling for mobile and message keys
    if(info == 'mobile') {
        str += '<td class="text-right">';
        str += '<label class="control-label">Mobile Key<label class="text-danger">*</label></label>';
        str += '<br><small class="text-dark" style="font-weight: 500;">Parameter name for phone numbers</small>';
        str += '<input type="hidden" id="info_' + rowcount + '" name="info_' + rowcount + '" value="' + info + '"></td>';
        str += '<td><input id="key_' + rowcount + '" name="key_' + rowcount + '" type="text" class="form-control" placeholder="e.g., to, mobiles, phone" value="' + key + '">';
        str += '<small class="text-primary" style="font-weight: bold;">Common values: <code style="background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">to</code>, <code style="background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">mobiles</code>, <code style="background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">phone</code></small></td>';
        str += '<td><input id="key_val_' + rowcount + '" name="key_val_' + rowcount + '" type="text" class="form-control" placeholder="Leave empty - auto-filled" readonly="true" value="' + keyValue + '">';
        str += '<small class="text-dark" style="font-weight: 500;">Auto-populated with actual phone number</small></td>';
    } else if(info == 'message') {
        str += '<td class="text-right">';
        str += '<label class="control-label">Message Key<label class="text-danger">*</label></label>';
        str += '<br><small class="text-dark" style="font-weight: 500;">Parameter name for message content</small>';
        str += '<input type="hidden" id="info_' + rowcount + '" name="info_' + rowcount + '" value="' + info + '"></td>';
        str += '<td><input id="key_' + rowcount + '" name="key_' + rowcount + '" type="text" class="form-control" placeholder="e.g., message, text, msg" value="' + key + '">';
        str += '<small class="text-primary" style="font-weight: bold;">Common values: <code style="background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">message</code>, <code style="background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">text</code>, <code style="background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">msg</code></small></td>';
        str += '<td><input id="key_val_' + rowcount + '" name="key_val_' + rowcount + '" type="text" class="form-control" placeholder="Leave empty - auto-filled" readonly="true" value="' + keyValue + '">';
        str += '<small class="text-dark" style="font-weight: 500;">Auto-populated with actual message content</small></td>';
    } else {
        // Default row for other parameters
        str += '<td class="text-right"><label class="control-label">' + info.charAt(0).toUpperCase() + info.slice(1) + ' Key<label class="text-danger">*</label></label>';
        str += '<input type="hidden" id="info_' + rowcount + '" name="info_' + rowcount + '" value="' + info + '"></td>';
        str += '<td><input id="key_' + rowcount + '" name="key_' + rowcount + '" type="text" class="form-control" value="' + key + '"></td>';
        str += '<td><input id="key_val_' + rowcount + '" name="key_val_' + rowcount + '" type="text" class="form-control" value="' + keyValue + '"></td>';
    }
    
    str += '<td><input type="button" class="btn btn-danger" name="btn_' + rowcount + '" id="btn_' + rowcount + '" value="-" title="Remove" onclick="removerow(' + rowcount + ')"></td>';
    str += '</tr>';
    
    $('#api_table tbody').append(str);
}

// Test SMS functionality
$('#test_sms').on("click", function(e) {
    var base_url = $("#base_url").val();
    var smsStatus = $("#sms_status").val();
    
    if(!smsStatus || smsStatus == '0') {
        toastr['warning']("Please select an SMS provider first before testing.");
        return;
    }
    
    // Show test SMS modal
    showTestSmsModal();
});

// Show test SMS modal
function showTestSmsModal() {
    // Create modal HTML
    var modalHtml = `
        <div class="modal fade" id="testSmsModal" tabindex="-1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title"><i class="fa fa-paper-plane"></i> Test SMS Configuration</h4>
                    </div>
                    <div class="modal-body">
                        <form id="testSmsForm">
                            <div class="form-group">
                                <label for="testPhone">Phone Number <span class="text-danger">*</span></label>
                                <input type="tel" class="form-control" id="testPhone" name="testPhone" 
                                       placeholder="+256712345678" value="+256712345678" required>
                                <small class="text-muted">Enter phone number with country code</small>
                            </div>
                            <div class="form-group">
                                <label for="testMessage">Message <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="testMessage" name="testMessage" 
                                          rows="3" placeholder="Enter test message" required>Test message from NCS Billing System</textarea>
                                <small class="text-muted">Enter the message you want to send</small>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-primary" id="sendTestSms">
                            <i class="fa fa-paper-plane"></i> Send Test SMS
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    $('#testSmsModal').remove();
    
    // Add modal to body
    $('body').append(modalHtml);
    
    // Show modal
    $('#testSmsModal').modal('show');
    
    // Handle send button click
    $('#sendTestSms').on('click', function() {
        sendTestSms();
    });
    
    // Handle Enter key in form
    $('#testSmsForm').on('keypress', function(e) {
        if (e.which === 13) {
            e.preventDefault();
            sendTestSms();
        }
    });
}

// Send test SMS
function sendTestSms() {
    var testPhone = $('#testPhone').val().trim();
    var testMessage = $('#testMessage').val().trim();
    var base_url = $("#base_url").val();
    
    // Validate inputs
    if (!testPhone) {
        toastr['error']("Please enter a phone number");
        $('#testPhone').focus();
        return;
    }
    
    if (!testMessage) {
        toastr['error']("Please enter a message");
        $('#testMessage').focus();
        return;
    }
    
    // Validate phone number format
    if (!isValidPhoneNumber(testPhone)) {
        toastr['error']("Please enter a valid phone number with country code (e.g., +256712345678)");
        $('#testPhone').focus();
        return;
    }
    
    // Disable send button and show loading
    $('#sendTestSms').attr('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Sending...');
    
    // Send AJAX request
    $.ajax({
        type: 'POST',
        url: base_url + 'sms/send_message',
        data: {
            mobile: testPhone,
            message: testMessage
        },
        success: function(result) {
            if (result == "success") {
                toastr['success']("Test SMS sent successfully to " + testPhone + "!");
                $('#testSmsModal').modal('hide');
            } else if (result == "failed") {
                toastr['error']("Failed to send test SMS. Please check your configuration.");
            } else {
                toastr['error']("Error: " + result);
            }
        },
        error: function() {
            toastr['error']("Network error. Please check your connection.");
        },
        complete: function() {
            $('#sendTestSms').attr('disabled', false).html('<i class="fa fa-paper-plane"></i> Send Test SMS');
        }
    });
}

// Phone number validation helper
function isValidPhoneNumber(phone) {
    // Basic phone number validation - should start with + and have at least 10 digits
    var phoneRegex = /^\+[1-9]\d{9,14}$/;
    return phoneRegex.test(phone);
}