/*==========================
# Create User Query
============================*/
$(document).ready(function(){
	$('#createUserBtn').click(function (e){
		e.preventDefault();
		var form = $('#createUserForm')[0];
		var firstname = $('#userFirstName').val();
		var lastname = $('#userLastName').val();
		var middlename = $('#userMiddleName').val();
		var phone = $('#userPhone').val();
		var email = $('#userEmail').val();
		var profilePic = $('#userProfilePic')[0].files[0];
		var role = $('#userRole').val();

		var formData = new FormData();
		formData.append('firstname', firstname);
		formData.append('lastname', lastname);
		formData.append('middlename', middlename);
		formData.append('phone', phone);
		formData.append('email', email);
		formData.append('profilePic', profilePic);
		formData.append('role', role);
		formData.append('action', 'create_user');

		if (!form.checkValidity()) {
            form.classList.add('was-validated');
			return;
        }
        $('#createUserBtn').prop('disabled', true).text('Processing...');
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: formData,
			contentType: false,
			processData: false,
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "User created successfully.",
						icon: "success"
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					}).then(() => {
						$('#createUserBtn').prop('disabled', false).text('Create User');
					})
				}
			}
		});
	});
});
/*==========================
#Edit Staff Query
===========================*/
$(document).ready(function(){
	$('[id^=editauthModalbtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var User_id = $('#User_id_' + index).val();
		var firstname = $('#yourFirstName_' + index).val();
		var lastname = $('#yourLastName_' + index).val();
		var middlename = $('#yourMiddlename_' + index).val();
		var phone = $('#phonenumber_' + index).val();
		var email = $('#yourEmail_' + index).val();
		var preview = $('#pre_preview_' + index).val();
		var profilePic = $('#yourProfilePic_' + index)[0].files[0];

		var formData = new FormData();
		formData.append('User_id', User_id);
		formData.append('firstname', firstname);
		formData.append('lastname', lastname);
		formData.append('middlename', middlename);
		formData.append('phone', phone);
		formData.append('email', email);
		formData.append('preview', preview);
		formData.append('profilePic', profilePic);
		formData.append('action', 'edit_user');

		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: formData,
			contentType: false,
			processData: false,
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Staff Edition successfully.",
						icon: "success"
					})
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
#Updated User Query
===========================*/
$(document).ready(function(){
	$('#Update_Profile').click(function (e){
		e.preventDefault();

		var formData = new FormData();
		formData.append('User_id', $('#user_id').val());
		formData.append('firstname', $('#first_name').val());
		formData.append('lastname', $('#last_name').val());
		formData.append('middlename', $('#middle_name').val());
		formData.append('phone', $('#phoneNumber').val());
		formData.append('email', $('#email').val());
		formData.append('dob', $('#dateOfBirth').val());
		formData.append('gender', $('#gender').val());
		formData.append('address', $('#address').val());
		formData.append('bio', $('#bio').val());
		formData.append('preview', $('#pre_profile').val());
		formData.append('profilePic', $('#userProfilePicInput')[0].files[0]);
		formData.append('action', 'Update_Profile');

		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: formData,
			contentType: false,
			processData: false,
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Profile Updated successfully.",
						icon: "success"
					})
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Log In Query
===========================*/
$(document).ready(function(){
	$('#auth_sign_in').click(function (e){
		e.preventDefault();
		username = $('#Username').val();
		password = $('#Password').val();
		$('#auth_sign_in').prop('disabled', true).text('loading ...');
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: { username: username, password: password, action: 'Authorize_signin' },
			success: function(response) {
				if(response == 1){ 
					Swal.fire({
						title: "login Successful",
						icon: "success"
					}).then(() => { 
						window.location.href = 'index.php';
					});
				} else if(response == 2){
					Swal.fire({
						title: "Login Successful",
						icon: "success"
					}).then(() => { 
						window.location.href = 'index.php';
					});
				} else if(response == 3){
					Swal.fire({
						title: "Login Successful",
						icon: "success"
					}).then(() => { 
						window.location.href = 'index.php';
					});
				} else if(response == 4){
					Swal.fire({
						title: "Login Successful",
						icon: "success"
					}).then(() => { 
						window.location.href = 'index.php';
					});
				} else if(response == 5){
					Swal.fire({
						title: "Login Successful",
						icon: "success"
					}).then(() => { 
						window.location.href = 'customer/index.php';
					});
				} else if(response == 0){
					Swal.fire({
						title: "Login Successful",
						icon: "success"
					}).then(() => { 
						window.location.href = 'sup_admin/index.php';
					});
				} else if (response == "BLOCKED") {
		            Swal.fire({
		                icon: 'error',
		                title: 'Account Deactivated',
		                text: 'Your account has been suspended by the administrator. Please contact support.',
		                footer: '<a href="mailto:admin@yourcompany.com">Contact Admin</a>'
		            }); 
		        } else {
					Swal.fire({
						title: "Login Failed",
						text: response,
						icon: "error"
					}).then(() => {
						$('#auth_sign_in').prop('disabled', false).text('Submit');						
					});
				}
			}
		});
	});
});
/*==========================
# Admin Reset user password Query
===========================*/
$(document).ready(function(){
	$('[id^=ResetUserpass_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var user_id = index;
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: { user_id: user_id, action: 'Authorize_Reset_user_pass' },
			success: function(response) {
				if(response == 1){ 
					Swal.fire({
						title: "Updated Successful",
						icon: "success"
					}).then(() => { 
						location.reload();
					});
				}  else {
					Swal.fire({
						title: "Login Failed",
						text: response,
						icon: "error"
					});
				}
			}
		});
	});
});
/*--------------------------
# Forget Password Query
---------------------------*/
$(document).ready(function(){
	let email;
	$('#ResetPassword').click(function(e){
		e.preventDefault;
		email = $('#req-email').val();
		$('#ResetPassword').prop('disabled', true).text('Sending...');
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: { action: 'reset_password', email: email },
			success: function(response) {
				$('#ResetPasswordx').prop('disabled', false).text('Send Code');
				if (response.includes("sent")) {
            $('#step-request').fadeOut(300, function() { $('#step-verify').fadeIn(); });
        } else {
            swal("Error", response, "error");
        }
			}
		});
	});
