{{-- Control Variables --}}
@php
    use App\Enums\Invoicing\InvoiceStatus;
@endphp

{{-- Modal --}}
<div id="invoicePaymentHistoryModal" class="mt-4 modal fade" tabindex="-1"
    role="dialog" aria-labelledby="modal-title" aria-hidden="true"
>
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">

            {{-- Header --}}
            <div class="pb-2 mt-4 modal-header d-flex align-items-center">

                {{-- Titles --}}
                <div class="mx-auto text-center">
                    <h3 class="text-uppercase">
                        {{ __('entity_forms')['tax_payment']['payment_history']['title'] }}
                    </h3>

                    <h6 class="text-uppercase text-dark">
                        {{ __('entity_forms')['tax_payment']['payment_history']['subtitle'] }}
                    </h6>
                </div>

                {{-- Close Button --}}
                <button type="button" data-dismiss="modal" aria-label="Close"
                    class="close d-flex align-items-center justify-content-center"
                    style="position:absolute; right:1.5rem;"
                >
                    <img src="{{ asset('icons/close_modal.svg') }}"
                        aria-hidden="true" style="width: 2.3rem;">
                </button>
            </div>

            {{-- Content --}}
            <div class="px-5 pb-3 modal-body">

                {{-- Original Invoice --}}
                <div class="my-3 table-responsive">
                    <table class="table table-bordered">

                        {{-- Header --}}
                        <thead><tr class="bg-light">
                            <th scope="col" class="font-weight-bold text-dark">
                                {{ __('entity_forms')['tax_payment']['payment_history']['invoice_data'] }}
                            </th>
                        </tr></thead>

                        {{-- Body --}}
                        <tbody><tr><td class="px-4">
                            {{-- Receiver --}}
                            <p class="mb-2 font-weight-bolder">
                                {{ __('entity_fields')['common']['receiver'] }}
                            </p>
                            <div class="d-flex justify-content-around align-items-around">
                                {{-- RFC --}}
                                <p>
                                    {{ __('entity_fields')['client']['tax_id'] }}<br>
                                    <span class="text-dark" id="receiver_tax_id"></span>
                                </p>

                                {{-- Razón Social --}}
                                <p>
                                    {{ __('entity_fields')['common']['legal_name'] }}<br>
                                    <span class="text-dark" id="receiver_legal_name"></span>
                                </p>

                                {{-- Regimen Fiscal --}}
                                <p>
                                    {{ __('entity_fields')['common']['tax_system'] }}<br>
                                    <span class="text-dark" id="receiver_tax_system"></span>
                                </p>
                            </div>

                            {{-- Invoice --}}
                            <p class="mb-2 font-weight-bolder">
                                {{ __('entity_forms')['tax_payment']['payment_history']['history_summary'] }}
                            </p>
                            <div class="d-flex justify-content-around align-items-around">
                                {{-- Fecha --}}
                                <p>
                                    {{ __('entity_fields')['common']['certification_date'] }}<br>
                                    <span class="text-dark" id="invoice_certification_date"></span>
                                </p>

                                {{-- Serie --}}
                                <p>
                                    {{ __('entity_fields')['common']['series'] }}<br>
                                    <span class="text-dark" id="invoice_serie"></span>
                                </p>

                                {{-- Folio --}}
                                <p>
                                    Folio<br>
                                    <span class="text-dark" id="invoice_sat_uuid"></span>
                                </p>
                            </div>
                            <div class="d-flex justify-content-around align-items-around">
                                {{-- Total --}}
                                <p>
                                    Total<br>
                                    <span class="text-dark" id="invoice_total"></span>
                                </p>

                                {{-- Monto Pagado --}}
                                <p>
                                    {{ __('entity_fields')['tax_payment']['amount_paid'] }}<br>
                                    <span class="text-dark" id="invoice_total_paid"></span>
                                </p>

                                {{-- Monto Pendiente --}}
                                <p>
                                    {{ __('entity_fields')['tax_payment']['remaining_balance'] }}<br>
                                    <span class="text-dark" id="invoice_remaining_balance"></span>
                                </p>

                                {{-- Moneda --}}
                                <p>
                                    {{ __('entity_fields')['common']['currency'] }}<br>
                                    <span class="text-dark" id="invoice_currency"></span>
                                </p>

                                {{-- Tipo de cambio --}}
                                <p>
                                    {{ __('entity_fields')['common']['exchange_rate'] }}<br>
                                    <span class="text-dark" id="invoice_exchange_rate"></span>
                                </p>
                            </div>
                        </td></tr></tbody>

                    </table>
                </div>

                {{-- Payments History --}}
                <div
                    class="my-3 table-responsive" id="tax-payment-history-table"
                    style="max-height: 17rem !important; overflow-y: auto;"
                >
                    <table class="table table-bordered table-striped table-hover">

                        {{-- Header --}}
                        <thead class="sticky-top" id="tax-payment-history-table-header">
                            <tr class="bg-light">
                                <th scope="col" colspan="10" class="text-center font-weight-bold text-dark">
                                    {{ __('entity_forms')['tax_payment']['payment_history']['history_table'] }}
                                </th>
                            </tr>

                            <tr class="text-center">
                                <th width="10%">{{ __('entity_fields')['tax_payment']['parciatiliy_number'] }}</th>
                                <th width="10%">{{ __('entity_fields')['common']['date'] }}</th>
                                <th width="5%">{{ __('entity_fields')['common']['series'] }}</th>
                                <th width="5%">Folio</th>
                                <th>{{ __('entity_fields')['common']['status'] }}</th>
                                <th>{{ __('entity_fields')['common']['currency'] }}</th>
                                <th width="10%">{{ __('entity_fields')['common']['exchange_rate'] }}</th>
                                <th width="12%">{{ __('entity_fields')['tax_payment']['amount_sample'] }}</th>
                                <th width="12%">{{ __('entity_fields')['tax_payment']['amount_paid'] }}</th>
                                <th width="10%">{{ __('entity_fields')['common']['actions'] }}</th>
                            </tr>
                        </thead>

                        {{-- Body --}}
                        <tbody id="tax-payment-history-table-body" class="text-center"></tbody>
                    </table>
                </div>

            </div>

            {{-- Buttons --}}
            <div class="modal-footer border-top-1 border-secondary d-flex justify-content-center">
                <button type="button" id="invoice_tax_payment_trigger"
                    value="" onclick="openPaymentComplement(this)"
                    class="w-25 btn btn-harsi" style="font-size: 1.1rem !important"
                >
                    {{ __('entity_forms')['tax_payment']['payment_history']['submit_button'] }}
                </button>
            </div>

        </div>
    </div>
