/*******************************************************************************
* Simplified PHP Invoice System                                                *
*                                                                              *
* Version: 1.1.1	                                                               *
* Author:  James Brandon                                    				   *
*******************************************************************************/
$(document).ready(function () {
    $('#response').hide();
});

// Close response
$(document).on('click', '.response-close', function () {
    $('#response').fadeOut(200);
});
setTimeout(function () {
    $('#response').fadeOut(500);
}, 5000);



$(document).ready(function() {

	// Invoice Type
	$('#invoice_type').change(function() {
		var invoiceType = $("#invoice_type option:selected").text();
		$(".invoice_type").text(invoiceType);
	});

	// Load dataTables
	$("#data-table").dataTable();

	// add product
	$("#action_add_product").click(function(e) {
		e.preventDefault();
	    actionAddProduct();
	});

	// add expense
	$("#action_add_expense").click(function(e) {
		e.preventDefault();
	    actionAddExpense();
	});

	// add schedule
	$("#action_add_schedule").click(function(e) {
		e.preventDefault();
	    actionAddSchedule();
	});	

	// password strength
	var options = {
        onLoad: function () {
            $('#messages').text('Start typing password');
        },
        onKeyUp: function (evt) {
            $(evt.target).pwstrength("outputErrorList");
        }
    };
    $('#password').pwstrength(options);

	// add user
	$("#action_add_user").click(function(e) {
		e.preventDefault();
	    actionAddUser();
	});

	// update customer
	$(document).on('click', "#action_update_user", function(e) {
		e.preventDefault();
		updateUser();
	});

	// update Expenses
	$(document).on('click', "#action_update_expense", function(e) {
		e.preventDefault();
		updateExpense();
	});

	// update Schedule
	$(document).on('click', "#action_update_schedule", function(e) {
		e.preventDefault();
		updateSchedule();
	});

	// delete user
	$(document).on('click', ".delete-user", function(e) {
        e.preventDefault();

        var userId = 'action=delete_user&delete='+ $(this).attr('data-user-id'); //build a post data structure
        var user = $(this);

	    $('#delete_user').modal({ backdrop: 'static', keyboard: false }).one('click', '#delete', function() {
			deleteUser(userId);
			$(user).closest('tr').remove();
        });
   	});

	// delete expenses
	$(document).on('click', ".delete-expense", function(e) {
        e.preventDefault();

        var userId = 'action=delete_expense&delete='+ $(this).attr('data-expense-id'); //build a post data structure
        var user = $(this);

	    $('#delete_expense').modal({ backdrop: 'static', keyboard: false }).one('click', '#delete', function() {
			deleteExpense(userId);
			$(user).closest('tr').remove();
        });
   	});

	// delete schedule
	$(document).on('click', ".delete-schedule", function(e) {
        e.preventDefault();

        var userId = 'action=delete_schedule&delete='+ $(this).attr('data-schedule-id'); //build a post data structure
        var user = $(this);

	    $('#delete_schedule').modal({ backdrop: 'static', keyboard: false }).one('click', '#delete', function() {
			deleteSchedule(userId);
			$(user).closest('tr').remove();
        });
   	});	

   	// delete customer
	$(document).on('click', ".delete-customer", function(e) {
        e.preventDefault();

        var userId = 'action=delete_customer&delete='+ $(this).attr('data-customer-id'); //build a post data structure
        var user = $(this);

	    $('#delete_customer').modal({ backdrop: 'static', keyboard: false }).one('click', '#delete', function() {
			deleteCustomer(userId);
			$(user).closest('tr').remove();
        });
   	});

	// update customer
	$(document).on('click', "#action_update_customer", function(e) {
		e.preventDefault();
		updateCustomer();
	});

	// update product
	$(document).on('click', "#action_update_product", function(e) {
		e.preventDefault();
		updateProduct();
	});

	// login form
	$(document).bind('keypress', function(e) {
		e.preventDefault;
		
        if(e.keyCode==13){
            $('#btn-login').trigger('click');
        }
    });

	$(document).on('click','#btn-login', function(e){
		e.preventDefault;
		actionLogin();
	});

	// download CSV
	$(document).on('click', ".download-csv", function(e) {
		e.preventDefault;

		var action = 'action=download_csv'; //build a post data structure
        downloadCSV(action);

	});

	// email invoice
	$(document).on('click', ".email-invoice", function(e) {
        e.preventDefault();

        var invoiceId = 'action=email_invoice&id='+$(this).attr('data-invoice-id')+'&email='+$(this).attr('data-email')+'&invoice_type='+$(this).attr('data-invoice-type')+'&custom_email='+$(this).attr('data-custom-email'); //build a post data structure
		emailInvoice(invoiceId);
   	});

	// delete invoice
	$(document).on('click', ".delete-invoice", function(e) {
        e.preventDefault();

        var invoiceId = 'action=delete_invoice&delete='+ $(this).attr('data-invoice-id'); //build a post data structure
        var invoice = $(this);

	    $('#delete_invoice').modal({ backdrop: 'static', keyboard: false }).one('click', '#delete', function() {
			deleteInvoice(invoiceId);
			$(invoice).closest('tr').remove();
        });
   	});


	//delete Voucher

	let deleteVoucherId = null;
let deleteRow = null;

$(document).on('click', '.delete-voucher', function (e) {
    e.preventDefault();

    deleteVoucherId = $(this).data('voucher-id');
    deleteRow = $(this).closest('tr');

    $('#delete_voucher').modal({
        backdrop: 'static',
        keyboard: false
    });
});


$('#confirm_delete').on('click', function () {

    if (!deleteVoucherId) return;

    deleteVoucher(deleteVoucherId, deleteRow);

    $('#delete_voucher').modal('hide');
});


	// delete product
	// delete product
$(document).on('click', '.delete-product', function (e) {
    e.preventDefault();

    let productId = $(this).data('product-id');
    let row = $(this).closest('tr');

    if (!productId) {
        alert('Invalid product selected');
        return;
    }

    // show correct modal
    $('#delete_product').modal('show');

    // ensure single click binding
    $('#delete').off('click').on('click', function () {

        $.ajax({
            url: 'response.php', 
            type: 'POST',
            dataType: 'json',
            data: {
                action: 'delete_product',
                delete: productId
            },
            success: function (response) {

                if (response.status === 'Success') {
                    row.fadeOut(300, function () {
                        $(this).remove();
                    });
                } else {
                    alert(response.message);
                }
            },
            error: function () {
                alert('Delete failed. Please try again.');
            }
        });

        // close modal
        $('#delete_product').modal('hide');
    });
});


// company settings create
$("#action_company_settings").click(function(e) {
	e.preventDefault();
	actionCompanySettings();
});

	// create customer
	$("#action_create_customer").click(function(e) {
		e.preventDefault();
	    actionCreateCustomer();
	});

	
//populate product
	$(document).on('click', ".item-select", function (e) {

    e.preventDefault();

    var product = $(this);

    $('#insert').modal({ backdrop: 'static', keyboard: false })
        .one('click', '#selected', function () {

            var selected  = $('#insert').find("option:selected");

            var itemText  = $.trim(selected.text());   // ✅ FIX
            var itemValue = selected.val();
            var itemDesc  = selected.data('desc');

            $(product).closest('tr').find('.invoice_product').val(itemText);
            $(product).closest('tr').find('.invoice_product_price').val(itemValue);
            $(product).closest('tr').find('.invoice_product_description').val(itemDesc);

            updateTotals('.calculate');
            calculateTotal();
        });

    return false;
});

   	

$(document).on('click', ".select-customer", function(e) {

   		e.preventDefault;

   		var customer = $(this);

   		$('#insert_customer').modal({ backdrop: 'static', keyboard: false });

   		return false;

   	});

   	$(document).on('click', ".customer-select", function(e) {

		    var customer_name = $(this).attr('data-customer-name');
		    var customer_email = $(this).attr('data-customer-email');
		    var customer_phone = $(this).attr('data-customer-phone');

		    var customer_address_1 = $(this).attr('data-customer-address-1');
		    var customer_address_2 = $(this).attr('data-customer-address-2');
		    var customer_town = $(this).attr('data-customer-town');
		    var customer_county = $(this).attr('data-customer-county');
		    var customer_postcode = $(this).attr('data-customer-postcode');

		    var customer_name_ship = $(this).attr('data-customer-name-ship');
		    var customer_address_1_ship = $(this).attr('data-customer-address-1-ship');
		    var customer_address_2_ship = $(this).attr('data-customer-address-2-ship');
		    var customer_town_ship = $(this).attr('data-customer-town-ship');
		    var customer_county_ship = $(this).attr('data-customer-county-ship');
		    var customer_postcode_ship = $(this).attr('data-customer-postcode-ship');

		    $('#customer_name').val(customer_name);
		    $('#customer_email').val(customer_email);
		    $('#customer_phone').val(customer_phone);

		    $('#customer_address_1').val(customer_address_1);
		    $('#customer_address_2').val(customer_address_2);
		    $('#customer_town').val(customer_town);
		    $('#customer_county').val(customer_county);
		    $('#customer_postcode').val(customer_postcode);


		    $('#customer_name_ship').val(customer_name_ship);
		    $('#customer_address_1_ship').val(customer_address_1_ship);
		    $('#customer_address_2_ship').val(customer_address_2_ship);
		    $('#customer_town_ship').val(customer_town_ship);
		    $('#customer_county_ship').val(customer_county_ship);
		    $('#customer_postcode_ship').val(customer_postcode_ship);

		    $('#insert_customer').modal('hide');

	});


	// create voucher
$("#action_create_voucher").on("click", function (e) {
    e.preventDefault();
    actionCreateVoucher();
});

// update voucher
$("#action_update_voucher").on("click", function (e) {
    e.preventDefault();
    actionUpdateVoucher();
});

	// create invoice
	$("#action_create_invoice").click(function(e) {
		e.preventDefault();
	    actionCreateInvoice();
	});

	// update invoice
	$(document).on('click', "#action_edit_invoice", function(e) {
		e.preventDefault();
		updateInvoice();
	});

	// enable date pickers for due date and invoice date
	var dateFormat = $(this).attr('data-vat-rate');
	$('#invoice_date, #expense_date, #start, #invoice_due_date').datetimepicker({
		showClose: false,
		format: dateFormat
	});

	// copy customer details to shipping
    $('input.copy-input').on("input", function () {
        $('input#' + this.id + "_ship").val($(this).val());
    });
    
    // remove product row
    $('#invoice_table').on('click', ".delete-row", function(e) {
    	e.preventDefault();
       	$(this).closest('tr').remove();
        calculateTotal();
    });

    // add new product row on invoice
$(".add-row").click(function(e) {
    e.preventDefault();

    // Clone the last row
    var newRow = $('#invoice_table tr:last').clone();

    // Clear all inputs
    newRow.find('input, select, textarea').each(function() {
        if ($(this).is(':checkbox') || $(this).is(':radio')) {
            $(this).prop('checked', false);
        } else {
            $(this).val('');
        }
    });

// Set default values when creating a new row
newRow.find('input[name="invoice_product_qty[]"]').val('1');
newRow.find('input[name="invoice_product_price[]"]').val('0.00');
// NOTE: removed discount default here

// Append the cleared and updated row to the table
newRow.appendTo('#invoice_table');
});

calculateTotal();

$('#invoice_table').on('input', '.calculate', function () {
    updateTotals(this);
    calculateTotal();
});

$('#invoice_totals').on('input', '.calculate', function () {
    calculateTotal();
});

$('#invoice_product').on('input', '.calculate', function () {
    calculateTotal();
});

$('.remove_vat').on('change', function() {
    calculateTotal();
});

function updateTotals(elem) {
    var tr = $(elem).closest('tr'),
        quantity = parseFloat($('[name="invoice_product_qty[]"]', tr).val()) || 0,
        price = parseFloat($('[name="invoice_product_price[]"]', tr).val()) || 0,
        subtotal = quantity * price;

    // Set the calculated row subtotal (no discount applied)
    $('.calculate-sub', tr).val(subtotal.toFixed(2));
}

function calculateTotal() {
    var grandTotal = 0,
        c_ship = parseFloat($('.calculate.shipping').val()) || 0,
        discInput = $('.calculate.discount').val().trim(); // raw input
    
    $('#invoice_table tbody tr').each(function() {
        var c_sbt = parseFloat($('.calculate-sub', this).val()) || 0;
        grandTotal += c_sbt;
    });

    // VAT, SHIPPING, TOTAL, SUBTOTAL:
    var subT = parseFloat(grandTotal),
        discount = 0;

    // ✅ Detect if discount is percentage or number
    if (discInput.endsWith('%')) {
        var discPercent = parseFloat(discInput.replace('%', '')) || 0;
        discount = (discPercent / 100) * subT;  // percentage of subtotal
    } else {
        discount = parseFloat(discInput) || 0; // fixed number
    }

    var finalTotal = parseFloat(grandTotal + c_ship - discount),
        vat = parseFloat($('.invoice-vat').attr('data-vat-rate')) || 0;

    // Display Subtotal
    $('.invoice-sub-total').text(subT.toFixed(2));
    $('#invoice_subtotal').val(subT.toFixed(2));

    // Display Discount
    $('.invoice-discount').text(discount.toFixed(2));
    $('#invoice_discount').val(discount.toFixed(2));

    // VAT calculation
    if ($('.invoice-vat').attr('data-enable-vat') === '1') {
        var vatAmount = ((vat / 100) * finalTotal);
        $('.invoice-vat').text(vatAmount.toFixed(2));
        $('#invoice_vat').val(vatAmount.toFixed(2));

        if ($('.invoice-vat').attr('data-vat-method') === '1') {
            // VAT inclusive
            $('.invoice-total').text(finalTotal.toFixed(2));
            $('#invoice_total').val(finalTotal.toFixed(2));
        } else {
            // VAT exclusive
            $('.invoice-total').text((finalTotal + vatAmount).toFixed(2));
            $('#invoice_total').val((finalTotal + vatAmount).toFixed(2));
        }
    } else {
        $('.invoice-total').text(finalTotal.toFixed(2));
        $('#invoice_total').val(finalTotal.toFixed(2));
    }

    // remove vat override
    if ($('input.remove_vat').is(':checked')) {
        $('.invoice-vat').text("0.00");
        $('#invoice_vat').val("0.00");
        $('.invoice-total').text(finalTotal.toFixed(2));
        $('#invoice_total').val(finalTotal.toFixed(2));
    }
}
	function actionAddUser() {

		var errorCounter = validateForm();

		if (errorCounter > 0) {
		    $("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
		    $("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
		    $("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
		} else {

			$(".required").parent().removeClass("has-error");

			var $btn = $("#action_add_user").button("loading");

			$.ajax({

				url: 'response.php',
				type: 'POST',
				data: $("#add_user").serialize(),
				dataType: 'json',
				success: function(data){
					$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
					$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
					$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
					$("#add_user").remove();
					$btn.button("reset");
				},
				error: function(data){
					$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
					$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
					$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
					$btn.button("reset");
				}

			});
		}

	}

	function actionAddProduct() {

    var errorCounter = validateForm();

    if (errorCounter > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error</strong>: It appears you have forgotten to complete something!");

        $("html, body").animate({
            scrollTop: $('#response').offset().top
        }, 800);

        return;
    }

    $(".required").parent().removeClass("has-error");

    var $btn = $("#action_add_product");
    $btn.prop("disabled", true).val("Saving...");

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#add_product").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn()
                    .find(".message")
                    .html("<strong>Error</strong>: " + (data.message || 'Product creation failed'));
                return;
            }

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn()
                .find(".message")
                .html("<strong>Success</strong>: " + data.message);

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("product-list.php");
            }, 1500);
        },

        error: function (xhr) {
            console.error(xhr.responseText);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn()
                .find(".message")
                .html("<strong>Server Error</strong>: Unable to add product.");
        },

        complete: function () {
            $btn.prop("disabled", false).val("Add Product");
        }
    });
}

