jQuery(function ($){
    var Admin = {
        init: function (){
        	jQuery("body").on('click','.category_delete',this.HandleCateDelete); // this function for delete category
            jQuery("body").on('click', '.subcategory_delete', this.HandleSubCateDelete);//THIS FUNCTION FOR DELETING SUBCATEGORY
			jQuery("body").on('click', '.province_delete', this.HandleProvinceDelete); // this function for deleting province 
			jQuery("body").on('click', '.village_delete', this.HandleVillageDelete); //this function for deleting the village  from web_Village
			jQuery("body").on('click', '.mail_delete', this.HandleMailDelete); // this function for deleting the mail from web_mailformats
			jQuery("body").on('click', '.sms_delete', this.HandleSmsDelete);  //this function for deleting the sms from web_smsformats
			jQuery("body").on('click', '.project_delete', this.HandleProjectDelete); // this function is for deleting the project from web_projects
			jQuery("body").on('click', '.status_delete', this.HandleStatusDelete );  //function to delete the status from web_tickestatus
			jQuery("body").on('click', '.base_delete', this.HandleBaseDelete );  //fucntion to delete the knowledge base from tbl_mst_faq
			jQuery("body").on('click', '.disposition_delete', this.HandleDispositionDelete ); //fucntion to delete the Disposition
			jQuery("body").on('click', '.delete_bulletin', this.HandleBulletinDelete ); //fucntion to delete the bulletin
			jQuery("body").on('click', '.bulk_delete', this.HandleBulkDelete);  //this function for deleting the bulk sms email template
			jQuery("body").on('click','#submitclkcity',this.HandleProvinceSubmit);  //function for handling request of province submit and update 
			jQuery("body").on('click','#submitclkvillage',this.HandleVillageSubmit);  //function for handling request of village submit and update 
			jQuery("body").on('click','#submitclksign',this.HandleSignature); //function for handling request of mail submit and update 
			jQuery("body").on('click','#submitclksub',this.HandleSubcategorySubmit); // function for handling request of subcategory submit and update 
			jQuery("body").on('click','#submitclkmail',this.HandleMailSubmit);  //function for handling request of mail format submit and update 
			jQuery("body").on('click','#submitclksms',this.HandleSmsSubmit); //fucntion for handling request of sms format submit and update
			jQuery("body").on('click','#submitclkproject',this.HandleProjectSubmit);  //function for handling request of  project submit and update 
			jQuery("body").on('click','#submitclkstatus',this.HandleStatusSubmit); //function for handling request of status submit and update 
			jQuery("body").on('click','#submitclkbase',this.HandleBaseSubmit);  //function for handling request of Knowledge Base  submit and update 
			jQuery("body").on('click','#submitclkbulk',this.HandleBulkSubmit);  //function for handling request of Knowledge Base  submit and update 
			jQuery("body").on('click','#submitclkescalation',this.HandleEscalationSubmit); //function for handlong request of updating  escalation status 
			jQuery("body").on('click','#submitclksmtp',this.HandleSMTPSubmit); //FUNCTION  for  handling  update request of smtp 
			jQuery("body").on('click','#submitclkimap',this.HandleIMAPSubmit); //FUNCTION  for  handling  update request of imap
			jQuery("body").on('click','#submitclkdisposition',this.HandleDispositionSubmit); //function to  update or insert in disposition table
			jQuery("body").on('click','#submitclkcallbacks',this.HandleCallbacksSubmit); //function to update   callback 
			jQuery("body").on('click','#update_sent_mail',this.HandleSentMailSubmit); //function to update tbl connection record for multiple case aert
			jQuery("body").on('click','#submitclk',this.HandleCategorySubmit);
			jQuery("body").on('click', '.formsubmitnews', this.validateForm);  //function to handle the request of  department assign 
			jQuery("body").on('click', '#submitadhoc', this.HandleAdhocMail);  //function to handle the updation of adhoc email id
			jQuery("body").on('click', '.webchat_delete', this.HandlewebchatDelete); 
			jQuery("body").on('click','#submitclkwebtemp',this.HandlewebchatSubmit); 
			jQuery("body").on('click', '.whatsapp_delete', this.HandlewhatsappDelete); 
			jQuery("body").on('click','#submitclkwhatstemp',this.HandlewhatsappSubmit);
			// jQuery("body").on('click','#submitclkspam',this.HandleSpamSubmit);  
			// jQuery("body").on('click', '.spam_mail_delete', this.HandleSpamMailDelete); 
       		

       		$('#type').select2({});
			$('#level3_users').select2({});
			$('#level2_users').select2({});
			$('#level1_users').select2({});
			this.bindEvents();
			this.fetchEmailRules(); // Load on page load
			this.loadEmailRuleData();
       	},
		bindEvents: function () {
			$('body').on('submit', '#emailRuleForm', this.handleEmailFormSubmit);
			$('body').on('keypress', '#priorityEscalationHour, #nonpriorityEscalationHour', function (e) {
				const charCode = e.which ? e.which : e.keyCode;
				if (charCode < 48 || charCode > 57) {
					e.preventDefault(); // Block non-numeric characters
				}
			});
			$('body').on('keypress', '#escalationTime', function (e) {
				const charCode = e.which ? e.which : e.keyCode;
				const charStr = String.fromCharCode(charCode);

				if (!/[0-9:]/.test(charStr)) {
					e.preventDefault(); // block anything except 0-9 and colon
				}
			});

        },
		sanitizeEmails: function (emailString) {
			// Alert if anything other than commas is used as a separator
			if (emailString.includes(';') || emailString.includes(' ') || emailString.includes('\n')) {
				alert('Please use only commas (,) to separate emails no semicolons, spaces, or newlines.');
				return null;
			}

			return emailString
				.split(',')
				.map(e => e.trim().toLowerCase())
				.filter(e => e.length > 0);
		},
		validateEmails: function (emails) {
			const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

			for (let i = 0; i < emails.length; i++) {
				if (!emailRegex.test(emails[i])) {
					alert(`Invalid email format: ${emails[i]}`);
					return false;
				}
			}
			return true;
		},
		hasDuplicates: function (array) {
            return new Set(array).size !== array.length;
        },
		handleEmailFormSubmit: function (e) {
			e.preventDefault();

			const escalationEmails = Admin.sanitizeEmails($('#escalationEmailIDs').val());
			const blockedEmails = Admin.sanitizeEmails($('#blockedMails').val());

			const escalationTime = $('#escalationTime').val().trim();
			const priorityHour = $('#priorityEscalationHour').val().trim();
			const nonPriorityHour = $('#nonpriorityEscalationHour').val().trim();

			if (Admin.hasDuplicates(escalationEmails)) {
				alert('Duplicate emails found in Escalation Email IDs.');
				return;
			}

			if (Admin.hasDuplicates(blockedEmails)) {
				alert('Duplicate emails found in Blocked Emails.');
				return;
			}
			//  Validate email format
			if (!Admin.validateEmails(escalationEmails) || !Admin.validateEmails(blockedEmails)) {
				return;
			}

			if (escalationEmails.length > 0) {
				if (priorityHour === '' || nonPriorityHour === '' || escalationTime === '') {
					alert('Priority/Non-priority hours and escalation time are required when escalation email is provided.');
					return;
				}
			}

			// Validate Escalation Time Format (if not empty)
			if (escalationTime !== '') {
				const timeRegex = /^([01]\d|2[0-3]):([0-5]\d)$/; // 00:00 to 23:59
				if (!timeRegex.test(escalationTime)) {
					alert('Escalation Time must be in HH:MM format (00:00 to 23:59)');
					return;
				}
			}

			const formData = {
				action: 'save_email_rule',
				stickyAgent: $('[name="stickyAgent"]').val(),
				priorityEscalationHour: priorityHour,
				nonpriorityEscalationHour: nonPriorityHour,
				escalationTime: escalationTime,
				escalationEmailIDs: escalationEmails.join(','),
				blockedMails: blockedEmails.join(','),
				microsoftDynamics: $('[name="microsoftDynamics"]').val(),
				enableLogging: $('[name="enableLogging"]').val()
			};

			// AJAX call
			$.ajax({
				url: 'admin/web_admin_function.php',
				method: 'POST',
				data: formData,
				dataType: 'json',
				success: function (res) {
					 if (res.status === 'success') {
						alert(res.message);
						Admin.fetchEmailRules();
					} else {
						alert(res.message);
					}
				},
				error: function () {
					alert('Error while saving the settings.');
				}
			});
		},
		fetchEmailRules: function () {
            $.ajax({
				url: 'admin/web_admin_function.php',
				method: 'POST',
				dataType: 'json',
				data: { action: 'fetch_email_rules' },
                success: function (data) {
					const tbody = $('#rulesTable tbody');
					tbody.empty(); // Clear previous rows

					if (data.length === 0) {
						tbody.append('<tr><td colspan="10">No records found</td></tr>');
						return;
					}

					$.each(data, function (index, row) {
						// Format email strings to break into new lines
						const escalationEmails = row.escalationEmailIDs
							? row.escalationEmailIDs.split(',').map(e => e.trim()).join('<br>')
							: '-';

						const blockedEmails = row.blockedMails
							? row.blockedMails.split(',').map(e => e.trim()).join('<br>')
							: '-';

						const tr = $('<tr>');
						tr.append(`<td>${row.id}</td>`);
						tr.append(`<td>${row.stickyAgent == 1 ? 'Yes' : 'No'}</td>`);
						tr.append(`<td>${row.priorityEscalationHour || '-'}</td>`);
						tr.append(`<td>${row.nonpriorityEscalationHour || '-'}</td>`);
						tr.append(`<td>${row.escalationTime || '-'}</td>`);
						tr.append(`<td>${escalationEmails}</td>`);
						tr.append(`<td>${blockedEmails}</td>`);
						tr.append(`<td>${row.microsoftDynamics == 1 ? 'Enabled' : 'Disabled'}</td>`);
						tr.append(`<td>${row.enableLogging == 1 ? 'Yes' : 'No'}</td>`);
						tr.append(`<td>${row.timestamp}</td>`);
						tbody.append(tr);
					});
				},
				error: function () {
					alert('Failed to fetch records.');
				}
            });
        },
		loadEmailRuleData: function () {
			$.ajax({
				url: 'admin/web_admin_function.php',
				method: 'POST',
				data: { action: 'get_email_rule' },
				dataType: 'json',
				success: function (res) {
					if (res.status === 'success') {
						const data = res.data;

						$('[name="stickyAgent"]').val(data.stickyAgent);
						$('#priorityEscalationHour').val(data.priorityEscalationHour);
						$('#nonpriorityEscalationHour').val(data.nonpriorityEscalationHour);
						$('#escalationTime').val(data.escalationTime);
						$('#escalationEmailIDs').val(data.escalationEmailIDs);
						$('#blockedMails').val(data.blockedMails);
						$('[name="microsoftDynamics"]').val(data.microsoftDynamics);
						$('[name="enableLogging"]').val(data.enableLogging);
					} else {
						alert('No record found.');
					}
				},
				error: function () {
					alert('Error loading email rule data.');
				}
			});
		},
		HandleCateDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'category_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Category Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error deleting Category</div>');
						}
					},
					error: function (xhr, status, error) {
						console.error(xhr.responseText);
						$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Unable to delete Category</div>');
					}
				});
			}
		},
		HandleSubCateDelete: function () {
			if (confirm("Are you sure to delete this subcategory?")) {
				var id = $(this).data('id');
			    console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'subcategory_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Subcategory Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000); 
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error deleting Sub Category </div>');
						}
					}
				});
			}
		},
		HandleBulkDelete: function () {
			if (confirm("Are you sure to delete this Template?")) {
				var id = $(this).data('id');
			    console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'bulk_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Template Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000); 
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error deleting Template</div>');
						}
					}
				});
			}
		},
		HandleBulletinDelete: function () {
			if (confirm("Are you sure to delete this Bulletin?")) {
				var id = $(this).data('id');
			    console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'delete_bulletin' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Bulletin Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000); 
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error deleting Bulletin </div>');
						}
					}
				});
			}
		},
		HandleProvinceDelete: function () {
			if (confirm("Are you sure to delete this province?")) {
				var id = $(this).data('id');
				console.log(id);
		
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'province_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Province Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error deleting province</div>');
						}
					}
				});
			}
		},
		HandleVillageDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'village_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success')  {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">District Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000); 
						} else {
				
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting District/div>');
						}
					}
				});
			}
		},
		HandleMailDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'mail_delete' },

					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Mail Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Mail </div>');
						}
					},
					error: function () {
						
						$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Mail </div>');
					}
				});
			}
		},
		HandleSmsDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'sms_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Mail Format Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Mail Format</div>');
						}
					},
					error: function () {
						$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Mail Format</div>');
					}
				});
			}
		},HandlewebchatDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'webchat_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">WebChat Template Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting WebChat Template</div>');
						}
					},
					error: function () {
						$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting WebChat Template</div>');
					}
				});
			}
		},
		// HandleSpamMailDelete: function () {
        //     if (confirm("Are you sure to delete?")) {
        //         var id = $(this).data('id');
        //         console.log("Deleting ID:", id);
        //         $.ajax({
        //             method: 'POST',
        //             url: 'admin/web_admin_function.php',
        //             data: { id: id, action: 'spam_mail_delete' },
        //             success: function (response) {
        //                 if (response.trim().toLowerCase() === 'success') {
        //                     $('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Blocked Mail Deleted Successfully</div>');
        //                     setTimeout(function () {
        //                         location.reload();
        //                     }, 2000);
        //                 } else {
        //                     $('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Blocked Mail</div>');
        //                 }
        //             },
        //             error: function () {
        //                 $('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Blocked Mail</div>');
        //             }
        //         });
        //     }
        // },
		HandlewhatsappDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'whatsapp_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">WhatsApp Template Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting WhatsApp Template</div>');
						}
					},
					error: function () {
						$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting WhatsApp Template</div>');
					}
				});
			}
		},
		HandleProjectDelete: function (e) {
			if (confirm("Are you sure to delete?")) {
				var id = $(this).data('id');
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'project_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') { 
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Project Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Project </div>');
						}
					},
					error: function () {
						$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error Deleting Project </div>');
					}
				});
			}
		},
		HandleStatusDelete: function () {
			if (confirm("Are you sure to delete?")) {
				var id = parseInt($(this).data('id'));
				console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: {'id': id, 'action': 'status_delete'},
					success: function (response) {
						if (response.trim() === 'success') { 
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Category Delete Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000);
						} else {
							alert('Error updating status: ' + response);
						}
					}
				});
			}
		},
		HandleBaseDelete: function () {
			if (confirm("Are you sure to delete this FAQ?")) {
				var i_id = $(this).data('i_id');
				console.log('i_id:', i_id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'i_id': i_id, 'action': 'base_delete' },
					success: function (response) {
						console.log('AJAX Response:', response);
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">FAQ Deleted Successfully</div>');
							setTimeout(function () {
								location.reload(true);
							}, 2000); 
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Deletion Failed: ' + response + '</div>');
						}
					}					
				});
			}
		},
		HandleDispositionDelete: function () {
			if (confirm("Are you sure to delete this Disposition?")) {
				var id = $(this).data('id');
			    console.log(id);
				$.ajax({
					method: 'POST',
					url: 'admin/web_admin_function.php',
					data: { 'id': id, 'action': 'disposition_delete' },
					success: function (response) {
						if (response.trim().toLowerCase() === 'success') {
							$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Disposition Deleted Successfully</div>');
							setTimeout(function () {
								location.reload();
							}, 2000); 
						} else {
							$('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error deleting Sub Category </div>');
						}
					}
				});
			}
		},
		HandleCategorySubmit: function(e) {
			e.preventDefault();
			var complaint_type = $('#type').val(); // Get the complaint type value
			if (complaint_type == '0') {
				alert("Please Select Complaint Type!");
				$('#type').focus();
				return false;
			}
		
			var category = $('#category').val();
			if (!category.trim()) {
				alert("Please Enter a Category!");
				$('#category').focus();
				return false;
			} else {
				var V_Description = $('#V_Description').val();
				var id = $('#id').val();
		
				// Log the data being sent to web_admin_function.php
				console.log('Data sent to web_admin_function.php:', {
					'V_Description': V_Description,
					'category': category.trim(),
					'complaint_type': complaint_type, // Add complaint type to the data object
					'id': id,
					'action': 'Submit_category'
				});
		
				$.ajax({
					url: 'admin/web_admin_function.php',
					type: "POST",
					data: {
						'V_Description': V_Description,
						'category': category.trim(),
						'complaint_type': complaint_type, // Include complaint type in the data
						'id': id,
						'action': 'Submit_category'
					},
					success: function(data) {
						$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Category ' + (id !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_category');
							window.location.href = "admin_index.php?action=view_category&token=" + encodeURIComponent(encodedToken);
						}, 2000); 
					}
				});
			}
		},
		HandleSubcategorySubmit: function (e) {
			e.preventDefault();
			var subcategory = $('#subcategory').val();
			if (!subcategory) {
				alert("Please enter Sub Category!");
				$('#subcategory').focus();
				return false;
			}
			var category = $('#category').val();
			if (!category) {
				alert("Please choose a Category!");
				$('#category').focus();
				return false;
			}
			var time_hours = $('#time_hours').val();
			if (!time_hours || isNaN(time_hours) || time_hours <= 0) {
				alert("Please enter a valid Escalation Time in hours");
				$('#time_hours').focus();
				return false;
			}
			var level1_users = $('#level1_users').val();
			if (!level1_users || isNaN(level1_users) || level1_users <= 0) {
				alert("Please select level 1 user");
				$('#level1_users').focus();
				return false;
			}
			var V_Description = $('#V_Description').val();
			var second_resolution = $('#second_resolution').val();
			var third_resolution = $('#third_resolution').val();
			var level1_users = $('#level1_users').val();
			var level2_users = $('#level2_users').val();
			var level3_users = $('#level3_users').val();
			var id = $('#id').val();
			$.ajax({
				url: 'admin/web_admin_function.php',
				type: 'POST',
				data: {
					'category': category,
					'subcategory': subcategory,
					'time_hours': time_hours,
					'V_Description': V_Description,
					'second_resolution': second_resolution,
					'third_resolution': third_resolution,
					'level1_users': level1_users,
					'level2_users': level2_users,
					'level3_users': level3_users,
					'id': id,
					'action': 'Submit_subcategory'
				},
				success: function (data) {
					$('#success').html('<div class="alert alert-success alert-dismissible" role="alert">' + data + '</div>');
					setTimeout(function () {
						var encodedToken = btoa('view_subcategory');
						window.location.href = "admin_index.php?action=view_subcategory&token=" + encodeURIComponent(encodedToken);
					}, 2000); 
				}
			})
		},
		HandleProvinceSubmit: function (e) {
			e.preventDefault();
			var id = jQuery("#id").val();
			var city = jQuery("#city").val();
			var action = (id !== '') ? 'update_province' : 'submit_province';
			var regex = /^[a-zA-Z\s]+$/;

			if (city === '') {
				// Show alert for empty province
				alert('Please enter Province Name');
				return; // Stop further execution
			}

			// Check if the city field is empty or contains invalid characters
			if (!regex.test(city)) {
				// Show alert for empty or invalid province
				alert('Please enter a valid Province Name');
				return; // Stop further execution
			}
			
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: { 'id': id, 'city': city, 'action': action },
				success: function (response) {
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Province ' + (id !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_province');
							window.location.href = "admin_index.php?action=view_province&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				}
			});
		},
		HandleSentMailSubmit: function(e){
			e.preventDefault();
		
			const sent_mail = $("#sent_mail").val();
			const case_count = $("#case_count").val();
			const status_active = $("input[name='status_active']:checked").val(); // Get the selected radio button value

			$.ajax({
				url: 'admin/web_admin_function.php',
				type: 'POST',
				data: {
					action: 'update_sent_mail',
					sent_mail: sent_mail,
					case_count: case_count,
					status_active: status_active 
				},
				success: function (response) {
					alert(response);
					$("#message-box").html(response);
					setTimeout(() => {
						location.reload();
					}, 2000);
				},
				error: function () {
					alert("Failed to update. Please try again."); 
					$("#message-box").html("Failed to update. Please try again.");
				}
			});
		},		
		HandleVillageSubmit: function (e) {
			e.preventDefault();
			
			var district = jQuery("#district").val();
			if (!district) {
				alert('Please Select Province!');
				return;
			}
			var village = jQuery("#village").val();
		
			var villageRegex = /^[a-zA-Z\s]+$/;
			if (!village) {
				alert('Village cannot be empty!');
				return;
			}
			if (!villageRegex.test(village)) {
				alert('Please enter valid Village Name');
				return;
			}
			var V_Description = jQuery("#V_Description").val();
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': jQuery("#id").val(),
					'district': district,
					'village': village,
					'V_Description': V_Description,
					'action': 'submit_village'
				},
				success: function (response) {
					try {
						var jsonResponse = JSON.parse(response);
						if (jsonResponse.error) {
							jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + jsonResponse.error_msg + '</div>');
						} else if (jsonResponse.message === 'success') {
							jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Village ' + (village !== '' ? 'updated' : 'inserted') + ' successfully</div>');
							setTimeout(function () {
								var encodedToken = btoa('view_village');
								window.location.href = "admin_index.php?action=view_village&token=" + encodeURIComponent(encodedToken);
							}, 2000);
						} else {
							jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Unexpected Error: ' + response + '</div>');
						}
					} catch (e) {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Parse Error: ' + response + '</div>');
					}
				}
			});
		}