</div>

{{-- Scripts --}}
<script>
  //* Global Variables
    window.tax_decrypt_data = "4ar51-e3067mnt-e0fe-4cb2-15f19";
    window.banxico_currencies = @JSON(config('constants.banxico_currencies'));

  //* General Control
    $(document).ready(function () {

      //- On close AdditionalDocs form
        $('#invoicePaymentHistoryModal').on('hide.bs.modal', function () {
            document.activeElement.blur();
        });

      //- Behavior
        // Scroll Table Control
        $('#tax-payment-history-table').on('scroll', function () {
            if ($(this).scrollTop() > 30) {
                $('#tax-payment-history-table-header').addClass('glass-background');
            } else {
                $('#tax-payment-history-table-header').removeClass('glass-background');
            }
        });

    });

  //* Interactions
    function displayPaymentHistory(id) {
      //* Reset Content
        resetPaymentHistory();

      //* Load Modal Data
        $.ajax({
            url: `/invoicing/invoices/${id}/payment-history`,
            dataType: "json",

            success: function (result) {
              //* Avoid Render on Error
                if(!result) return;

              //* Parse Data
                const invoice = result.data;
                const receiver = invoice.receptor;
                const payments = invoice.tax_payment_docs;
                const latest_tax_payment_doc = invoice.latest_tax_payment_doc;

                //Stamp limit
                const stamp_limit_status = result.stamping_limit_status;

              //* Structure Data
                let invoice_total_paid = "0.00";
                let invoice_remaining_balance = invoice.total;
                let last_payment_id = null;

                if (latest_tax_payment_doc !== null) {
                    invoice_total_paid = parseFloat(invoice.total) - parseFloat(latest_tax_payment_doc.remaining_balance);
                    invoice_total_paid = invoice_total_paid.toFixed(2);

                    invoice_remaining_balance = latest_tax_payment_doc.remaining_balance;

                    last_payment_id = latest_tax_payment_doc.tax_payment_id
                }

                const has_remaining_balance = invoice_remaining_balance > 0;

                // Get currency parities
                const exchange_rate_val = parseFloat(invoice.exchange_rate).toFixed(4) || 1;
                const currency_code = invoice.currency;

              //* Fill Fields
                // Receiver
                const receiver_tax_system = receiver?.tax_system?.item_key + " - " + receiver?.tax_system?.label;
                const encrypted_invoice_data = CryptoJS.AES.encrypt(JSON.stringify(invoice), window.tax_decrypt_data).toString();

                $('#receiver_tax_id').text(receiver.tax_id);
                $('#receiver_legal_name').text(receiver.legal_name);
                $('#receiver_tax_system').text(receiver_tax_system || "-- -- --");

                // Invoice Data
                $('#invoice_tax_payment_trigger').val(encrypted_invoice_data).toggle(has_remaining_balance);

                $('#invoice_certification_date').text(
                    moment(invoice.certification_date).format("YYYY-MM-DD HH:mm:ss")
                );
                $('#invoice_serie').text(`${invoice?.tax_format?.serie || invoice.invoice_type}-${invoice.serial_consecutive}`);
                $('#invoice_sat_uuid').text(invoice.sat_uuid);

                // Convert amounts by cuerency
                $('#invoice_total').text( formatBanxicoCurrency(invoice.total, currency_code ) );
                $('#invoice_total_paid').text( formatBanxicoCurrency(invoice_total_paid, currency_code ) );
                $('#invoice_remaining_balance').text( formatBanxicoCurrency(invoice_remaining_balance, currency_code ) );

                $('#invoice_currency').text(currency_code);
                $('#invoice_exchange_rate').text( formatBanxicoCurrency(exchange_rate_val, currency_code) );

                // Payment History (Build Table)
                buildPaymentHistory(payments, receiver, invoice.id, last_payment_id, currency_code, stamp_limit_status);

                // Display payment button
                displayPaymentButton(stamp_limit_status);

                $('#invoicePaymentHistoryModal').modal('show');
            }
        })
    }

    function sendPaymentByEmail(id, receiver_email) {
        Swal.fire({
            type: "warning",
            title: `${translateAndReplace('entity_forms.tax_payment.messages.send_cfdi_title')}`,
            html: `
                <small>
                    ${translateAndReplace('entity_forms.tax_payment.messages.send_cfdi_warnings')}
                </small>

                <div class="px-4 mt-3">
                    <label for="swal_receiver_email_ext" class="pt-1 mt-0 swal2-input-label switch_label justify-content-start">
                        ${translateAndReplace('entity_forms.tax_payment.messages.send_cfdi_receiver_label')}
                    </label>
                    <input id="swal_receiver_email_ext" type="email" value="${receiver_email}"
                        class="my-1 swal2-input" placeholder="email@gmail.com">

                    <label for="swal_email_cc1_ext" class="pt-3 mt-0 swal2-input-label switch_label justify-content-start">
                        ${translateAndReplace('entity_forms.tax_payment.messages.send_cfdi_cc_label')}
                        (${translateAndReplace('neutral_words.optional')})
                    </label>
                    <input id="swal_email_cc1_ext" type="email"
                        class="my-1 swal2-input" placeholder="email@ejemplo.com">

                    <label for="swal_email_cc2_ext" class="pt-3 mt-0 swal2-input-label switch_label justify-content-start">
                        ${translateAndReplace('entity_forms.tax_payment.messages.send_cfdi_cc_label')}
                        (${translateAndReplace('neutral_words.optional')})
                    </label>
                    <input id="swal_email_cc2_ext" type="email"
                        class="my-1 swal2-input" placeholder="email@ejemplo.com">
                </div>
            `,

            focusConfirm: false,
            showCancelButton: true,
            confirmButtonText: "{{ __('common_actions')['send'] }}",
            cancelButtonText: "{{ __('common_actions')['cancel'] }}",
            showLoaderOnConfirm: true,

            preConfirm: async function () {
                var popup = Swal.getPopup();

                var receiver_email  = popup.querySelector('#swal_receiver_email_ext').value.trim();
                var email_cc1 = popup.querySelector('#swal_email_cc1_ext').value.trim();
                var email_cc2 = popup.querySelector('#swal_email_cc2_ext').value.trim();

                if (!receiver_email) {
                    Swal.showValidationMessage(
                        "{{ __('validation.required', ['attribute' => __('entity_fields')['common']['email']]) }}"
                    );
                    return false;
                }

                var emails = {
                    to: receiver_email,
                    cc: [email_cc1, email_cc2].filter(e => e !== '')
                };
                var token = $('meta[name="csrf-token"]').attr('content');

                try {
                    const resp = await $.ajax({
                        url: `/invoicing/invoices/payment-complement/${id}/send-cfdi`,
                        method: 'POST',
                        data: JSON.stringify({ emails }),
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        headers: { 'X-CSRF-TOKEN': token },
                    });

                    return resp;
                } catch (xhr) {
                    let msg = "{{ __('common_responses_and_messages')['email_not_sent'] }}";
                        if (xhr.responseJSON && xhr.responseJSON.message) msg = xhr.responseJSON.message;

                    if (xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors) {
                        const firstKey = Object.keys(xhr.responseJSON.errors)[0];
                        msg = xhr.responseJSON.errors[firstKey][0];
                    }

                    Swal.showValidationMessage(msg);
                }
            },

            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed || result.value?.success)
                launchSwalToast('success',result.value.message);
            else
                launchSwalToast('warning', "{{ __('common_responses_and_messages')['email_not_sent'] }}");
        });
    }

    function cancelPaymentComplement(id, invoice_id) {
        Swal.fire({
            type: "warning",
            title: `{{ __('entity_forms')['tax_payment']['messages']['cancel_complement_title'] }}`,
            html: `
                <div class="px-4 mb-4">
                    <label for="swal_cancellation_reason_ext" class="pt-1 mt-0 swal2-input-label switch_label justify-content-start">
                        ${translateAndReplace("entity_forms.tax_payment.inputs.cancel_complement_reason")}
                    </label>
                    <select id="swal_cancellation_reason_ext" class="mt-1 mb-3 swal2-input" onchange="displaySubstituteUuidExt(this)">
                        <option value="" selected disabled>-- ${translateAndReplace("common_actions.select")} --</option>
                        @foreach ($cancellation_reasons as $reason)
                            <option value="{{ $reason->item_key }}">{{ $reason->item_key }} - {{ $reason->label }}</option>
                        @endforeach
                    </select>

                    <div id="cancellation_substitute_block_ext" style="display: none;">
                        <label for="swal_cancellation_substitute_ext" class="pt-1 mt-0 swal2-input-label switch_label justify-content-start">
                            ${translateAndReplace("entity_forms.tax_payment.inputs.cancel_complement_substitution_uuid")}
                        </label>
                        <select id="swal_cancellation_substitute_ext" class="my-1 w-100"></select>
                    </div>
                </div>

                <small class="text-danger">
                    ${translateAndReplace("entity_forms.tax_payment.messages.cancel_complement_warning")}
                </small>
            `,

            onOpen: () => {
                $(document).off('focusin.bs.modal');

                const $popup = $(Swal.getPopup());
                const $select_ext = $popup.find('#swal_cancellation_substitute_ext');

                $select_ext.select2({
                    placeholder: "{{ __('entity_forms')['tax_payment']['placeholders']['cancel_complement_substitution'] }}",
                    allowClear: true,
                    minimumInputLength: 3,
                    dropdownParent: $popup,
                    width: '100%',

                    ajax: {
                        url: "{{ route('tax-payments.searchByUuid') }}",
                        dataType: 'json',
                        delay: 250,

                        data: function (params) {
                            return {
                                q: params.term || '',
                                page: params.page || 1
                            };
                        },

                        processResults: function (data, params) {
                            params.page = params.page || 1;
                            return {
                                results: data.results,
                                pagination: { more: data.pagination.more }
                            };
                        },

                        cache: true
                    },
                });
            },

            preConfirm: () => {
                const popup = Swal.getPopup();
                const reason = popup.querySelector('#swal_cancellation_reason_ext').value;

                if (!reason) {
                    Swal.showValidationMessage("{{ __('validation.required', ['attribute' => __('entity_forms')['tax_payment']['inputs']['cancel_complement_reason']]) }}");
                    return false;
                }

                let substitute_uuid_id = null;
                if (reason === '01') {
                    substitute_uuid_id = $('#swal_cancellation_substitute_ext').val();

                    if (!substitute_uuid_id) {
                        Swal.showValidationMessage("{{ __('validation.required', ['attribute' => __('entity_forms')['tax_payment']['inputs']['cancel_complement_substitution_uuid']]) }}");
                        return false;
                    }
                }

                return {
                    reason,
                    substitute_uuid_id,
                    accepted: true,
                };
            },

            focusConfirm: false,
            showCancelButton: true,
            confirmButtonText: "{{ __('common_actions')['accept'] }}",
            cancelButtonText: "{{ __('common_actions')['cancel'] }}",
        }).then((result) => {
            if (result?.value?.accepted) {
                // Build Payload
                const data = result.value;

                const payload = {
                    cancel_motive: data.reason,
                };
                if (data.reason === '01') payload.substitution_invoice_id = data.substitute_uuid_id;

                window.loader.show(); // Display Loader

                // Request Cancellation
                $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    url: `/invoicing/invoices/payment-complement/${id}/cancel`,
                    method: "POST",
                    data: payload,

                    success: function (data) {
                        window.loader.hide(); // Hide Loader

                        launchSwalToast('success', data.message);

                        displayPaymentHistory(invoice_id);
                        $('#tax_invoice_table').DataTable().ajax.reload(null, false);

                      // Update stamp counter
                        let stamping_status = data.stamping_limit_status;

                        updateStampCounterIndex(stamping_status);
                        displayPaymentButton(stamping_status);
                        stampLimitAlerts(stamping_status);
                    },

                    error: function(data){
                        // Extract Data
                        const response = data.responseJSON;

                        // Define error types
                        if(response?.errors && typeof response?.errors === 'object'){
                            const errors = response.errors;
                            Object.keys(errors).forEach((key) => {
                                errors[key].forEach(message => showToast(message, "#C34808", "#78350F")); // Display as Validation Error
                            });
                        }else if(response?.message){
                            showToast(response.message, "#C34808", "#78350F" );
                        }else{
                            showToast("{{ __('entity_forms')['tax_invoice']['messages']['unexpected_cancellation_error']}}", "#C34808", "#78350F");
                        }

                        window.loader.hide(); // Hide Loader
                        return;
                    },
                });
            } else {
                launchSwalToast('warning', "{{ __('common_responses_and_messages')['data_not_loaded'] }}");
            }
        });
    }

  //* Support functions
    // Visual Changes
    function buildPaymentHistory(invoice_payments, receiver, invoice_id, last_payment_id, invoice_currency, stamp_limit_status) {
        let history_records = "";

        if (invoice_payments.length) {
            invoice_payments.forEach(txp => {
              //* Parse Data
                // Extract and Parse
                const tax_payment = txp.tax_payment;
                const payment_date = moment(tax_payment.payment_date).format("YYYY-MM-DD HH:mm:ss");

                const payment_serie = tax_payment?.tax_format?.serie || "P";
                const payment_serie_folio = tax_payment.serial_consecutive;

                // Cancellation Workflow Controls
                const is_cancellation_pending = tax_payment.cancellation_status === "pending";
                const is_finally_canceled = tax_payment.status === "canceled";

              //* Resources
                const routes = {
                    show: `/invoicing/invoices/payment-complement/${tax_payment.id}`,
                    download_pdf: `/invoicing/invoices/payment-complement/${tax_payment.id}?download=1`,
                    download_xml: `/invoicing/invoices/payment-complement/${tax_payment.id}/download-xml`,
                }

                const titles = {
                    show:           translateAndReplace('entity_forms.tax_invoice.action_titles.show'),
                    download_pdf:   translateAndReplace('entity_forms.tax_invoice.action_titles.download_pdf'), // Implemented
                    download_xml:   translateAndReplace('entity_forms.tax_invoice.action_titles.download_xml'), // Implemented
                    send_cfdi:      translateAndReplace('entity_forms.tax_invoice.action_titles.send_cfdi'),
                    cancel_cfdi:    translateAndReplace('entity_forms.tax_invoice.action_titles.cancel_cfdi'),
                };

                const button_options = {
                    show: {
                        condition: true,
                        structure: `
                            <a
                                href="${routes.show}" target="_blank"
                                class='dropdown-item text-primary'
                                title="${titles.show}"
                            >
                                <i class="mr-2 fas fa-file-pdf"></i> ${titles.show}
                            </a>
                        `,
                    },

                    download_pdf: {
                        condition: true,
                        structure: `
                            <a
                                href="${routes.download_pdf}"
                                class='dropdown-item harsi-color'
                                title="${titles.download_pdf}"
                            >
                                <i class="mr-2 fas fa-file-download"></i> ${titles.download_pdf}
                            </a>
                        `,
                    },

                    download_xml: {
                        condition: true,
                        structure: `
                            <a
                                href="${routes.download_xml}"
                                class='dropdown-item' style="color: #28a745 !important;"
                                title="${titles.download_xml}"
                            >
                                <i class="mr-2 fas fa-file-code"></i> ${titles.download_xml}
                            </a>
                        `,
                    },

                    send_cfdi: {
                        condition: true,
                        structure: `
                            <button
                                type="button" onclick="sendPaymentByEmail(${tax_payment.id}, '${receiver.email_billing}')"
                                class='dropdown-item text-warning'
                                title="${titles.send_cfdi}"
                            >
                                <i class="mr-2 fas fa-paper-plane"></i> ${titles.send_cfdi}
                            </button>
                        `,
                    },

                    cancel_cfdi: {
                        condition: txp.tax_payment_id === last_payment_id && !is_cancellation_pending && !is_finally_canceled && !stamp_limit_status.reached,
                        structure: `
                            <button
                                type="button" onclick="cancelPaymentComplement(${tax_payment.id}, ${invoice_id})"
                                class='dropdown-item text-danger'
                                title="${titles.cancel_cfdi}"
                            >
                                <i class="mr-2 fas fa-ban"></i> ${titles.cancel_cfdi}
                            </button>
                        `,
                    },
                };

              //* Define Actions
                let buttonsConfig;
                    if (is_cancellation_pending)
                        buttonsConfig = [ button_options.download_xml, button_options.download_pdf, button_options.show ];
                    else if (is_finally_canceled)
                        buttonsConfig = [ button_options.download_xml, button_options.download_pdf,  button_options.show ];
                    else if (tax_payment.status === "valid")
                        buttonsConfig = [ button_options.download_xml, button_options.download_pdf, button_options.send_cfdi, button_options.show, button_options.cancel_cfdi ];
                    else
                        buttonsConfig = [];

                const buttons = buttonsConfig.filter(({ condition }) => condition)
                    .map(({ structure }) => structure);

              //* Valor real del pago
                let reconverted_amount_paid;
                if(invoice_currency === 'MXN' && txp.currency === 'MXN'){
                    // Monto pagado *  Val. moneda de pago
                    reconverted_amount_paid= parseFloat(
                        txp.amount_paid * tax_payment.exchange_rate
                    ).toFixed(2);
                }else{
                    // Val.Act. moneda factura * monto pagado / Val. moneda pago
                    reconverted_amount_paid= parseFloat(
                        (txp.exchange_rate * txp.amount_paid) / tax_payment.exchange_rate
                    ).toFixed(2);
                }

              //* Build Table Rows
                history_records += `
                    <tr>
                        <td>${ txp.installment_number }</td>
                        <td>${ payment_date }</td>
                        <td>${ payment_serie }</td>
                        <td>${ payment_serie_folio}</td>
                        <td>${ translateAndReplace(`neutral_words.${tax_payment.status}`).toUpperCase() }</td>
                        <td>${ txp.currency }</td>
                        <td>${ removeUnnecessaryDecimal(tax_payment.exchange_rate) }</td>
                        <td>${ formatBanxicoCurrency(txp.previous_balance, invoice_currency) } </td>
                        <td>${ formatBanxicoCurrency(reconverted_amount_paid, txp.currency) }</td>
                        <td><div class='btn-group'>
                            <button type='button'
                                class='mx-1 btn btn-outline-secondary dropdown-toggle fixed-width no-caret'
                                data-toggle='dropdown' data-boundary="window" aria-haspopup='true' aria-expanded='false'
                            >
                                <i class='fas fa-ellipsis-v'></i>
                            </button>
                            <div class='dropdown-menu dropdown-menu-right' style="z-index: 2;">
                                ${buttons.join('')}
                            </div>
                        </div></td>
                    </tr>
                `;
            });
        } else {
            history_records += `
                <tr><td colspan="10">
                    ${translateAndReplace('data_tables.sEmptyTable')}
                </td></tr>
            `;
        }

        $('#tax-payment-history-table-body').html(history_records);
    }

    function resetPaymentHistory() {
      //* Reset Inputs
        $('#invoice_tax_payment_trigger').val("");

      //* Reset Texts
        // Receiver
        $('#receiver_tax_id, #receiver_legal_name, #receiver_tax_system').text("");

        // Invoices
        $('#invoice_certification_date, #invoice_serie, #invoice_sat_uuid').text("");
        $('#invoice_total, #invoice_total_paid, #invoice_remaining_balance').text( formatCurrency("0.00") );

        $('#invoice_currency').text("MXN");
        $('#invoice_exchange_rate').text( formatCurrency("1.00") );

      //* Reset Tables
        $('#tax-payment-history-table-body').html("");
    }

    function displaySubstituteUuidExt(input) {
        const selected_reason = input.value;
        $("#cancellation_substitute_block_ext").toggle(selected_reason === "01");
    }

    function displayPaymentButton(status) {
        $('#invoice_tax_payment_trigger')
            .prop('disabled', status.reached)
            .text(
                status.reached
                    ? "{{ __('entity_forms')['tax_payment']['payment_history']['disable_submit_button'] }}"
                    : "{{ __('entity_forms')['tax_payment']['payment_history']['submit_button'] }}"
            );
    }
</script>