function actionAddExpense() {

    var errorCounter = validateForm();

    if (errorCounter > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error</strong>: It appears you have forgotten to complete something!");

        $("html, body").animate({
            scrollTop: $('#response').offset().top
        }, 800);

        return;
    }

    $(".required").parent().removeClass("has-error");

    var $btn = $("#action_add_expense");
    $btn.prop("disabled", true).val("Saving...");

    // IMPORTANT: Create FormData to send FILES
    var formData = new FormData(document.getElementById("add_expense"));

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn()
                    .find(".message")
                    .html("<strong>Error</strong>: " + (data.message || 'Expense creation failed'));
                return;
            }

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn()
                .find(".message")
                .html("<strong>Success</strong>: " + data.message);

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("expense-list.php");
            }, 1000);
        },

        error: function (xhr) {

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn()
                .find(".message")
                .html("<strong>AJAX Error</strong>: " + (xhr.responseText || 'Unexpected error'));
        },

        complete: function () {
            $btn.prop("disabled", false).val("Add Expense");
        }
    });
}



	function actionAddSchedule() {

    var errorCounter = validateForm();

    if (errorCounter > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error</strong>: It appears you have forgotten to complete something!");

        $("html, body").animate({
            scrollTop: $('#response').offset().top
        }, 800);

        return;
    }

    $(".required").parent().removeClass("has-error");

    var $btn = $("#action_add_schedule");
    $btn.prop("disabled", true).val("Saving...");

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#add_schedule").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn()
                    .find(".message")
                    .html("<strong>Error</strong>: " + (data.message || 'Schedule creation failed'));
                return;
            }

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn()
                .find(".message")
                .html("<strong>Success</strong>: " + data.message);

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("schedule-list.php");
            }, 1000);
        },

        error: function (xhr) {
            console.error(xhr.responseText);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn()
                .find(".message")
                .html("<strong>Server Error</strong>: Unable to add schedule.");
        },

        complete: function () {
            $btn.prop("disabled", false).val("Add Schedule");
        }
    });
}


	function actionCreateCustomer() {

    var errorCounter = validateForm();

    if (errorCounter > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error</strong>: It appears you have forgotten to complete something!");

        $("html, body").animate({
            scrollTop: $('#response').offset().top
        }, 800);

        return;
    }

    var $btn = $("#action_create_customer");
    $btn.prop("disabled", true).val("Saving...");

    $(".required").parent().removeClass("has-error");

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#create_customer").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn()
                    .find(".message")
                    .html("<strong>Error</strong>: " + (data.message || 'Customer creation failed'));
                return;
            }

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn()
                .find(".message")
                .html("<strong>Success</strong>: " + data.message);

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("customer-list.php");
            }, 1000);
        },

        error: function (xhr) {
            console.error(xhr.responseText);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn()
                .find(".message")
                .html("<strong>Server Error</strong>: Unable to create customer.");
        },

        complete: function () {
            $btn.prop("disabled", false).val("Create Customer");
        }
    });
}



	function actionCompanySettings(){

		var errorCounter = validateForm();

		if (errorCounter > 0) {
		    $("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
		    $("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
		    $("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
		} else {

			var $btn = $("#action_company_settings").button("loading");

			$(".required").parent().removeClass("has-error");

			$.ajax({

				url: 'response.php',
				type: 'POST',
				data: $("#company_settings").serialize(),
				dataType: 'json',
				success: function(data){
					$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
					$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
					$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
					$("#company_settings").before().html("<a href='./company-edit.php' class='btn btn-primary'>Edit Your Settings</a>");
					$("#create_cuatomer").remove();
					$btn.button("reset");
				},
				error: function(data){
					$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
					$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
					$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
					$btn.button("reset");
				} 

			});
		}

	}

function actionCreateVoucher() {

    if (validateForm() > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error:</strong> Please complete all required fields.");
        return;
    }

    let $btn = $("#action_create_voucher");
    $btn.prop("disabled", true).val("Creating...");

    $.ajax({
        url: "response.php",
        type: "POST",
        data: $("#create_voucher").serialize(),
        dataType: "json",

 success: function (res) {

    if (res.status !== 'success') {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error:</strong> " + res.message);
        return;
    }

    $("#response")
        .removeClass("alert-warning")
        .addClass("alert-success")
        .fadeIn()
        .find(".message")
        .html("<strong>Success:</strong> " + res.message);

    // Smooth scroll to message
    $("html, body").animate({
        scrollTop: $("#response").offset().top - 20
    }, 600);

    // Redirect after 1.5 seconds
    setTimeout(function () {
        window.location.href = "voucher-list.php";
    }, 1500);
},

    });
}

function actionUpdateVoucher() {

    if (validateForm() > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error:</strong> Please complete all required fields.");
        return;
    }

    let $btn = $("#action_update_voucher");
    $btn.prop("disabled", true).val("Updating...");

    $.ajax({
        url: "response.php",
        type: "POST",
        data: $("#update_voucher").serialize(),
        dataType: "json",

        success: function (res) {

            if (res.status !== 'success') {
                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn()
                    .find(".message")
                    .html("<strong>Error:</strong> " + res.message);
                return;
            }

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn()
                .find(".message")
                .html("<strong>Success:</strong> " + res.message);

            // Smooth scroll to message
            $("html, body").animate({
                scrollTop: $("#response").offset().top - 20
            }, 600);

            // Redirect after short delay
            setTimeout(function () {
                window.location.href = "voucher-list.php";
            }, 1500);
        },

        error: function (xhr) {
            alert("Server Error:\n" + xhr.responseText);
        },

        complete: function () {
            $btn.prop("disabled", false).val("Update Voucher");
        }
    });
}



	function actionCreateInvoice() {

    var errorCounter = validateForm();

    if (errorCounter > 0) {
        $("#response")
            .removeClass("alert-success")
            .addClass("alert-warning")
            .fadeIn()
            .find(".message")
            .html("<strong>Error</strong>: It appears you have forgotten to complete something!");

        $("html, body").animate({
            scrollTop: $('#response').offset().top
        }, 800);

        return;
    }

    var $btn = $("#action_create_invoice");
    $btn.prop("disabled", true).val("Creating...");

    $(".required").parent().removeClass("has-error");
    $("#create_invoice").find(':input:disabled').removeAttr('disabled');

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#create_invoice").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn()
                    .find(".message")
                    .html("<strong>Error</strong>: " + (data.message || 'Invoice creation failed'));
                return;
            }

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn()
                .find(".message")
                .html("<strong>Success</strong>: " + data.message);

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("invoice-list.php");
            }, 1500);
        },

        error: function (xhr, status, error) {
            console.log(xhr.responseText);
            alert(
                "AJAX Error\n" +
                "Status: " + status + "\n" +
                "Error: " + error + "\n" +
                "Response:\n" + xhr.responseText
            );
        },

        complete: function () {
            $btn.prop("disabled", false).val("Create Invoice");
        }
    });
}


   	function deleteProduct(productId) {

        jQuery.ajax({

        	url: 'response.php',
            type: 'POST', 
            data: productId,
            dataType: 'json', 
            success: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			},
			error: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			} 
    	});

   	}

   	function deleteUser(userId) {

        jQuery.ajax({

        	url: 'response.php',
            type: 'POST', 
            data: userId,
            dataType: 'json', 
            success: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			},
			error: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			} 
    	});

   	}


