(function($) {
    "use strict";

$(function() { 
	$('.selectpicker').selectpicker();
	$('.selectpicker').prop("selectedIndex", -1);
});

$(document).ready(function() {
	
/***
* Dummy Email List
***/
		// Add
	var actions = '<a class="save" title="Save"><i class="icon-copy dw dw-add"></i></a><a class="edit" title="Edit"><i class="icon-copy dw dw-edit-1"></i></a><a class="delete" title="Delete"><i class="icon-copy dw dw-delete-3"></i></a>';
    $(document).on('click', '.de_add', function(){
		var el = $(this).closest("#dummy_emails_list");
		$(this).attr("disabled", "disabled");
		el.find(".dataTables_paginate ul li").addClass("disabled");
		var index = el.find("table tbody tr:first-child").index();
        var row = '<tr>' +
            '<td>#</td>' +
            '<td id="sub>" class="table-plus edit_text"><textarea class="form-control" name="sub"></textarea></td>' +
            '<td id="msg" class="edit_text"><textarea class="form-control" name="msg"></textarea></td>' +
			'<td>' + actions + '</td>' +
        '</tr>';
    	el.find("table").prepend(row);		
		el.find("table tbody tr").eq(index).find(".save, .edit").toggle();
    });
	// Save
	$(document).on('click', '#dummy_emails_list .save', function(){
		var el = $(this).closest("#dummy_emails_list");
		var empty = false;
		var input = $(this).parents("tr").find('textarea');
		var content = [];
        input.each(function(n){
			if(!$(this).val()){
				$(this).addClass("error");
				empty = true;
			} else{
				content[n] = $(this).val();
                $(this).removeClass("error");
            }
		});
		$(this).parents("tr").find(".error").first().focus();
		if(!empty){
	  event.preventDefault();
	  var timeoutId;	
	  var get_target_id = $(this).parents("tr").attr("data-target");
	    clearTimeout(timeoutId);
		timeoutId = setTimeout(function() {
		$.ajax({
			url: "../functions/settings_functions.php",
			type: "POST",
			data: {
				target_id: get_target_id,
				de_data: content,
				de_filter: 'update'
			},
			dataType: "json",
			beforeSend: function(xhr) {
				$('.submission_status').html('Saving...').css("display", "flex").hide().fadeIn();
			},
			success: function(data) {
				var reSuccess = data.success;
				var reError = data.error;
				if (reSuccess) {
					var sub = data.sub;
					var msg = data.msg;
					var target_id = data.target_id;
					 $(this).parents("tr").attr('data-target', target_id);
					input.each(function(){
						$(this).parent("td.edit_text").html($(this).val());
					});
					  var saved = $(".submission_status").html(reSuccess);
					} else {
						var saved = $(".submission_status").html(reError);
						if(!$(".submission_status").hasClass("alert alert-danger")) {
							$(".submission_status").toggleClass("alert alert-danger");
						}					
					}
				saved;
				setTimeout(function() {
					  saved.fadeOut(function() {
						  $(this).removeClass("alert alert-danger");
						});
				}, 1000); 
			}
		});
		}, 1000);
			$(this).parents("tr").find(".save, .edit").toggle();
			el.find(".de_add").removeAttr("disabled");
			el.find(".dataTables_paginate ul li").removeClass("disabled");
		}		
    });
	// Edit
	$(document).on('click', '#dummy_emails_list .edit', function(){
		var el = $(this).closest("#dummy_emails_list");
        $(this).parents("tr").find("td.edit_text").each(function(){
			$(this).html('<textarea class="form-control">' + $(this).html() + '</textarea>');
		});		
		$(this).parents("tr").find(".save, .edit").toggle();
		el.find(".de_add").attr("disabled", "disabled");
		el.find(".dataTables_paginate ul li").addClass("disabled");
    });
	// Delete
	$(document).on('click', '#dummy_emails_list .delete', function(){
		event.preventDefault();
		var el = $(this).closest("#dummy_emails_list");
		var rm = $(this).parents("tr");
		var timeoutId;
		var get_target_id = $(this).parents("tr").attr('data-target');		 
			clearTimeout(timeoutId);
			timeoutId = setTimeout(function() {
			$.ajax({
				context:this,
				url: "../functions/settings_functions.php",
				type: "POST",
				data: {
					target_id: get_target_id,
					de_filter: 'delete'
				},
				dataType: "json",
				beforeSend: function(xhr) {
					$('.submission_status').html('Saving...').css("display", "flex").hide().fadeIn();
				},
				success: function(data) {
					var reSuccess = data.success;
					var reError = data.error;
					if (reSuccess) {
							var target_id = data.target_id;
							rm.remove();
							var saved = $(".submission_status").html(reSuccess);
						} else {
							var saved = $(".submission_status").html(reError);
							if(!$(".submission_status").hasClass("alert alert-danger")) {
								$(".submission_status").toggleClass("alert alert-danger");
							}					
						}
					saved;
					setTimeout(function() {
						  saved.fadeOut(function() {
							  $(this).removeClass("alert alert-danger");
							});
					}, 1000); 
				}
			});
	}, 1000);
		el.find(".de_add").removeAttr("disabled");
		el.find(".dataTables_paginate ul li").removeClass("disabled");
    }); 
	
/***
X Dummy Emails List X
***/

/***
* Email Filter List
***/


         var selected_rows = 0;


	 var dataTable = $('.email_filter_table').DataTable({
		scrollCollapse: true,
		autoWidth: false,
		responsive: false,
		columnDefs: [{
			targets: "datatable-nosort",
			orderable: false,
		}],
		"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
		"language": {
			"info": "_START_-_END_ of _TOTAL_ entries",
			searchPlaceholder: "Search",
			paginate: {
				next: '<i class="ion-chevron-right"></i>',
				previous: '<i class="ion-chevron-left"></i>'  
			}
		},
		dom: '<"container-fluid"<"row"<"col"l><"col"f>><"row"<"col md-12 mt-2 mb-2"B>>>rtip',
		 buttons: {
			 
                        "buttons": [
                            {
                                text: 'Add Email Address',
								attr:  {
									title: 'Add Email Address',
									id: 'ea_add',
									name: 'ea_add',
									class: "ea_add"
								},
                                action: function () {
									$("#AddEmail").modal('toggle');
                                },
                            },
							{
                                text: 'Upload Email List',
								attr:  {
									title: 'Upload Email List',
									id: 'ea_upload',
									name: 'ea_upload',
									class: "ea_upload"
								},
                                action: function () {
									$("#ImportEmail").modal('toggle');
                                },
                            },
							{
								text: 'Edit',
								attr:  {
									title: 'Edit',
									id: 'ea_edit',
									name: 'ea_edit',
									class: "ea_edit"
								},
								action: function(){
                  edit_row();

								}
							},
							{
								text: 'Delete',
								attr:  {
									title: 'Delete',
									id: 'ea_delete',
									name: 'ea_delete',
									class: "ea_delete"
								},
								action: function(){
								  delete_row();
								}
							},
							{
								text: 'Select All',
								attr:  {
									title: 'Select All',
									id: 'ea_selc_all',
									name: 'ea_selc_all',
									class: "ea_selc_all"
								},
								action: function(){
								  $('.email_filter_table tr').each(function(index) {
									  // add a class to the row based on its index
									$(this).toggleClass("selected");
								  });
								}
							}
                        ],
                    },
					
					
	});
	
         // ************************* Select/Deselect Rows *************
         $(document).on('click', '.email_filter_table tbody tr', function () {
            $(this).toggleClass('selected');
         });

         // *********************** Add Email ******************

        $(document).on('click', '#add_email_button', function(e){
			e.preventDefault();
           var email_address = $("#email_address").val();
           var email_reason = $("#email_reason").val();
           var pattern = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if(email_address == ""){
              Swal.fire({
                title: "Empty!",
                text: "Please Enter Email Address",
                icon: 'info',

              });
            }
            else if(!pattern.test(email_address)){
              Swal.fire({
                title: "Incorrect Email Format!",
                text: "Email should be like: abc@gmail.com",
                icon: 'error',    
              });
            }
            else{
			$.ajax({
				type: "POST",
				url: "../functions/settings_functions.php",
				data: { ea_filter: "add_email", email_address: email_address, email_reason: email_reason },
				dataType: "json",
				success: function (result) {
					var title = "";
					var text = "";
					if (result.msg == 'success') {
						title = "Great!";
						text = email_address + " - Added!";
					} else if (result.msg == 'info') {
						title = "Matched!";
						text = email_address + " Already Exists!";
					} else {
						title = "Oops!";
						text = "There has been an error, Try Again Later!";
						console.error("Server Error:", result); // Log server response for debugging
					}
					Swal.fire({
						icon: result.msg,
						title: title,
						text: text
					}).then(function () {
						location.reload();
					});

					if (result.msg == 'success') {
						$('#AddEmail').modal('toggle');
						$("#email_address").val("");
					}
				},
				error: function (xhr, status, error) {
				console.error("AJAX Error:", status, error); // Log AJAX error for debugging
				Swal.fire({
						title: "Error",
						text: "Failed to communicate with the server. Please try again.",
						icon: 'error',
					});
				  }
			}); // End of ajax
              
            }
        }); // End of Add Email Function


        // *********************** Delete Row Function ***************//
        function delete_row() {
			const selected_ids = [];
			if($('.email_filter_table tr').hasClass('selected')){
				$('.email_filter_table tr.selected').each(function(){
					selected_ids.push($(this).attr('data-target'));
				});
              $.ajax({
				  type: "POST",
                  url: "../functions/settings_functions.php",
                  data: {ea_filter:"delete_email", selected_ids:selected_ids},
                  success: function(result){

                    var title = "";
                    var text = "";
                    var icon = "info";
                    if(result.msg == 'error'){
                      title = "Oops!";
                      text = "There has been an error, Try Again Later!";
                      icon = result.msg;
                    }
                    else{
                      title = "Great!";
                      text = 'Successfully deleted';
                      icon = "success";
                    }
                    Swal.fire({
                        title: title,
                        text: text,
                        icon: icon,
                    }).then(function() {
					  location.reload();
					});
                  }
              });//End of ajax
             
            }
            else{
              Swal.fire({
                title: "Select First!",
                text: "Select the rows you want to delete",
                icon: 'warning',
              });

            }
            
        }// End of Delete Row Function


        //******************** Import CSV *******************//
         $(document).on('submit', '#upload_csv', function(event) {
			event.preventDefault();
			var fileName = $("#file").val();

			if (fileName == "") {
				Swal.fire({
					title: "Select File!",
					text: "Please Select CSV File",
					icon: 'info',
				});
			} else {
				var formData = new FormData(this);
				formData.append('ea_filter', 'upload');
				$.ajax({
					type: 'POST',
					url: "../functions/settings_functions.php",
					data: formData,
					processData: false,
					contentType: false,
					dataType: "json",
					success: function(result) {
						if (result && result.status === "success") {
							Swal.fire({
								title: "Upload Complete",
								text: result.message,
								icon: 'success',
							});
							if (result.errors && result.errors.length > 0) {
								console.error("Errors:", result.errors.join("\n"));
							}
							$('#ImportEmail').modal('toggle');
							$("#file").val("");
							$("#select_colum").html("");
							location.reload();
						} else {
							Swal.fire({
								title: "Error",
								text: result.message || "An unexpected error occurred.",
								icon: 'error',
							});
						}
					},
					error: function(xhr) {
						Swal.fire({
							title: "Error",
							text: "Failed to upload the file. Please try again.",
							icon: 'error',
						});
					}
				});
			}
		}); // End of Import CSV function


        // ************************* Close CSV Modal ************

        $(document).on('click', '#closeCSVModal', function(){
          $("#file").val("");
          $("#select_colum").html("");

        })
         
		 
		     // ************************** Read CSV File ************
        	$(document).on('change', '#upload_csv input', function(){


            var files = document.querySelector('#file').files;

            // Selected file
            var file = files[0];

            // FileReader Object
              var reader = new FileReader();

              // Read file data as string 
              reader.readAsText(file);

              // Load event
              reader.onload = function(event) {
                      
                  // Read file data
              var csvdata = event.target.result;

              // Split by line break to gets rows Array
              var rowData = csvdata.split('\n');
              rowColData = rowData[0].split(',');
            
              var output = "<select name='get_column' class='form-control'>";
              for (var col = 0; col < rowColData.length; col++) {
                output += "<option value="+col+">"+rowColData[col]+"</option>";
                }
                output += "</select>";
                document.getElementById("select_colum").innerHTML = output;
              
              };
              
			}) // End of Read CSV File
		  
	
/***
X Email Filter List X
***/

/***
* MX SERVER FILTER
***/
// MX SERVER FILTER
var mxActions = '<a class="save" title="Save"><i class="icon-copy dw dw-add"></i></a><a class="edit" title="Edit"><i class="icon-copy dw dw-edit-1"></i></a><a class="delete" title="Delete"><i class="icon-copy dw dw-delete-3"></i></a>';

// Add MX Response
$(document).on('click', '.mx_add', function() {
    var el = $(this).closest('#mx_server_filter');
    $(this).attr('disabled', 'disabled');
    el.find('.dataTables_paginate ul li').addClass('disabled');
    var index = el.find('table tbody tr:first-child').index();
    var row = '<tr>' +
        '<td>#</td>' +
        '<td class="table-plus edit_text"><input type="text" class="form-control" name="mx_server"></td>' +
        '<td class="edit_text"><input type="text" class="form-control" name="reason"></td>' +
        '<td>' + mxActions + '</td>' +
        '</tr>';
    el.find('table').prepend(row);
    el.find('table tbody tr').eq(index).find('.save, .edit').toggle();
});

// Save MX Response
$(document).on('click', '#mx_server_filter .save', function() {
    var el = $(this).closest('#mx_server_filter');
    var empty = false;
    var input = $(this).parents('tr').find('input[type="text"]');
    var content = [];
    input.each(function(n) {
        if (!$(this).val()) {
            $(this).addClass('error');
            empty = true;
        } else {
            content[n] = $(this).val();
            $(this).removeClass('error');
        }
    });
    $(this).parents('tr').find('.error').first().focus();
    if (!empty) {
        event.preventDefault();
        var timeoutId;
        var get_target_id = $(this).parents('tr').attr('data-target');
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            $.ajax({
                url: '../functions/settings_functions.php',
                type: 'POST',
                data: {
                    target_id: get_target_id,
                    mx_data: content,
                    mx_filter: 'update'
                },
                dataType: 'json',
                beforeSend: function() {
                    $('.submission_status').html('Saving...').css('display', 'flex').hide().fadeIn();
                },
                success: function(data) {
                    var reSuccess = data.success;
                    var reError = data.error;
                    if (reSuccess) {
                        var target_id = data.target_id;
                        $(this).parents('tr').attr('data-target', target_id);
                        input.each(function() {
                            $(this).parent('td.edit_text').html($(this).val());
                        });
                        var saved = $('.submission_status').html(reSuccess);
                    } else {
                        var saved = $('.submission_status').html(reError);
                        if (!$('.submission_status').hasClass('alert alert-danger')) {
                            $('.submission_status').toggleClass('alert alert-danger');
                        }
                    }
                    setTimeout(function() {
                        saved.fadeOut(function() {
                            $(this).removeClass('alert alert-danger');
                        });
                    }, 1000);
                }
            });
        }, 1000);
        $(this).parents('tr').find('.save, .edit').toggle();
        el.find('.mx_add').removeAttr('disabled');
        el.find('.dataTables_paginate ul li').removeClass('disabled');
    }
});

// Edit MX Response
$(document).on('click', '#mx_server_filter .edit', function() {
    var el = $(this).closest('#mx_server_filter');
    $(this).parents('tr').find('td.edit_text').each(function() {
        $(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
    });
    $(this).parents('tr').find('.save, .edit').toggle();
    el.find('.mx_add').attr('disabled', 'disabled');
    el.find('.dataTables_paginate ul li').addClass('disabled');
});

// Delete MX Response
$(document).on('click', '#mx_server_filter .delete', function() {
    event.preventDefault();
    var el = $(this).closest('#mx_server_filter');
    var rm = $(this).parents('tr');
    var timeoutId;
    var get_target_id = $(this).parents('tr').attr('data-target');
    clearTimeout(timeoutId);
    timeoutId = setTimeout(function() {
        $.ajax({
            url: '../functions/settings_functions.php',
            type: 'POST',
            data: {
                target_id: get_target_id,
                mx_filter: 'delete'
            },
            dataType: 'json',
            beforeSend: function() {
                $('.submission_status').html('Saving...').css('display', 'flex').hide().fadeIn();
            },
            success: function(data) {
                var reSuccess = data.success;
                var reError = data.error;
                if (reSuccess) {
                    rm.remove();
                    var saved = $('.submission_status').html(reSuccess);
                } else {
                    var saved = $('.submission_status').html(reError);
                    if (!$('.submission_status').hasClass('alert alert-danger')) {
                        $('.submission_status').toggleClass('alert alert-danger');
                    }
                }
                setTimeout(function() {
                    saved.fadeOut(function() {
                        $(this).removeClass('alert alert-danger');
                    });
                }, 1000);
            }
        });
    }, 1000);
    el.find('.mx_add').removeAttr('disabled');
    el.find('.dataTables_paginate ul li').removeClass('disabled');
});

// Delete All MX Responses
$(document).on('click', '.mx_delete_all', function() {
    var el = $(this).closest('#mx_server_filter');
    Swal.fire({
        title: 'Delete All MX Filters?',
        text: 'This will remove all MX server filters from the database. Are you sure?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, delete all!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '../functions/settings_functions.php',
                type: 'POST',
                data: { mx_filter: 'delete_all' },
                dataType: 'json',
                beforeSend: function() {
                    $('.submission_status').html('Deleting...').css('display', 'flex').hide().fadeIn();
                },
                success: function(data) {
                    var reSuccess = data.success;
                    var reError = data.error;
                    if (reSuccess) {
                        el.find('table tbody').empty();
                        var saved = $('.submission_status').html(reSuccess);
                    } else {
                        var saved = $('.submission_status').html(reError);
                        if (!$('.submission_status').hasClass('alert alert-danger')) {
                            $('.submission_status').toggleClass('alert alert-danger');
                        }
                    }
                    setTimeout(function() {
                        saved.fadeOut(function() {
                            $(this).removeClass('alert alert-danger');
                        });
                    }, 1000);
                }
            });
        }
    });
});
/***
X MX SERVER FILTER X
***/
	
