<!-- JAVASCRIPT -->
<script src="{{ asset('assets/libs/jquery/jquery.min.js') }}"></script>
<script src="{{ asset('assets/libs/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
<script src="{{ asset('assets/libs/metismenu/metisMenu.min.js') }}"></script>
<script src="{{ asset('assets/libs/simplebar/simplebar.min.js') }}"></script>
<script src="{{ asset('assets/libs/node-waves/waves.min.js') }}"></script>

<script src="{{ asset('assets/libs/toastr/build/toastr.min.js') }}"></script>
<script src="{{ asset('assets/libs/sweetalert2/sweetalert2.min.js') }}"></script>

<!-- apexcharts -->
<script src="{{ asset('assets/libs/apexcharts/apexcharts.min.js') }}"></script>

<!-- dashboard init -->
<script src="{{ asset('assets/js/pages/dashboard.init.js') }}"></script>

<script src="{{ asset('assets/libs/select2/js/select2.min.js') }}"></script>
<script src="{{ asset('assets/libs/bootstrap-datepicker/js/bootstrap-datepicker.min.js') }}"></script>
<script src="{{ asset('assets/libs/bootstrap-timepicker/js/bootstrap-timepicker.min.js') }}"></script>
<script src="{{ url('https://cdn.jsdelivr.net/npm/flatpickr') }}"></script>
<script src="{{ asset('assets/libs/dataTables/dataTables.js') }}"></script>

<!-- App js -->
<script src="{{ asset('assets/js/app.js') }}"></script>
<script src="{{ asset('assets/js/settings.js') }}"></script>
<script src="{{ asset('assets/js/custom.js') }}"></script>

<script>
    window.APP_LOCALE = "{{ app()->getLocale() }}";
</script>

<!-- Additional Scripts -->
@include('layouts.partials.scripts._flatpickr-scripts')
@include('layouts.partials.scripts._select2-scripts')

