$(document).ready(function () {
    let shavingResults = parseFloat(unformatRupiah($('#shaving_result').val())) || 0;
    if ($('#employee').val()) {
        $('#percentage_shaving').prop('readonly', false);
    }

    $('#employee').on('change', function () {
        let employeeId = $(this).val();

        if (!employeeId) {
            $('#percentage_shaving').prop('readonly', true);
            $('#percentage_shaving').val('');
            return;
        }

        $.ajax({
            url: `/dashboard/finance/payroll/get-salary/${employeeId}`,
            method: 'GET',
            success: function (response) {
                if (response.status) {
                    $('#amount').val(response.data.baseSalary || '0');
                    $('#cut').val(response.data.debt || '0');
                    $('#shaving_result').val(response.data.shavingResults || '0');

                    shavingResults = parseFloat(unformatRupiah(response.data.shavingResults)) || 0;

                    $('#percentage_shaving').prop('readonly', false);

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

                $('#percentage_shaving').prop('readonly', true);
                $('#percentage_shaving').val('');
            }
        });
    });

    $('#amount, #incentive, #cut, #percentage_shaving').on('input', function () {
        calculateTotal();
    });

    function calculateTotal() {
        let amount = parseInt(unformatRupiah($('#amount').val())) || 0;
        let incentive = parseInt(unformatRupiah($('#incentive').val())) || 0;
        let cut = parseInt(unformatRupiah($('#cut').val())) || 0;
        let percentage = parseFloat($('#percentage_shaving').val()) || 0;

        let percentageAmount = (shavingResults * percentage) / 100;

        let total = amount + incentive + percentageAmount - cut;
        $('#total').val('Rp' + formatRupiah(total));
    }

    function formatRupiah(angka) {
        if (!angka) return '0';
        return new Intl.NumberFormat('id-ID').format(angka);
    }

    function unformatRupiah(rupiahStr) {
        if (!rupiahStr) return '0';
        return rupiahStr.replace(/\D/g, '');
    }
});