/***
* SMTP SERVERS
***/
// Add
	var smtp_actions = '<a class="smtp_test_mail" title="Test Connection"><i class="icon-copy dw dw-mail"></i></a><a class="save" title="Save"><i class="icon-copy dw dw-add"></i></a><a class="edit" title="Edit"><i class="icon-copy dw dw-edit-1"></i></a><a class="delete" title="Delete"><i class="icon-copy dw dw-delete-3"></i></a>';
    $(document).on('click', '.smtp_add', function(){
		var el = $(this).closest("#smtp_servers");
		$(this).attr("disabled", "disabled");
		el.find(".dataTables_paginate ul li").addClass("disabled");
		var index = el.find("table tbody tr:first-child").index();
        var row = '<tr>' +
            '<td>#</td>' +
            '<td id="smtp_limit" class="edit_text"><input type="text" class="form-control" name="smtp_limit"></td>' +
            '<td id="smtp_email" class="edit_text"><input type="text" class="form-control" name="smtp_email"></td>' +
            '<td id="smtp_host" class="edit_text"><input type="text" class="form-control" name="smtp_host"></td>' +
            '<td id="smtp_port" class="edit_text"><input type="text" class="form-control" name="smtp_port"></td>' +
            '<td id="smtp_security" class="edit_text"><input type="text" class="form-control" name="smtp_security"></td>' +
            '<td id="smtp_ssl_verify" class="edit_text"><input type="text" class="form-control" name="smtp_ssl_verify"></td>' +
            '<td id="smtp_auth" class="edit_text"><input type="text" class="form-control" name="smtp_auth"></td>' +
            '<td id="smtp_user" class="edit_text"><input type="text" class="form-control" name="smtp_user"></td>' +
            '<td id="smtp_pass" class="edit_text"><input type="text" class="form-control" name="smtp_pass"></td>' +
			'<td>' + smtp_actions + '</td>' +
        '</tr>';
    	el.find("table").prepend(row);		
		el.find("table tbody tr").eq(index).find(".save, .edit").toggle();
    });
	// Save
	$("#smtp_servers").on("click", ".save", function(){
		var el = $(this).closest("#smtp_servers");
		var empty = false;
		var input = $(this).parents("tr").find('input[type="text"]');
		var content = [];
        input.each(function(n){
			if(!$(this).val()){
				$(this).addClass("error");
				empty = true;
			} else{
				content[n] = $(this).val();
                $(this).removeClass("error");
            }
		});
		$(this).parents("tr").find(".error").first().focus();
		if(!empty){
	  event.preventDefault();
	  var timeoutId;	
	  var get_target_id = $(this).parents("tr").attr("data-target");
	    clearTimeout(timeoutId);
		timeoutId = setTimeout(function() {
		$.ajax({
			url: "../functions/settings_functions.php",
			type: "POST",
			data: {
				target_id: get_target_id,
				smtp_data: content,
				smtp_server: 'update'
			},
			dataType: "json",
			beforeSend: function(xhr) {
				$('.submission_status').html('Saving...').css("display", "flex").hide().fadeIn();
			},
			success: function(data) {
				var reSuccess = data.success;
				var reError = data.error;
				if (reSuccess) {
					var mx_server = data.mx_server;
					var reason = data.reason;
					var target_id = data.target_id;
					 $(this).parents("tr").attr('data-target', target_id);
					input.each(function(){
						$(this).parent("td.edit_text").html($(this).val());
					});
					  var saved = $(".submission_status").html(reSuccess);
					} else {
						var saved = $(".submission_status").html(reError);
						if(!$(".submission_status").hasClass("alert alert-danger")) {
							$(".submission_status").toggleClass("alert alert-danger");
						}					
					}
				saved;
				setTimeout(function() {
					  saved.fadeOut(function() {
						  $(this).removeClass("alert alert-danger");
						});
				}, 1000); 
			}
		});
		}, 1000);
			$(this).parents("tr").find(".save, .edit").toggle();
			el.find(".smtp_add").removeAttr("disabled");
			el.find(".dataTables_paginate ul li").removeClass("disabled");
		}		
    });
	// Edit
	$("#smtp_servers").on("click", ".edit", function(){
		var el = $(this).closest("#smtp_servers");
        $(this).parents("tr").find("td.edit_text").each(function(){
			$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
		});		
		$(this).parents("tr").find(".save, .edit").toggle();
		el.find(".smtp_add").attr("disabled", "disabled");
		el.find(".dataTables_paginate ul li").addClass("disabled");
    });
	// Delete
	$("#smtp_servers").on("click", ".delete", function(){
		event.preventDefault();
		var el = $(this).closest("#smtp_servers");
		var rm = $(this).parents("tr");
		var timeoutId;
		var get_target_id = $(this).parents("tr").attr('data-target');		 
			clearTimeout(timeoutId);
			timeoutId = setTimeout(function() {
			$.ajax({
				context:this,
				url: "../functions/settings_functions.php",
				type: "POST",
				data: {
					target_id: get_target_id,
					smtp_server: 'delete'
				},
				dataType: "json",
				beforeSend: function(xhr) {
					$('.submission_status').html('Saving...').css("display", "flex").hide().fadeIn();
				},
				success: function(data) {
					var reSuccess = data.success;
					var reError = data.error;
					if (reSuccess) {
							var target_id = data.target_id;
							rm.remove();
							var saved = $(".submission_status").html(reSuccess);
						} else {
							var saved = $(".submission_status").html(reError);
							if(!$(".submission_status").hasClass("alert alert-danger")) {
								$(".submission_status").toggleClass("alert alert-danger");
							}					
						}
					saved;
					setTimeout(function() {
						  saved.fadeOut(function() {
							  $(this).removeClass("alert alert-danger");
							});
					}, 1000); 
				}
			});
	}, 1000);
		el.find(".smtp_add").removeAttr("disabled");
		el.find(".dataTables_paginate ul li").removeClass("disabled");
    });
	
	// Test Mail
	$("#smtp_servers").on("click", ".smtp_test_mail", function(){
	event.preventDefault();
		var el = $(this).closest("#smtp_servers");
		var empty = false;
		var content = [];
        var input = $(this).parents("tr").find("td.edit_text");
		input.each(function(n){
			if(!$(this).text()){
				$(this).addClass("error");
				empty = true;
			} else{
				content[n] = $(this).text();
                $(this).removeClass("error");
            }
		});
		if(!empty) {
			console.log('email not assigned');
		} else {
			console.log('email assigned');
		}
	
	var get_target_id = $(this).parents("tr").attr('data-target');

    Swal.fire({
        title: "Test SMTP Connection",
        text: "Insert An Email To Receive",
        input: 'text',
        showCancelButton: true,
        confirmButtonText: 'Send Test',
        showLoaderOnConfirm: true,
        preConfirm: function(text) {
            return new Promise(function(resolve) {
                    $.ajax({
                        url: "../functions/settings_functions.php",
                        method: 'POST',
                        data: {
							target_id: get_target_id,
                            camp_smtp_test: text
                        },
						dataType: "json"
					}).done(function (response) {
						if(response['title'] === 'Success') {
							Swal.fire({
							title: "Sent",
							showConfirmButton: true,
							icon: 'success',
							type: "success",
							html: 'Email successfully sent',
							})
						} else if(response['title'] === 'Error'){
							Swal.fire({
							title: "Connection Error",
							showConfirmButton: true,
							icon: 'error',
							type: "error",
							html: 'Could not sent email',
							})
						}
					})
				})
			},
		})
		
	});
	