<script>
    $(function () {

        const routes = {
            roles: `{{ route('ajax.get-roles') }}`,
            plans: `{{ route('ajax.get-plans') }}`,
            customers: `{{ route('ajax.get-customers') }}`,
            banks: `{{ route('ajax.get-banks') }}`,
            paymentMethods: `{{ route('ajax.get-payment-methods') }}`,
            paymentMethodData: `{{ route('data.get-payment-methods') }}`,
            subscriptionData: `{{ route_ID_('data.get-subscriptions') }}`,
            customersData: `{{ route('data.get-customers') }}`,
            subscriptions: `{{ route('ajax.get-subscriptions') }}`,
            regions: `{{ route('ajax.get-regions') }}`,
            cities: `{{ route('ajax.get-cities') }}`,
        };

        const inputs = {
            roles: $(".roles-select"),
            plans: $(".plans-select"),
            payeeName: $(".payee-name-input"),
            customerBalance: $(".customer-wallet-input"),
            receiptTypes: $(".receipt-vouchers-types-select"),
            paymentTypes: $(".payment-vouchers-types-select"),
            customers: $(".customers-select"),
            subscriptions: $(".subscriptions-select"),
            paymentMethods: $(".payment-methods-select"),
            banks: $(".banks-select"),
            subscriptionAmount: $(".subscription-amount"),
            regions: $(".regions-select"),
            cities: $(".cities-select"),
        };

        const cols = {
            payeeName: $(".payee-name-col"),
            customerBalance: $(".customer-wallet-col"),
            customers: $(".customers-col"),
            subscriptions: $(".subscriptions-col"),
            banks: $(".banks-col"),
        };

        initSelect2();
        bindEvents();

        /* -----------------------------
           Initialize Select2 fields
        -----------------------------*/
        function initSelect2() {
            lazySelect2Ajax(inputs.customers, routes.customers);
            lazySelect2Ajax(inputs.banks, routes.banks);
            lazySelect2Ajax(inputs.paymentMethods, routes.paymentMethods);
            lazySelect2Ajax(inputs.roles, routes.roles);
            lazySelect2Ajax(inputs.plans, routes.plans);
            lazySelect2Ajax(inputs.regions, routes.regions);
        }

        /* -----------------------------
           Events
        -----------------------------*/
        function bindEvents() {
            inputs.receiptTypes.on('change', handleReceiptTypeChange);
            inputs.paymentTypes.on('change', handlePaymentTypesChange);
            inputs.paymentMethods.on('change', handlePaymentMethodChange);
            inputs.customers.on('change', handleCustomerChange);
            inputs.subscriptions.on('change', handleSubscriptionChange);
        }

        inputs.regions.on('change', function () {
            const regionId = Number(inputs.regions.val());
            inputs.cities.val(null).trigger('change');

            if (!regionId) return;

            lazySelect2Ajax(inputs.cities, routes.cities, false, null, {
                region_id: regionId,
            });
        });

        /* -----------------------------
           Type change
        -----------------------------*/
        function handleReceiptTypeChange() {
            const type = inputs.receiptTypes.val();
            const isSubscription = type === 'subscription';

            cols.subscriptions.toggleClass('d-none', !isSubscription);

            resetSelect(inputs.subscriptions);
        }

        function handlePaymentTypesChange() {
            const type = inputs.paymentTypes.val();
            const isInternal = type === 'internal';

            cols.customers.toggleClass('d-none', !isInternal);
            cols.subscriptions.toggleClass('d-none', !isInternal);
            cols.payeeName.toggleClass('d-none', isInternal);

            resetSelect(inputs.customers);
            resetInput(inputs.payeeName);
        }

        /* -----------------------------
           Payment Method change
        -----------------------------*/
        function handlePaymentMethodChange() {
            const paymentMethodId = Number(inputs.paymentMethods.val());

            if (!paymentMethodId) return;

            $.ajax({
                url: routes.paymentMethodData,
                method: 'GET',
                dataType: 'json',
                data: { id: paymentMethodId },
                success(response) {
                    if (response.error) {
                        console.error(response.message);
                        return;
                    }

                    updatePaymentMethodUI(response);
                }, error(xhr) {
                    console.error(xhr.responseJSON ?? xhr.responseText);
                }
            });

        }

        /* -----------------------------
           Subscription change
        -----------------------------*/
        function handleSubscriptionChange() {
            const subscriptionId = Number(inputs.subscriptions.val());

            if (!subscriptionId) return;

            $.ajax({
                url: (routes.subscriptionData).replace('_ID_', subscriptionId),
                method: 'GET',
                dataType: 'json',
                success(response) {
                    if (response.error) {
                        console.error(response.message);
                        return;
                    }

                    inputs.subscriptionAmount.val(response.remaining_paid || 0).trigger('input');
                }, error(xhr) {
                    console.error(xhr.responseJSON ?? xhr.responseText);
                }
            });

        }

        /* -----------------------------
           Update UI based on payment type
        -----------------------------*/
        function updatePaymentMethodUI(data) {
            const isBank = data.type === 'bank';

            cols.banks.toggleClass('d-none', !isBank);
        }

        /* -----------------------------
           Customer change
        -----------------------------*/
        function handleCustomerChange() {
            const customerId = Number(inputs.customers.val());

            resetSelect(inputs.subscriptions);

            if (!customerId) {
                inputs.subscriptions.empty();
                return;
            }
            resetSelect(inputs.subscriptions);

            lazySelect2Ajax(
                inputs.subscriptions,
                routes.subscriptions,
                false,
                null,
                { customer: customerId }
            );

            $.ajax({
                url: routes.customersData,
                method: 'GET',
                dataType: 'json',
                data: { id: customerId },
                success(response) {
                    if (response.error) {
                        console.error(response.message);
                        return;
                    }
                    resetInput(inputs.customerBalance);

                    inputs.customerBalance.val(response.balance || 0).trigger('input');
                }, error(xhr) {
                    console.error(xhr.responseJSON ?? xhr.responseText);
                }
            });

        }

        /* -----------------------------
           Helpers
        -----------------------------*/
        function resetSelect(element) {
            element.val(null).trigger('change');
        }
        function resetInput(element) {
            element.val(null).trigger('input');
        }

    });


</script>

@yield("scripts")
