$(document).ready(function () {
    $('#service').on('change', function () {
        let serviceId = $(this).val();

        $.ajax({
            url: `/dashboard/manage/transaction/get-price/${serviceId}`,
            method: 'GET',
            success: function (response) {
                if (response.status) {
                    $('#price').val(response.data || '0');

                    calculateTotal();
                }
            },
            error: function () {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: 'Terjadi kesalahan saat mengambil data layanan! Silakan coba lagi. Jika masalah berlanjut, hubungi administrator.',
                });
            }
        });
    });

    function calculateTotal() {
        let price = parseFloat($('#price').val().replace(/[^0-9]/g, '') || 0);
        let discount = parseFloat($('#discount').val().replace(/[^0-9]/g, '') || 0);

        let total = price - discount;

        $('#total').val('Rp' + total.toLocaleString('id-ID'));
    }

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