function edit_row() {
	// Select all rows with the "selected" class
	$('.email_filter_table tr.selected').each(function () {
		// Find all editable cells in the row and replace their content with input fields
		$(this).find("td.edit_text").each(function () {
			$(this).html('<textarea class="form-control">' + $(this).text() + '</textarea>');
		});
	});
}

// Save Email Reason
$(document).on('click', '.save-email-reason', function () {
    var id = $(this).data("id");
    var email = $("#email_" + id).text().trim();
    var reason = $("#reason_" + id).text().trim();

    $.ajax({
        url: "../functions/settings_functions.php",
        type: "POST",
        data: {
            ea_filter: "update",
            target_id: id,
            ea_data: email,
            reason_add: reason
        },
        dataType: "json",
        beforeSend: function () {
            $(".save-email-reason[data-id='" + id + "']").prop("disabled", true).text("Saving...");
        },
        success: function (response) {
            if (response.msg === "success") {
                alert(response.success);
            } else if (response.msg === "error") {
                alert(response.error || "An error occurred.");
            } else {
                alert("Unexpected response from the server.");
            }
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", status, error);
            alert("Failed to communicate with the server. Please try again.");
        },
        complete: function () {
            $(".save-email-reason[data-id='" + id + "']").prop("disabled", false).text("Save");
        }
    });
});
 
// doc ready	
});

})(jQuery);