,		
		HandleMailSubmit: function (e) {
			e.preventDefault();
			
			var template_name = $("#template_name").val();
			var type = $("#type").val();
			var subject = $("#subject").val();
			var greeting = $("#greeting").val();
			var body = $("#body").val();
			var description = $("#description").val();
			var signature = $("#signature").val();
			var expiry = $("#expiry").val();

			// Check if template_name is empty
			if (template_name === '') {
				alert('Please enter a template name.');
				return; // Stop further execution
			}
		
			// Check if type is empty
			if (type === '') {
				alert('Please enter a mail type.');
				return; // Stop further execution
			}
		
			// Check if subject is empty
			if (subject === '') {
				alert('Please enter a mail subject.');
				return; // Stop further execution
			}
		
			// Check if greeting is empty
			if (greeting === '') {
				alert('Please enter a mail greeting.');
				return; // Stop further execution
			}
		
			// Check if description is empty
			if (description === '') {
				alert('Please enter a description.');
				return; // Stop further execution
			}
			if (expiry !== "" && (!/^\d+$/.test(expiry) || parseInt(expiry) < 0)) {
				alert("Please enter a valid Expiry Time (a non-negative integer).");
				$('#expiry').focus();
				return false;
			}
			var fields = [
				{ id: "#template_name", name: "TemplateName" },
				{ id: "#type", name: "Type" },
				{ id: "#subject", name: "Subject" },
				{ id: "#greeting", name: "Greeting" },
				
				{ id: "#description", name: "Description" }
			];
		
			for (var i = 0; i < fields.length; i++) {
				var field = fields[i];
				var value = jQuery(field.id).val();
			  
				if (!value) {
				  jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Please Enter ' + field.name + '</div>');
				  return;
				}
			  }
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': jQuery("#id").val(),
					'template_name': jQuery("#template_name").val(),
					'type': jQuery("#type").val(),
					'subject': jQuery("#subject").val(),
					'greeting': jQuery("#greeting").val(),
					'body': jQuery("#body").val(),
					'description': jQuery("#description").val(),
					'signature': jQuery("#signature").val(),
					'expiry': jQuery("#expiry").val(),
					'action': (jQuery("#id").val() !== '') ? 'update_mail' : 'submit_mail'
				},
				success: function (response) {
					console.log(response);
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Mail ' + (jQuery("#id").val() !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_mail');
							window.location.href = "admin_index.php?action=view_mail&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				},
				error: function (xhr, status, error) {
					console.error(xhr.responseText);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + error + '</div>');
				}
			});
		},
		HandleSmsSubmit: function (e) {
			e.preventDefault();
			console.log('HandleSmsSubmit function triggered');
			var expiry = $("#expiry").val();
			var description = $("#description").val();
			var footer = $("#footer").val();
			var body = $("#body").val();
			var header = $("#header").val();
			var type = $("#type").val();
			var template_name = $("#template_name").val();
			if (template_name === '') {
				alert('Please enter a template name.');
				return; // Stop further execution
			}
			if (type === '') {
				alert('Please enter type.');
				return; // Stop further execution
			}

			if (header === '') {
				alert('Please enter Header.');
				return; // Stop further execution
			}
			if (body === '') {
				alert('Please enter Body.');
				return; // Stop further execution
			}
			if (description === '') {
				alert('Please enter Description.');
				return; // Stop further execution
			}

			if (expiry !== "" && (isNaN(expiry) || parseInt(expiry) <= 0)) {
				alert("Please enter a valid Expiry Time");
				$('#expiry').focus();
				return false;
			}
			var fields = [
				{ id: "#template_name", name: "Template Name" },
				{ id: "#type", name: "Type" },
				{ id: "#header", name: "Header" },
				{ id: "#body", name: "Body" },
				{ id: "#description", name: "Description" }
			];
		
			for (var i = 0; i < fields.length; i++) {
				var field = fields[i];
				var value = jQuery(field.id).val();
		
				if (!value) {
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Please Enter ' + field.name + '</div>');
					return;
				}
			}
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': jQuery("#id").val(),
					'template_name': jQuery("#template_name").val(),
					'type': jQuery("#type").val(),
					'header': jQuery("#header").val(),
					'body': jQuery("#body").val(),
					'footer': jQuery("#footer").val(),
					'description': jQuery("#description").val(),
					'expiry': jQuery("#expiry").val(),
					'action': (jQuery("#id").val() !== '') ? 'update_sms' : 'submit_sms'
				},
				success: function (response) {
					console.log(response);
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">SMS Format ' + (jQuery("#id").val() !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_sms');
							window.location.href = "admin_index.php?action=view_sms&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				},
				error: function (xhr, status, error) {
					console.error(xhr.responseText);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + error + '</div>');
				}
			});
		},HandlewebchatSubmit: function (e) {
			e.preventDefault();
			if (template_name === '') {
				alert('Please enter a template name.');
				return; // Stop further execution
			}
			if (type === '') {
				alert('Please enter type.');
				return; // Stop further execution
			}

			
			if (body === '') {
				alert('Please enter Content.');
				return; // Stop further execution
			}
			
			var fields = [
				{ id: "#template_name", name: "Template Name" },
				{ id: "#type", name: "Type" },
				{ id: "#body", name: "Body" }
			];
		
			for (var i = 0; i < fields.length; i++) {
				var field = fields[i];
				var value = jQuery(field.id).val();
		
				if (!value) {
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Please Enter ' + field.name + '</div>');
					return;
				}
			}
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': jQuery("#id").val(),
					'template_name': jQuery("#template_name").val(),
					'type': jQuery("#type").val(),
					'body': jQuery("#body").val(),
					'action': (jQuery("#id").val() !== '') ? 'update_webchat' : 'submit_webchat'
				},
				success: function (response) {
					console.log(response);
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">WebChat Template ' + (jQuery("#id").val() !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('webchat_template');
							window.location.href = "admin_index.php?action=view_sms&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				},
				error: function (xhr, status, error) {
					console.error(xhr.responseText);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + error + '</div>');
				}
			});
		},HandlewhatsappSubmit: function (e) {
			console.log("whatsapp submit");
			e.preventDefault();
			if (template_name === '') {
				alert('Please enter a template name.');
				return; // Stop further execution
			}
			if (type === '') {
				alert('Please enter type.');
				return; // Stop further execution
			}

			
			if (body === '') {
				alert('Please enter Content.');
				return; // Stop further execution
			}
			
			var fields = [
				{ id: "#template_name", name: "Template Name" },
				{ id: "#type", name: "Type" },
				{ id: "#body", name: "Body" }
			];
		
			for (var i = 0; i < fields.length; i++) {
				var field = fields[i];
				var value = jQuery(field.id).val();
		
				if (!value) {
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Please Enter ' + field.name + '</div>');
					return;
				}
			}
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': jQuery("#id").val(),
					'template_name': jQuery("#template_name").val(),
					'type': jQuery("#type").val(),
					'body': jQuery("#body").val(),
					'action': (jQuery("#id").val() !== '') ? 'update_whatsapp' : 'submit_whatsapp'
				},
				success: function (response) {
					console.log(response);
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Whatsapp Template ' + (jQuery("#id").val() !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('whatsapp_template');
							window.location.href = "admin_index.php?action=view_sms&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				},
				error: function (xhr, status, error) {
					console.error(xhr.responseText);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + error + '</div>');
				}
			});
		},
		HandleProjectSubmit: function(e) {
			e.preventDefault();
		
			var category = $('#category').val();
			if (!category) {
				alert("Please choose a Category!");
				$('#category').focus();
				return false;
			}
		
			var projectname = $('#vProjectName').val();
			var ProjectRegex = /^[a-zA-Z\s]+$/;
			if (!projectname) {
				alert("Please enter Project Name!");
				$('#vProjectName').focus();
				return;
			}
		
			if (!ProjectRegex.test(projectname)) {
				alert("Please enter a valid Project Name!");
				$('#vProjectName').focus();
				return;
			}
		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'category': category,
					'vProjectName': projectname,
					'id': jQuery("#id").val(),
					'action': (jQuery("#id").val() !== '') ? 'update_project' : 'submit_project'
				},
				success: function(response) {
					console.log(response);
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Project ' + (jQuery("#id").val() !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function() {
							var encodedToken = btoa('view_project');
							window.location.href = "admin_index.php?action=view_project&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				},
				error: function(xhr, status, error) {
					console.error(xhr.responseText);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + error + '</div>');
				}
			});
		},
		
		HandleStatusSubmit : function(e){
			e.preventDefault();
			var id = jQuery("#id").val();
			var status = jQuery("#status").val();
			var action = (id !== '') ? 'update_status' : 'submit_status';
		
			if(status.trim() === ''){
				alert('Please enter Status Name!');
				return;
			}
			var statusRegex = /^[a-zA-Z\s]+$/;

			if (!statusRegex.test(status)) {
				alert('Please enter valid Status Name!');
				return;
			}

			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: { 'id': id, 'status': status, 'action': action },
				success: function (response) {
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Province ' + (id !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_status');
							window.location.href = "admin_index.php?action=view_province&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
					
				}
			});
			
		},
		// HandleSpamSubmit :function(e){
		// 	e.preventDefault();

		// 	var mail = jQuery('#mail').val();
		// 	var action = 'spam_mail';
		// 	jQuery.ajax({
		// 		method:'POST',
		// 		url:'admin/web_admin_function.php',
		// 		data:{'mail':mail ,'action':action},
		// 		success:function(response){
		// 			if(response.trim().toLowerCase() === 'success'){
		// 				jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Mail Id Blocked successfully</div>');
		// 				setTimeout(function () {
		// 					var encodedToken = btoa('spam_mail');
		// 					window.location.href = "admin_index.php?action=view_province&token=" + encodeURIComponent(encodedToken);
		// 				}, 2000);
		// 			}
		// 		}
		// 	});
		// },
		HandleBaseSubmit(e) {
			e.preventDefault();
			
			var id = jQuery("#id").val();
			var v_qus = jQuery("#qus").val();
			var v_ans = jQuery("#ans").val();
		
			if (!v_qus.trim() || !v_ans.trim()) {
				console.log("Showing alert: Please enter both Question and Answer.");
				alert('Please enter both Question and Answer.');
				return;
			}
		
			var action = (id !== '') ? 'update_base' : 'submit_base';
		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: { 'i_id': id, 'v_qus': v_qus, 'v_ans': v_ans, 'action': action },
				success: function (response) {
					console.log('AJAX Response:', response);
					var jsonResponse;
					try {
						jsonResponse = JSON.parse(response);
					} catch (e) {
						console.log('Invalid JSON response:', response);
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Invalid server response</div>');
						return;
					}
		
					if (jsonResponse.status === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Knowledge Base ' + (id !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_base');
							window.location.href = "admin_index.php?action=view_base&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + jsonResponse.message + '</div>');
					}
				}
			});
		},
		HandleBulkSubmit(e) {
			e.preventDefault();
		
			var id = jQuery("#id").val();  // Make sure the correct value is retrieved
			var type = jQuery("#type").val();
			var slug = jQuery("#slug").val();
			var template_name = jQuery("#template_name").val();
			var template_content = jQuery("#template_content").val();
		
			// Check for empty fields and alert the user
			if (!type) {
				alert("Type cannot be empty!");
				return;
			}
			if (!template_name) {
				alert("Template name cannot be empty!");
				return;
			}
			if (!template_content) {
				alert("Template content cannot be empty!");
				return;
			}
			console.log("update bulk clicked");
		
			var action = "update_bulk_data"; // Action to update the template
		
			
		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': id,  // Ensure 'id' is correctly passed
					'template_name': template_name,
					'template_content': template_content,
					'action': action,
					'slug':slug,
					'type': type
				},
				success: function (response) {
					console.log('AJAX Response:', response);
					var jsonResponse;
					try {
						jsonResponse = JSON.parse(response);  // Parse the JSON response
					} catch (e) {
						console.log('Invalid JSON response:', response); // Handle invalid JSON
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Invalid server response</div>');
						return;
					}
		
					if (jsonResponse.status === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Template ' + (id !== '' ? 'updated' : 'inserted') + ' successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('email_sms_template');
							window.location.href = "admin_index.php?action=view_base&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + jsonResponse.message + '</div>');
					}
				}
			});
		},
		
		HandleEscalationSubmit: function(e) {
			e.preventDefault();
		
			var id = jQuery("#id").val();
			var escalation_to = jQuery("input[name='escalation_to']:checked").val();
			var escalation_media = jQuery("input[name='escalation_media']:checked").val();
			var escalation_list = jQuery("#escalation_list option:selected").map(function() {
				return this.value;
			}).get();
		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': id,
					'escalation_to': escalation_to,
					'escalation_media': escalation_media,
					'escalation_list': escalation_list,
					'action': 'Submit_escalation'
				},
				success: function(response) {
					console.log('Response from server:', response);
					if (response.trim().toLowerCase() === 'success') {
						console.log('Status Updated Successfully');
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Status Updated Successfully</div>');
						setTimeout(function() {
							var encodedToken = btoa('view_escalation');
							window.location.href = "admin_index.php?action=view_escalation&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						console.log('Error updating status:', response);
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				},
				error: function(jqXHR, textStatus, errorThrown) {
					console.log('AJAX Error:', textStatus, errorThrown);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">AJAX Error: ' + errorThrown + '</div>');
				}
			});
		},
		
		HandleSMTPSubmit: function (e) {
			e.preventDefault();
		
			var id = jQuery("#id").val();
			var i_port = jQuery("#i_port").val();
			var v_username = jQuery("#v_username").val();
			var v_password = jQuery("#v_password").val();
			var v_server = jQuery("#v_server").val();
			var i_tls = jQuery("#i_tls").val();
			var i_debug = jQuery("#i_debug").val();
		
			if (!i_port || !v_username || !v_password || !v_server || !i_tls || !i_debug) {
				alert("Please fill in all required fields!");
				return false;
			}
		
			if (!/^\d+$/.test(i_port)) {
				alert("Please enter a valid port with only numbers!");
				jQuery("#i_port").focus();
				return false;
			}
			if (!/^\d{1,3}$/.test(i_tls)) {
				alert("Please enter a valid TLS!");
				jQuery("#i_tls").focus();
				return false;
			}
		
			if (!/^\d{1,3}$/.test(i_debug)) {
				alert("Please enter a valid DEBUG value!");
				jQuery("#i_debug").focus();
				return false;
			}
		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': id,
					'i_port': i_port,
					'v_username': v_username,
					'v_password': v_password,
					'v_server': v_server,
					'i_tls': i_tls,
					'i_debug': i_debug,
					'action': 'update_smtp'
				},
				success: function (response) {
					if (typeof response !== "object") {
						try {
							response = JSON.parse(response);
						} catch (e) {
							console.error('Error parsing JSON response:', e);
							jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error parsing JSON response</div>');
							return;
						}
					}
		
					if (response.status === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">SMTP Settings Updated Successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_imap_smtp');
							window.location.href = "admin_index.php?action=view_imap_smtp&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response.message + '</div>');
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					console.error("AJAX Error: " + textStatus, errorThrown);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: Internal Server Error</div>');
				}
			});
		},
		
		HandleIMAPSubmit(e) {
			e.preventDefault();
		
			var id = jQuery("#id").val();
			var v_connectionname = jQuery("#v_connectionname").val();
			var v_ipaddress = jQuery("#v_ipaddress").val();
			var v_username = jQuery("#v_username").val();
			var v_password = jQuery("#v_pasowrd").val(); // Ensure this matches the PHP variable name
			var v_type = jQuery("#v_type").val();
			var v_client_id = jQuery("#v_client_id").val();
			var v_client_secret = jQuery("#v_client_secret").val();
			var v_tenant = jQuery("#v_tenant").val();
		
			if (v_connectionname === '') {
				alert("Please enter Connection Name");
				return false;
			}
		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': id,
					'v_connectionname': v_connectionname,
					'v_ipaddress': v_ipaddress,
					'v_username': v_username,
					'v_pasowrd': v_password, // Ensure this matches the PHP variable name
					'v_type': v_type,
					'v_client_id': v_client_id,
					'v_client_secret': v_client_secret,
					'v_tenant': v_tenant,
					'action': 'update_imap'
				},
				success: function(response) {
					if (typeof response !== "object") {
						try {
							response = JSON.parse(response);
						} catch (e) {
							console.error('Error parsing JSON response:', e);
							jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error parsing JSON response</div>');
							return;
						}
					}
		
					if (response.status === 'success') {
						console.log('Update successful');
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">IMAP Settings Update successful</div>');
						setTimeout(function() {
							var encodedToken = btoa('view_imap_smtp');
							window.location.href = "admin_index.php?action=view_village&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						console.error('Update failed. Server returned:', response.message);
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Update failed: ' + response.message + '</div>');
					}
				},
				error: function(xhr, status, error) {
					console.error('Ajax request failed:', status, error);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Ajax request failed</div>');
				}
			});
		},
		
		HandleDispositionSubmit: function(e){
			e.preventDefault();
		
			var id = $("#id").val();
			var disposition = $("#disposition").val();
			if (disposition  === '') {
				alert('Please enter Disposition.');
				return; // Stop further execution
			}
			// var DispoRegex = /^[a-zA-Z\s]+$/;

			// if (!DispoRegex.test(disposition)) {
			// 	alert('Please enter valid Disposition');
			// 	return;
			// }

			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'id': id,
					'disposition': disposition,
					'action': (id !== '') ? 'update_disposition' : 'submit_disposition'
				},
				success: function(response) {
					if (response.trim().toLowerCase() === 'success') {
						console.log('Update successful');
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Updated successful</div>');
						setTimeout(function() {
							var encodedToken = btoa('view_disposition');
							window.location.href = "admin_index.php?action=view_disposition&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						console.error('Update failed. Unexpected response:', response);
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Unexpected response from the server</div>');
					}
				},
				error: function(xhr, status, error) {
					console.error('Ajax request failed:', status, error);
					jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Ajax request failed</div>');
				}
			});
		
			return false; 
		},
		HandleCallbacksSubmit: function (e) {
			e.preventDefault();

			var id = jQuery("#id").val();
			var callback_time = jQuery("#callback_time").val();
			var callback_alert_hour = jQuery("#callback_alert_hour").val();
			var callback_alert_minute = jQuery("#callback_alert_minute").val();
			var callback_remark = jQuery("#callback_remark").val();
			var reassignCallback = jQuery("#reassignCallback").val();
			console.log(callback_alert_hour);

		
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: { 'id': id, 'callback_alert_minute':callback_alert_minute ,'callback_alert_hour':callback_alert_hour ,'callback_remark':callback_remark ,'callback_time':callback_time ,'reassignCallback':reassignCallback, 'action': 'submit_callbacks' },
				success: function (response) {
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success alert-dismissible" role="alert">Callback Time Updated successfully</div>');
						setTimeout(function () {
							var encodedToken = btoa('view_callbacks');
							window.location.href = "admin_index.php?action=view_province&token=" + encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html('<div class="alert alert-danger alert-dismissible" role="alert">Error: ' + response + '</div>');
					}
				}
			});
		},
		validateForm: function (e) {
			var user = $('#user').val();
			var assignto = $('input[name="assignto[]"]:checked').length;
			
			
			if (user === '') {
				alert('Please select a user.');
				e.preventDefault(); 
				return;
			}
		
			if (assignto === 0) {
				alert('Please select Township');
				e.preventDefault(); 
				return;
			}
			$.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'user': user,
					'assignto': $('input[name="assignto[]"]:checked').map(function () {
						return this.value;
					}).get(),
					'action': 'assignProjectsToUser'
				},
				success: function (response) {
					location.reload(); 
				},
				error: function () {
					alert('An error occurred during the request.');
				}
			});
		},

		
		HandleSignature: function (e) {
			e.preventDefault(); // stop normal submit

			console.log("HandleSignature triggered");

const sign = window.quill.root.innerHTML.trim();
			const fileInput = document.getElementById("signature_image");
			const action = 'update_sign';

			if (sign === '') {
				alert('Please enter the signature');
				return;
			}

			// --- File validation (optional image) ---
			if (fileInput.files.length > 0) {
				const file = fileInput.files[0];
				const allowedTypes = ['image/jpeg', 'image/png'];

				if (!allowedTypes.includes(file.type)) {
					alert('Only JPG, JPEG and PNG files are allowed');
					fileInput.value = '';
					return;
				}
			}

			// --- FormData (REQUIRED for file upload) ---
			const formData = new FormData();
			formData.append('action', action);
			formData.append('sign', sign);

			if (fileInput.files.length > 0) {
				formData.append('signature_image', fileInput.files[0]);
			}

			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: formData,
				processData: false,   // 🔴 REQUIRED
				contentType: false,   // 🔴 REQUIRED
				success: function (response) {
					console.log("Server response:", response);

					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html(
							'<div class="alert alert-success">Signature updated successfully</div>'
						);

						setTimeout(function () {
							const encodedToken = btoa('mail_sign');
							window.location.href =
								"admin_index.php?action=view_mail_sign&token=" +
								encodeURIComponent(encodedToken);
						}, 2000);
					} else {
						jQuery('#success').html(
							'<div class="alert alert-danger">Error: ' + response + '</div>'
						);
					}
				},
				error: function (xhr, status, error) {
					console.error("AJAX error:", status, error);
					jQuery('#success').html(
						'<div class="alert alert-danger">AJAX request failed</div>'
					);
				}
			});
		},

		HandleAdhocMail(e){
			e.preventDefault();

			let email1 = jQuery("#emailadhoc1").val().trim();
			let email2 = jQuery("#emailadhoc2").val().trim();

			let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

			// Reset previous error states
			jQuery("#emailadhoc1, #emailadhoc2").removeClass("is-invalid");

			// ❌ Email 1 required
			if (!email1) {
				jQuery("#emailadhoc1").addClass("is-invalid");
				jQuery('#success').html('<div class="alert alert-danger">Adhoc Email 1 is required</div>');
				return;
			}

			// ❌ Email 1 invalid format
			if (!emailRegex.test(email1)) {
				jQuery("#emailadhoc1").addClass("is-invalid");
				jQuery('#success').html('<div class="alert alert-danger">Invalid Email 1 format</div>');
				return;
			}

			// ❌ Email 2 invalid (only if filled)
			if (email2 && !emailRegex.test(email2)) {
				jQuery("#emailadhoc2").addClass("is-invalid");
				jQuery('#success').html('<div class="alert alert-danger">Invalid Email 2 format</div>');
				return;
			}

			// ✅ If all valid → continue AJAX
			jQuery.ajax({
				method: 'POST',
				url: 'admin/web_admin_function.php',
				data: {
					'emailadhoc1': email1,
					'emailadhoc2': email2,
					'action': 'Submit_emailadhoc'
				},
				success: function(response) {
					if (response.trim().toLowerCase() === 'success') {
						jQuery('#success').html('<div class="alert alert-success">Updated Successfully</div>');
					} else {
						jQuery('#success').html('<div class="alert alert-danger">Error: ' + response + '</div>');
					}
				}
			});
		}
	}
	jQuery("#emailadhoc1, #emailadhoc2").on("input", function () {
		jQuery(this).removeClass("is-invalid");
	});
	$(document).ready(function () {
		$('#showButton').click(function () {
		   var user = $('#user').val();
	 
		   if (user === '') {
			  alert('Please select a user');
		   }
		});
		
		$("#emailadhoc1, #emailadhoc2").prop('disabled', true);
		$("#submitadhoc").prop('disabled', true);

		$("#editadhoc").on("click", function () {
			$("#emailadhoc1, #emailadhoc2").prop('disabled', false);
			$("#submitadhoc").prop('disabled', false);
		});

	 });
	 
	 Admin.init();
});