// delete expenses
function deleteExpense(userId) {

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: userId,
        dataType: 'json',

        success: function (data) {

            $("#response .message")
                .html("<strong>" + data.status + "</strong>: " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Auto-hide & fully reset after 1500ms
            setTimeout(function () {
                $("#response").fadeOut(400, function () {
                    $(this)
                        .removeClass("alert-success alert-warning")
                        .find(".message").html("");
                });
            }, 1500);
        },

        error: function (xhr, status, errorThrown) {

            let realError = xhr.responseText ? xhr.responseText : errorThrown;

            $("#response .message")
                .html("<strong>Server Error</strong>:<br>" + realError);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Auto-hide & reset error alert too
            setTimeout(function () {
                $("#response").fadeOut(400, function () {
                    $(this)
                        .removeClass("alert-success alert-warning")
                        .find(".message").html("");
                });
            }, 1500);
        }
    });
}



	function deleteSchedule(userId) {

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: userId,
        dataType: 'json',

        success: function (data) {

            $("#response .message")
                .html("<strong>" + data.status + "</strong>: " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ AUTO-HIDE after 1500ms
            setTimeout(function () {
                $("#response").fadeOut(400);
            }, 1500);
        },

        error: function (xhr, status, errorThrown) {

            let realError = xhr.responseText ? xhr.responseText : errorThrown;

            $("#response .message")
                .html("<strong>Server Error</strong>:<br>" + realError);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            setTimeout(function () {
				$("#response").fadeOut(400, function () {
					$(this).removeClass("alert-success alert-warning");
				});
			}, 1500);

        }
    });
}

	function deleteCustomer(userId) {

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: userId,
        dataType: 'json',

        success: function (data) {

            $("#response .message")
                .html("<strong>" + data.status + "</strong>: " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Auto-hide & fully reset after 1500ms
            setTimeout(function () {
                $("#response").fadeOut(400, function () {
                    $(this)
                        .removeClass("alert-success alert-warning")
                        .find(".message").html("");
                });
            }, 1500);
        },

        error: function (xhr) {

            let realError = xhr.responseText || 'Unexpected error';

            $("#response .message")
                .html("<strong>Server Error</strong>:<br>" + realError);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Auto-hide & fully reset error alert too
            setTimeout(function () {
                $("#response").fadeOut(400, function () {
                    $(this)
                        .removeClass("alert-success alert-warning")
                        .find(".message").html("");
                });
            }, 1500);
        }
    });
}

   	function emailInvoice(invoiceId) {

        jQuery.ajax({

        	url: 'response.php',
            type: 'POST', 
            data: invoiceId,
            dataType: 'json', 
            success: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
			},
			error: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
			} 
    	});

   	}

   	function deleteInvoice(invoiceId) {

        jQuery.ajax({

        	url: 'response.php',
            type: 'POST', 
            data: invoiceId,
            dataType: 'json', 
            success: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			},
			error: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			} 
    	});

   	}