// HANDLING STEP 2: VERIFY
    $('#btn-verify').on('click', function(e) {
        e.preventDefault();
        let otp = $('#verify-otp').val();
        $('#btn-verify').prop('disabled', true).text('Verifying...');

        $.post('inc/code_query.php', { action: 'verify_otp', email: email, otp: otp }, function(res) {
            $('#btn-verify').prop('disabled', false).text('Verify Code');
            if (res.includes("Success")) {
                $('#step-verify').fadeOut(300, function() { $('#step-reset').fadeIn(); });
            } else {
                Swal.fire("Error", res, "error");
            }
        });
    });

    // HANDLING STEP 3: RESET
    $('#btn-reset').on('click', function(e) {
        e.preventDefault();
        let pass = $('#new-pass').val();
        let confirm = $('#confirm-pass').val();

        if (pass !== confirm) { return Swal.fire("Error", "Passwords do not match", "error"); }

        $('#btn-reset').prop('disabled', true).text('Updating...');
        $.post('inc/code_query.php', { 
            action: 'update_password', 
            email: email, 
            password: pass, 
            confirm_password: confirm 
        }, function(res) {
            if (res.includes("successfully")) {
                Swal.fire("Success", "Password updated! Redirecting to login...", "success").then(() => {
                    window.location.href = "auth-login.html";
                });
            } else {
                $('#btn-reset').prop('disabled', false).text('Update Password');
                Swal.fire("Error", res, "error");
            }
        });
    });
});


$('#btnUpdatePass').on('click', function(e) {
    e.preventDefault();

    const email = $('#security-email').val();
    const currPass = $('#current_password').val();
    const newPass = $('#new_password').val();
    const confirmPass = $('#confirm_new_password').val();
    const btn = $('#btnUpdatePass');

    if (newPass !== confirmPass) {
        return Swal.fire("Error", "New passwords do not match!", "error");
    }

    btn.prop('disabled', true).text('Processing...');

    $.ajax({
        url: 'inc/code_query.php',
        type: 'POST',
        data: {
            action: 'change_password_logged_in', // Reusing your existing PHP action
            email: email,
            currPass: currPass,
            confirm_password: confirmPass
        },
        success: function(response) {
            btn.prop('disabled', false).html('<i class="bi bi-check-circle"></i> Update Password');
            
            if (response.includes("successfully")) {
                Swal.fire("Success", "Password updated successfully!", "success");
                $('#changePasswordForm')[0].reset();
            } else {
                Swal.fire("Error", response, "error");
            }
        }
    });
});