// delete voucher
function deleteVoucher(voucherId, row) {

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: {
            action: 'delete_voucher',
            voucher_id: voucherId
        },
        dataType: 'json',

        success: function (res) {

            $("#response .message")
                .html("<strong>" + res.status + "</strong>: " + res.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            // remove row only after success
            if (row) {
                row.fadeOut(300, function () {
                    $(this).remove();
                });
            }

            // ✅ Auto-hide & fully reset after 1500ms
            setTimeout(function () {
                $("#response").fadeOut(400, function () {
                    $(this)
                        .removeClass("alert-success alert-warning")
                        .find(".message").html("");
                });
            }, 1500);
        },

        error: function (xhr) {

            $("#response .message")
                .html("<strong>Error</strong>: " + (xhr.responseText || 'Unexpected error'));

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            // ✅ Auto-hide & reset error alert too
            setTimeout(function () {
                $("#response").fadeOut(400, function () {
                    $(this)
                        .removeClass("alert-success alert-warning")
                        .find(".message").html("");
                });
            }, 1500);
        }
    });
}


function updateProduct() {

    var $btn = $("#action_update_product");
    $btn.prop("disabled", true).val("Updating...");

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#update_product").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response .message")
                    .html("<strong>Error:</strong> " + (data.message || 'Update failed'));

                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn();

                $("html, body").animate({
                    scrollTop: $('#response').offset().top
                }, 600);

                $btn.prop("disabled", false).val("Update Product");
                return;
            }

            $("#response .message")
                .html("<strong>Success:</strong> " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("product-list.php");
            }, 1500);
        },

        error: function (xhr) {

            $("#response .message")
                .html("<strong>Server Error</strong>: " + (xhr.responseText || 'Unexpected error'));

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            $btn.prop("disabled", false).val("Update Product");
        }
    });
}

   
   	function updateUser() {

   		var $btn = $("#action_update_user").button("loading");

        jQuery.ajax({

        	url: 'response.php',
            type: 'POST', 
            data: $("#update_user").serialize(),
            dataType: 'json', 
            success: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			},
			error: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
				$btn.button("reset");
			} 
    	});

   	}

	function updateExpense() {

    var $btn = $("#action_update_expense");
    $btn.prop("disabled", true).val("Updating...");

    let form = document.getElementById("update_expense");
    let formData = new FormData(form);

    $.ajax({
        url: "response.php",
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        dataType: "json",

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response .message")
                    .html("<strong>Error</strong>: " + (data.message || 'Update failed'));

                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn();

                $("html, body").animate({
                    scrollTop: $('#response').offset().top
                }, 600);

                $btn.prop("disabled", false).val("Update Expense");
                return;
            }

            $("#response .message")
                .html("<strong>Success</strong>: " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("expense-list.php");
            }, 1000);
        },

        error: function (xhr, status, errorThrown) {

            let realError = xhr.responseText ? xhr.responseText : errorThrown;

            $("#response .message")
                .html("<strong>Server Error</strong>:<br>" + realError);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            $btn.prop("disabled", false).val("Update Expense");
        }
    });
}



	function updateSchedule() {

    var $btn = $("#action_update_schedule");
    $btn.prop("disabled", true).val("Updating...");

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#update_schedule").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response .message")
                    .html("<strong>Error</strong>: " + (data.message || 'Update failed'));

                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn();

                $("html, body").animate({
                    scrollTop: $('#response').offset().top
                }, 600);

                $btn.prop("disabled", false).val("Update Schedule");
                return;
            }

            $("#response .message")
                .html("<strong>Success</strong>: " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("schedule-list.php");
            }, 1000);
        },

        error: function (xhr) {

            $("#response .message")
                .html("<strong>Server Error</strong>: " + (xhr.responseText || 'Unexpected error'));

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            $btn.prop("disabled", false).val("Update Schedule");
        }
    });
}


   	function updateCustomer() {

    var $btn = $("#action_update_customer");
    $btn.prop("disabled", true).val("Updating...");

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#update_customer").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response .message")
                    .html("<strong>Error:</strong> " + (data.message || 'Update failed'));

                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn();

                $("html, body").animate({
                    scrollTop: $('#response').offset().top
                }, 600);

                $btn.prop("disabled", false).val("Update Customer");
                return;
            }

            $("#response .message")
                .html("<strong>Success:</strong> " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("customer-list.php");
            }, 1000);
        },

        error: function (xhr) {

            $("#response .message")
                .html("<strong>Server Error</strong>: " + (xhr.responseText || 'Unexpected error'));

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            $btn.prop("disabled", false).val("Update Customer");
        }
    });
}


   	function updateInvoice() {

    var $btn = $("#action_update_invoice");
    $btn.prop("disabled", true).val("Updating...");

    // Ensure disabled fields are included
    $("#update_invoice").find(':input:disabled').removeAttr('disabled');

    $.ajax({
        url: 'response.php',
        type: 'POST',
        data: $("#update_invoice").serialize(),
        dataType: 'json',

        success: function (data) {

            // Normalize status to avoid casing issues
            var status = (data.status || '').toString().toLowerCase();

            if (status !== 'success') {
                $("#response .message")
                    .html("<strong>Error:</strong> " + (data.message || 'Update failed'));

                $("#response")
                    .removeClass("alert-success")
                    .addClass("alert-warning")
                    .fadeIn();

                $("html, body").animate({
                    scrollTop: $('#response').offset().top
                }, 600);

                $btn.prop("disabled", false).val("Update Invoice");
                return;
            }

            $("#response .message")
                .html("<strong>Success:</strong> " + data.message);

            $("#response")
                .removeClass("alert-warning")
                .addClass("alert-success")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            // ✅ Redirect after short delay
            setTimeout(function () {
                window.location.assign("invoice-list.php");
            }, 1500);
        },

        error: function (xhr, status, errorThrown) {

            let realError = xhr.responseText ? xhr.responseText : errorThrown;

            $("#response .message")
                .html("<strong>Server Error</strong>:<br>" + realError);

            $("#response")
                .removeClass("alert-success")
                .addClass("alert-warning")
                .fadeIn();

            $("html, body").animate({
                scrollTop: $('#response').offset().top
            }, 600);

            $btn.prop("disabled", false).val("Update Invoice");
        }
    });
}

   	function downloadCSV(action) {

   		jQuery.ajax({

   			url: 'response.php',
   			type: 'POST',
   			data: action,
   			dataType: 'json',
   			success: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
			},
			error: function(data){
				$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
				$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
				$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
			} 
   		});

   	}

   	// login function
	function actionLogin() {

		var errorCounter = validateForm();

		if (errorCounter > 0) {

		    $("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
		    $("#response .message").html("<strong>Error</strong>: Missing something are we? check and try again!");
		    $("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);

		} else {

			var $btn = $("#btn-login").button("loading");

			jQuery.ajax({
				url: 'response.php',
				type: "POST",
				data: $("#login_form").serialize(), // serializes the form's elements.
				dataType: 'json',
				success: function(data){
					$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
					$("#response").removeClass("alert-warning").addClass("alert-success").fadeIn();
					$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
					$btn.button("reset");

					window.location = "dashboard.php";
				},
				error: function(data){
					$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
					$("#response").removeClass("alert-success").addClass("alert-warning").fadeIn();
					$("html, body").animate({ scrollTop: $('#response').offset().top }, 1000);
					$btn.button("reset");
				}

			});

		}
		
	}

   	function validateForm() {
	    // error handling
	    var errorCounter = 0;

	    $(".required").each(function(i, obj) {

	        if($(this).val() === ''){
	            $(this).parent().addClass("has-error");
	            errorCounter++;
	        } else{ 
	            $(this).parent().removeClass("has-error"); 
	        }


	    });

	    return errorCounter;
	}

});