/*==========================
# Log Out Query
===========================*/
$(document).ready(function(){
	$('#authorize_sign_out').click(function (e){
		e.preventDefault();
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: { action: 'authorize_sign_out' },
			success: function(response) {
				Swal.fire({
				title: "Logout",
				icon: "success"
				}).then(() => {
					window.location.href = 'auth-login.html';
				});			
			}
		});
	});
});

/*==========================
# Preview Profile Picture Before Upload
===========================*/
const userProfilePicInput = document.getElementById('userProfilePic');
const previewImage = document.getElementById('preview');
if (userProfilePicInput) {
  userProfilePicInput.addEventListener('change', function() {
    const file = this.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(e) {
        previewImage.src = e.target.result;
        previewImage.style.display = 'block';
      };
      reader.readAsDataURL(file);
    }
  });
}

/*==========================
# Create Driver Query
===========================*/
$(document).ready(function(){
    $('#createDriverBtn').click(function (e){
        e.preventDefault();
        
        var form = $('#createDriverForm')[0];
        var formData = new FormData(form);

        // SAFE CHECK: Only try to access files if the element exists
        var profilePicInput = $('#DriverProfilePic')[0];
        var driverDocInput = $('#DriverDoc')[0];

        if (profilePicInput && profilePicInput.files.length > 0) {
            formData.append('profilePic', profilePicInput.files[0]);
        }

        if (driverDocInput && driverDocInput.files.length > 0) {
            formData.append('driverDoc', driverDocInput.files[0]);
        }
        
        // Manually append the action and role
        formData.append('action', 'create_Driver'); 

        $.ajax({
            type: "POST",
            url: "inc/code_query.php",
            data: formData,
            contentType: false, // Required for file uploads
            processData: false, // Required for file uploads
            beforeSend: function() {
                // Optional: Disable button to prevent double clicks
                $('#createDriverBtn').prop('disabled', true).text('Processing...');
            },
            success: function(response) {
                if(response == 1) {
                    Swal.fire({
                        title: "Success",
                        text: "Driver created and invitation sent successfully.",
                        icon: "success"
                    }).then(() => {
                        form.reset(); 
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: "Error",
                        text: response,
                        icon: "error"
                    });
                    $('#createDriverBtn').prop('disabled', false).text('New Driver');
                }
            }
        });
    });
});
/*==========================
# Edit Driver Query
===========================*/
$(document).on('click', '.editBtndriver', function() {
    var count = $(this).data('count');
    var form = $('#editDriverForm_' + count)[0];
    var formData = new FormData(form);
    formData.append('action', 'edit_driver'); 

    $.ajax({
        type: "POST",
        url: "inc/code_query.php",
        data: formData,
        contentType: false,
        processData: false,
        success: function(response) {
            if(response == 1) {
                Swal.fire("Updated!", "Driver record has been updated.", "success")
                .then(() => location.reload());
            } else {
                Swal.fire("Error", response, "error");
            }
        }
    });
});
/*==========================
# Add Truck Record Query
===========================*/
$(document).ready(function(){
	$('#addtruckrecordBtn').click(function (e){
		e.preventDefault();
		var formData = new FormData();
		formData.append('license_plate',  $('#truck_license_column').val());
		formData.append('make', $('#make-column').val());
		formData.append('model', $('#model-column').val());
		formData.append('year', $('#year-column').val());
		formData.append('vin', $('#vin-column').val());
		formData.append('registration_start', $('#registration-column').val());
		formData.append('registration_end', $('#registration-end-column').val());
		formData.append('driver_id', $('#driver-colum').val());
		formData.append('action', 'Truck_record');
    	$('#addtruckrecordBtn').prop('disabled', true).text('Processing...');
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: formData,
			contentType: false,
			processData: false,
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Truck Record successfully.",
						icon: "success"
					}).then(() => { 
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					}).then (() => {
						$('#addtruckrecordBtn').prop('disabled', false).text('Submit');
					})
				}
			}
		});
	});
});
/*==========================
# Edit Truck Record Query
===========================*/
$(document).ready(function(){
	$('[id^=edittruckModalbtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var truck_id = $('#truck_id_' + index).val();
		var license_plate = $('#license_plate_' + index).val();
		var make = $('#make_' + index).val();
		var model = $('#model_' + index).val();
		var year = $('#year_' + index).val();
		var vin = $('#vin_' + index).val();
		var registration_start = $('#registration_column_' + index).val();
		var registration_end = $('#registration_end_' + index).val();
		var driver_id = $('#driver_id_' + index).val();
		var current_status = $('#current_status_' + index).val();
		var action = 'edit_truck_record';

		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {truck_id : truck_id, license_plate : license_plate, registration_start: registration_start, registration_end: registration_end, make : make, model : model, year : year, vin : vin, driver_id : driver_id, current_status : current_status, action : action},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Truck Record Edited successfully.",
						icon: "success"

					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Add Customer Record Query
===========================*/
$(document).ready(function(){
	$('#create_CustomerBtn').click(function (e){
		e.preventDefault();
		var formData = new FormData();
		formData.append('name',  $('#name-column').val());
		formData.append('phone', $('#phone-column').val());
		formData.append('email', $('#email-column').val());
		formData.append('address', $('#address-column').val());
		formData.append('action', 'customer_record');
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: formData,
			contentType: false,
			processData: false,
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Customer Record successfully.",
						icon: "success"
					}).then(() => {
						$('#truck_form')[0].reset(); 
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					}).then (() => {
						location.reload();
					})
				}
			}
		});
	});
});
/*==========================
# Edit Customer Record Query
===========================*/
$(document).ready(function(){
	$('[id^=editcustomerModalbtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var customer_id = $('#customer_id_' + index).val();
		var name = $('#customerName_' + index).val();
		var phone = $('#phonenumber_' + index).val();
		var email = $('#customerEmail_' + index).val();
		var address = $('#customeraddress_' + index).val();
		var action = 'edit_customer_record';
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {customer_id : customer_id, name : name, phone : phone, email : email, address : address, action : action},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Customer Record Edited successfully.",
						icon: "success"	
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Add Maintenance Record Query
===========================*/
$(document).ready(function(){
	$('#create_MaintenceBtn').click(function (e){
		e.preventDefault();
		var formData = new FormData();
		formData.append('truck_license',  $('#truck_license').val());
		formData.append('Maintence_type', $('#Maintence_type').val());
		formData.append('cost', $('#cost').val());
		formData.append('datecarryout', $('#datecarryout').val());
		formData.append('vendor_id', $('#vendor_id').val())
		formData.append('Description', $('#Description').val());
		formData.append('action', 'maintence_record');
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: formData,
			contentType: false,
			processData: false,
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Maintenance Record successfully.",
						icon: "success"
					}).then(() => {
						$('#truck_form')[0].reset(); 
						window.location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Edit Maintenance Record Query
===========================*/
$(document).ready(function(){
	$('[id^=editmaintenceModalbtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var maintence_id = $('#Maintence_id_' + index).val();
		var truck_license = $('#trucklicense_' + index).val();
		var Maintence_type = $('#Maintence_type_' + index).val();
		var cost = $('#cost_' + index).val();
		var datecarryout = $('#datecarryout_' + index).val();
		var Description = $('#Description_' + index).val();
		var vendor_id = $('#vendor_id_' + index).val()
		var action = 'edit_maintence_record';
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {maintence_id : maintence_id, vendor_id:vendor_id, truck_license : truck_license, Maintence_type : Maintence_type, cost : cost, datecarryout : datecarryout, Description : Description, action : action},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Maintenance Record Edited successfully.",
						icon: "success"
					}).then(() => {
						window.location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Add ATC Record Query
===========================*/
$(document).ready(function(){
	$('#add_atc_recordBtn').click(function (e){
		e.preventDefault();
		var atc_num = $('#atc_no_column').val();
		var volume = $('#volume-column').val();
		var type = $('#type-column').val();
		var action = 'atc_record';
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {atc_num : atc_num, volume : volume, type: type, action : action}, 
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "ATC Record successfully.",
						icon: "success"
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					}).then (() => {
						$('#atc_form')[0].reset(); 
					})
				}
			}
		});
	});
});
/*==========================
# Edit ATC Record Query
===========================*/
$(document).ready(function(){
	$('[id^=editatcModalbtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var atc_id = $('#atc_id_' + index).val();
		var atc_num = $('#atc_num_' + index).val();
		var volume = $('#volume_' + index).val();
		var type = $('#type_' + index).val();
		var action = 'edit_atc_record';
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {atc_id : atc_id, atc_num : atc_num, type: type, volume : volume, action : action},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "ATC Record Edited successfully.",
						icon: "success"
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}	
			}

		});
	});
});
/*==========================
# Create Trip Query
===========================*/
$(document).ready(function(){
	$('#createTripFormBtn').click(function (e){
		e.preventDefault();
		var atc_id = $('#atc-colum').val();
		var unit = $('#unit-column').val();
		var selling = $('#sell-column').val();
		var cost = $('#cost-column').val();
		var allowance = $('#allowance-column').val();
		var customer_id = $('#customer-colum').val();
		var location = $('#location-column').val();
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: { allowance: allowance, unit: unit, selling: selling, cost: cost, atc_id: atc_id, customer_id: customer_id, location: location, 'action': 'createTrip'},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Trip created successfully!",
						icon: "success"
					}).then(() => {
						window.location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Create Trip by order Query
===========================*/
$(document).ready(function(){
	$('[id^=o-dispatch_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var order_id = $('#order_id_' + index).val();
		var atc_id = $('#atc-colum_' + index).val();
		var unit = $('#unit_' + index).val();
		var selling = $('#cost_price_' + index).val();
		var cost = $('#selling_price_' + index).val();
		var allowance = $('#driver_allowance_' + index).val();
		var customer_id = $('#customer-colum_' + index).val();
		var location = $('#location-column_' + index).val();
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: { allowance: allowance, order_id: order_id, unit: unit, selling: selling, cost: cost, atc_id: atc_id, customer_id: customer_id, location: location, 'action': 'createTrip'},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Trip created successfully!",
						icon: "success"
					}).then(() => {
						window.location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Edit Trip Query
===========================*/
$(document).ready(function() {
	$('[id^=edittripModalbtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var trip_id = $('#trip_id_' + index).val();
		var unit = $('#unit_' + index).val();
		var order_id = $('order_id_' + index).val();
		var selling = $('#sell_' + index).val();
		var cost = $('#cost_' + index).val();
		var allowance = $('#allowance_' + index).val();
		var atc_id = $('#atc_colum_' + index).val();
		var customer_id = $('#customer_colum_' + index).val();
		var location = $('#location_column_' + index).val();
		var action = 'editTrip';

		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {trip_id : trip_id, order_id: order_id, customer_id : customer_id, unit : unit, cost : cost, selling : selling, location : location, action : action, allowance : allowance, atc_id : atc_id},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Trip Edited successfully.",
						icon: "success"
					}).then(() => {
						window.location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});	
/*==========================
# Complete Trip Query
===========================*/
$(document).ready(function(){
	$('[id^=completeTripBtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var trip_id = $('#trip_id_' + index).val();
		var action = 'completeTrip';
		
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {trip_id : trip_id, action : action},	
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Trip Completed successfully.",
						icon: "success"
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# Cancel Trip Query
===========================*/
$(document).ready(function(){
	$('[id^=cancelTripBtn_]').click(function (e){
		e.preventDefault();
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var trip_id = $('#trip_id_' + index).val();
		var action = 'cancelTrip';
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {trip_id : trip_id, action : action},	
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Trip Canceled successfully.",
						icon: "success"
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});

/*==========================
# User Role Access control Management
===========================*/
$(document).ready(function(){
	$('[id^=saveUserRoleAccessBtn_]').click(function (){
		var buttonId = $(this).attr('id');
		var index = buttonId.split('_').pop();
		var user_id = $('#user_id_' + index).val();
		var pages = [];
		$('input[id="pages_' + index + '"]:checked').each(function() {
			pages.push($(this).val());
		});
		var action = 'update_user_access';
		console.log(pages);
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {user_id : user_id, pages : pages, action : action},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						title: "Success",
						text: "Role Access Updated successfully.",
						icon: "success"
					}).then(() => {
						location.reload();
					});
				} else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
});
/*==========================
# User Role Access control Management insertion
===========================*/
$(document).ready(function(){
	$('#createUserRoleAccessBtn').click(function (e){
		e.preventDefault();
		var user_id = $('#user_id').val();
		var pages = [];
		$('input[name="pages[]"] ').each(function() {
			pages.push($(this).val());
		}
		);
		var action = 'create_user_access';
		alert(pages);
		$.ajax({
			type: "POST",
			url: "inc/code_query.php",
			data: {user_id : user_id, pages : pages, action : action},
			success: function(response) {
				if(response == 1) {
					Swal.fire({
						icon: "success",
						title: "Success",
						text: "Role Access Created successfully."
					}).then(() => {
						location.reload();
					});
				}
				else {
					Swal.fire({
						title: "Error",
						text: response,
						icon: "error"
					})
				}
			}
		});
	});
}); 


$('#updateAssignmentForm').on('submit', function(e) {
    e.preventDefault();

    // Get values
    let liters = parseFloat($('#edit_liters_filled').val()) || 0;
    let costPerLiter = parseFloat($('#edit_cost_per_liter').val()) || 0;
    let station = $('#edit_filling_station').val().trim();

    // VALIDATION LOGIC
    if (liters <= 0) {
        Swal.fire('Invalid Data', 'Liters filled must be greater than zero.', 'error');
        return false;
    }
    if (costPerLiter <= 0) {
        Swal.fire('Invalid Data', 'Please provide a valid cost per liter.', 'error');
        return false;
    }
    if (station === "") {
        Swal.fire('Missing Detail', 'Please enter the Filling Station name.', 'error');
        return false;
    }

    // If validation passes, proceed with AJAX
    $.post('inc/code_query.php', $(this).serialize() + '&action=updateFullAssignment', function(res) {
        if(res == 1) {
            Swal.fire('Success', 'Trip assignment and fuel updated!', 'success');
            location.reload();
        } else {
            Swal.fire('Error', res, 'error');
        }
    });
});

$(document).on('click', '.status-toggle-btn', function() {
    var logId = $(this).data('id');
    var userid = $(this).data('userid');
    var status = $(this).data('status');
    var actionText = (status == 1) ? "Deactivate" : "Activate";

    Swal.fire({
        title: 'Are you sure?',
        text: "Do you want to " + actionText + " this user?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: status == 1 ? '#d33' : '#28a745',
        confirmButtonText: 'Yes, ' + actionText + ' it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'inc/code_query.php',
                type: 'POST',
                data: {
                    action: 'toggle_user_status',
                    log_id: logId,
                    user_id: userid,
                    current_status: status
                },
                success: function(res) {
                    if (res == 1) {
                        Swal.fire('Updated!', 'User status has been changed.', 'success')
                        .then(() => location.reload());
                    } else {
                        Swal.fire('Error', res, 'error');
                    }
                }
            });
        }
    });
});


$(document).on('click', '.toggle-all-sessions', function() {
    var userId = $(this).data('userid');
    var status = $(this).data('currentstatus');
    var newStatus = (status == 0) ? 2 : 0;
    var msg = (status == 0) ? "This will log the user out of ALL devices and roles. Continue?" : "Reactivate all roles for this user?";

    Swal.fire({
        title: 'Are you sure?',
        text: msg,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: status == 0 ? '#d33' : '#28a745',
        confirmButtonText: 'Yes, proceed'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'inc/code_query.php',
                type: 'POST',
                data: {
                    action: 'global_status_update',
                    user_id: userId,
                    target_status: newStatus
                },
                success: function(res) {
                    if (res == 1) {
                        location.reload();
                    } else {
                        Swal.fire('Error', res, 'error');
                    }
                }
            });
        }
    });
});

$(document).on('click', '.customer-toggle-btn', function() {
    let btn = $(this);
    let logId = btn.data('logid');
    let userId = btn.data('userid');
    let currentStatus = btn.data('status');
    
    // Toggle: if 1, make it 0. If 0, make it 1.
    let newStatus = (currentStatus == 1) ? 0 : 1;
    let actionText = (currentStatus == 1) ? 'Deactivate' : 'Activate';

    Swal.fire({
        title: 'Are you sure?',
        text: "You are about to " + actionText + " this customer account.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: (currentStatus == 1) ? '#ffc107' : '#28a745',
        confirmButtonText: 'Yes, ' + actionText + '!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'inc/code_query.php',
                type: 'POST',
                data: {
                    action: 'toggle_customer_status',
                    log_id: logId,
                    user_id: userId,
                    status: newStatus
                },
                success: function(response) {
                    if(response == 1) {
                        Swal.fire('Success!', 'Account status updated.', 'success')
                        .then(() => location.reload());
                    } else {
                        Swal.fire('Error', 'Update failed: ' + response, 'error');
                    }
                }
            });
        }
    });
});

$('[id^=update_finance_]').on('click', function(e) {
    e.preventDefault(); 
    
    // 1. Get the index (the number at the end of the ID)
    var buttonId = $(this).attr('id');
    var index = buttonId.split('_').pop();
    
    // 2. Target the form using the index (Added the # for ID)
    var trip_id = $('#trip_id_' + index).val();
    var haulage_amount = $('#haulage_rate_' + index).val(); 
    var promo_amount = $('#promo_amount_' + index).val();
    var incentive_amount = $('#incentive_amount_' + index).val();

    // 5. Execute Ajax
    $.ajax({
        url: 'inc/code_query.php',
        type: 'POST',
        data:{trip_id : trip_id, haulage_amount : haulage_amount, promo_amount : promo_amount, incentive_amount : incentive_amount, action : 'update_finance'},
        beforeSend: function() {
            $('#update_finance_' + index).prop('disabled', true).text('Processing...');
        },
        success: function(response) {
	        if(response == 1) {
                Swal.fire('Success!', 'Rates updated successfully!', 'success')
                .then(() => location.reload());
            } else {
                Swal.fire('Error', 'Update failed: ' + response, 'error');
            }
        },
        error: function() {
        	Swal.fire('Error', 'Something went wrong. Please try again.', 'error');
            $('#update_finance_' + index).prop('disabled', false).text('Apply & Save');
        }
    });
});

function executeResend() {
    // 1. Get values from the modal inputs
    const logId = $('#resend_log_id').val();
    const emailAddr = $('#resend_email_input').val();
    
    // basic validation
    if(emailAddr === "") {
        Swal.fire("Error","Please enter a valid email.", "error");
        return;
    }

    // 2. AJAX Request
    $.ajax({
        url: 'inc/code_query.php', // point to your logic file
        type: 'POST',
        data: {
            action: 'resend_invite',
            log_id: logId,
            email: emailAddr
        },
        beforeSend: function() {
            // Disable button to prevent double-clicking
            $('.btn-resend-action').prop('disabled', true).text('Sending...');
        },
        success: function(response) {
            if(response == 1) {
                Swal.fire("Success","Successful! A new invitation has been sent to " + emailAddr, "success");
                $('#resendModal').modal('hide');
            } else {
            	$('.btn-resend-action').prop('disabled', true).text('Update & Resend Now');
                Swal.fire("Error","Error: " + response, "error");

            }
        },
        error: function() {
            Swal.fire("Error","System error. Could not reach the server.", "error");
        },
        complete: function() {
            $('.btn-resend-action').prop('disabled', false).text('Update & Resend Now');
        }
    });
}




$(document).ready(function() {
    $('#btn-pay').on('click', function() {
        var maintenanceId = $(this).data('id');
        var button = $(this);
        var action = 'vendor_status';

        Swal.fire({
            title: 'Confirm Payment?',
            text: "Are you sure you want to mark this record as paid?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, mark as paid!'
        }).then((result) => {
            if (result.isConfirmed) {
                
                // Show a small "Processing" loader
                Swal.showLoading();

                $.ajax({
                    url: 'inc/code_query.php',
                    type: 'POST',
                    data: { id: maintenanceId, action: action},
                    success: function(response) {
                        if (response.trim() === 'success') {
                            // Success Toast Notification
                            Swal.fire({
                                icon: 'success',
                                title: 'Updated!',
                                text: 'The record has been marked as paid.',
                                timer: 2000,
                                showConfirmButton: false
                            }).then(() => {
                            	location.reload();
                            });
                        } else {
                            Swal.fire('Error!', 'Could not update the database.', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error!', 'Network error. Please try again.', 'error');
                    }
                });
            }
        });
    });
});


$(document).ready(function() {
	$(document).on('click', '.btn-submit-topup', function(e) {
	    e.preventDefault();
	    
	    var customerId = $(this).data('id');
	    var formData = $('#topupForm' + customerId).serialize();
	    var submitBtn = $(this);
	    var finalData = formData + '&action=topup';
	    // Disable button to prevent double clicks
	    submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Processing...');

	    $.ajax({
	        url: 'inc/code_query.php', // Create this file
	        type: 'POST',
	        data: finalData,
	        success: function(response) {
	            if (response.trim() === 'success') {
	                $('#topupModal' + customerId).modal('hide');
	                
	                Swal.fire({
	                    title: 'Successfully',
	                    text: 'Wallet updated successfully!',
	                    icon: 'success'
	                }).then(() => {
	                    location.reload(); 
	                });
	            } else {
	                Swal.fire('Error', response, 'error');
	                submitBtn.prop('disabled', false).text('Confirm Top-up');
	            }
	        },
	        error: function() {
	            Swal.fire('Error','Server error. Please try again.', 'error');
	            submitBtn.prop('disabled', false).text('Confirm Top-up');
	        }
	    });
	});
});


$(document).ready(function() {
    $(document).on('click', '.btn-submit-trip', function() {
        var formId = $(this).data('form-id');
        var form = $('#' + formId);
        var truckId = form.find("select.truck_license_plate").val();
        var formData = form.serialize();
	    formData += '&action=assign_truck';
        console.log(form);
        // Validate
        // if (!truckId || truckId === "" || truckId === "0") {
        //     Swal.fire('Required', 'Please select a truck to start the trip.', 'warning');
        //     return;
        // }

        $.ajax({
            url: 'inc/code_query.php', // Update this to your processing file
            type: 'POST',
            data: formData,
            success: function(response) {
                if (response.trim() === 'success') {
                    Swal.fire({
                        icon: 'success',
                        title: 'Trip Created!',
                        text: 'Truck and Driver are now dispatched.',
                        timer: 2000
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire('Error', response, 'error');
                }
            }
        });
    });
});


$(document).ready(function() {
    $(document).on('click', '.btn-submit-withdraw', function(e) {
        e.preventDefault();
        
        const $btn = $(this);
        const customerId = $btn.data('id');
        const formElement = $('#withdrawForm' + customerId);
        console.log(formElement.serialize() + '&action=withdrawal');
        Swal.fire({
            title: 'Confirm Withdrawal',
            text: 'Are you sure you want to process this transaction?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, Process it!',
            cancelButtonText: 'No, Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                
                // UI State Change
                $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

                Swal.fire({
                    title: 'Processing...',
                    didOpen: () => { Swal.showLoading(); },
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });

                $.ajax({
                    url: 'inc/code_query.php',
                    type: 'POST',
                    data: formElement.serialize() + '&action=withdrawal',
                    success: function(response) {
                        if (response.trim() === 'success') {
                            Swal.fire({
                                icon: 'success',
                                title: 'Success!',
                                text: 'Withdrawn successfully.',
                                timer: 1500,
                                showConfirmButton: false
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            $btn.prop('disabled', false).text('Try Again');
                            Swal.fire('Transaction Failed', response, 'error');
                        }
                    },
                    error: function() {
                        $btn.prop('disabled', false).text('Try Again');
                        Swal.fire('Server Error', 'Could not connect to the server.', 'error');
                    }
                });
            }
        });
    });
});















// 
