<style>
  /* Modals */
    .modal-xl {
        max-width: 72% !important;
    }

  /* Text */
    .section-title {
        font-weight: 600 !important;
        font-size: 1.2rem !important;
        border-bottom: 1px solid #0d68897a !important;
        width: 45%;
        padding-left: 0.5rem;
    }

  /* Tables */
    th {
        vertical-align: middle !important;
    }

  /* Decorators */
    .border-left-tiny {
        border-left: 0.8px solid #b5b6b7 !important;
    }

    .full-bottom-border {
        width: 100%;
    }
</style>

{{-- Modal --}}
@php
    use App\Enums\Invoicing\QuantityApplicationType;
@endphp

<div id="taxProdServFormModal" class="modal fade" role="dialog">
    <div class="modal-dialog modal-xl">
        <div class="modal-content special-modal-body">

            {{-- Headers --}}
            <div class="pt-4 pb-3 pl-3 modal-header">
                {{-- Titles --}}
                <div class="col-11">
                    <h4 class="text-uppercase modal_title" style="font-weight: 800; color: #0d6889c9; font-size: 1.8rem;"></h4>
                </div>

                {{-- Close Buttons --}}
                <div class="col-1">
                    <button type="button" class="pt-2 close" data-dismiss="modal" aria-label="Close" style="float: none">
                        <span>
                            <img src="{{ asset('icons/close_modal.svg') }}" aria-hidden="true"
                                style="width: 2.5rem;">
                        </span>
                    </button>
                </div>
            </div>

            {{-- Form --}}
            <form method="post" id="tax_prod_serv_form"
                autocomplete="off" enctype="multipart/form-data"
            >@csrf

                {{-- Content --}}
                <div
                    class="pt-4 pb-1 modal-body"
                    style="max-height: 695px;overflow-y: auto;"
                >

                    {{-- Product/Service Data --}}
                    <section class="align-items-start d-flex">

                        {{-- Local Data --}}
                        <div class="px-3 pb-1 col-6">
                            {{-- Header --}}
                            <p class="mt-2 mb-3 text-muted section-title">
                                {{ __('entity_forms')['tax_prod_serv']['sections']['local_data'] }}
                            </p>

                            {{-- SKU --}}
                            <div class="form-group row">
                                <label for="sku" class="text-center col-md-3">
                                    SKU
                                </label>
                                <div class="col-md-9">
                                    <input type="text" name="sku" id="sku" required
                                        minlength="3" maxlength="16" class="form-control"
                                        placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['sku'] }}"/>
                                </div>
                            </div>

                            {{-- Nombre --}}
                            <div class="form-group row">
                                <label for="name" class="text-center col-md-3">
                                    {{ __('entity_fields')['common']['name'] }}
                                </label>
                                <div class="col-md-9">
                                    <input type="text" name="name" id="name" required
                                        maxlength="150" class="form-control"
                                        placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['name'] }}"/>
                                </div>
                            </div>

                            {{-- Descripción --}}
                            <div class="pl-3 mb-3 form-group">
                                <h6 class="text-capitalize">
                                    {{ __('entity_fields')['tax_prod_serv']['description'] }} ({{ __('neutral_words')['optional'] }})
                                </h6>

                                <textarea name="description" id="description" class="p-2 form-control"
                                    rows="3" placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['description'] }}">{{ __('neutral_words')['none'] }}</textarea>
                            </div>
                        </div>

                        {{-- Fiscal Data --}}
                        <div class="px-3 col-6 border-left-tiny">

                            {{-- Header --}}
                            <p class="mt-2 mb-3 text-muted section-title">
                                {{ __('entity_forms')['tax_prod_serv']['sections']['fiscal_data'] }}
                            </p>

                            {{-- Clave Fiscal --}}
                            <div class="form-group row">
                                <label for="prod_serv_key" class="pt-2 text-center col-md-4">
                                    {{ __('entity_fields')['tax_prod_serv']['prod_serv_key'] }}
                                </label>
                                <div class="col-md-8">
                                    <select name="prod_serv_key" id="prod_serv_key" required
                                        class="form-control"
                                    ></select>
                                </div>
                            </div>

                            {{-- Descripción (SAT) --}}
                            <div class="form-group row">
                                <label for="sat_description" class="text-center col-md-4">
                                    {{ __('entity_fields')['tax_prod_serv']['description'] }}
                                </label>
                                <div class="col-md-8">
                                    <input type="text" name="sat_description" id="sat_description"
                                        class="form-control" required readonly
                                        placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['sat_description'] }}"/>
                                </div>
                            </div>

                            {{-- Unidad de Medida --}}
                            <div class="form-group row">
                                <label for="unit_key" class="text-center col-md-4">
                                    {{ __('entity_fields')['tax_prod_serv']['unit_key'] }}
                                </label>
                                <div class="col-md-8">
                                    <select name="unit_key" id="unit_key" required
                                        class="form-control"
                                    ></select>
                                </div>
                            </div>

                            {{-- Objeto de Impuesto --}}
                            <div class="form-group row">
                                <label for="object_tax" class="text-center col-md-4">
                                    {{ __('entity_fields')['tax_prod_serv']['object_tax'] }}
                                </label>
                                <div class="col-md-8">
                                    <select
                                        name="object_tax" id="object_tax"
                                        class="form-control" onchange="calculateTotal()"
                                    >
                                        @foreach ($tax_objects_catalog as $tax_object)
                                            <option value="{{ $tax_object->item_key }}">{{ $tax_object->item_key }} - {{ $tax_object->label }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            {{-- Precio unitario --}}
                            <div class="form-group row">
                                <label for="unit_price" class="text-center col-md-4">
                                    {{ __('entity_fields')['tax_prod_serv']['unit_price_short'] }}
                                </label>
                                <div class="col-md-8">
                                    <input type="number" name="unit_price" id="unit_price" required
                                        min='0.0' step="0.0000001" value="0.0" class="form-control"
                                        onchange="roundDecimals(this, 6); calculateTotal()"
                                        placeholder="{{ \App\Helpers\Formats\FormatCurrencyHelper::currencyPlaceHolder() }}"/>
                                </div>

                                {{-- Indications --}}
                                <small class="pt-2 pl-2 text-center offset-1 indications">
                                    <i class="fas fa-info-circle"></i> &nbsp;&nbsp;
                                    {{ __('entity_fields')['tax_prod_serv']['unit_price'] }}
                                    (<span class="font-weight-bold" id="pu_indications">{{ __('entity_forms')['tax_prod_serv']['without_taxes'] }}</span>)
                                </small>
                            </div>

                        </div>

                    </section>

                    {{-- Tax Breakdown --}}
                    <section class="px-3 mb-5" id="tax_breakdown_block">
                        {{-- Header --}}
                        <p class="mt-2 text-muted section-title full-bottom-border">
                            {{ __('entity_forms')['tax_prod_serv']['sections']['tax_breakdown'] }}
                        </p>

                        {{-- Inner Forms --}}
                        <div class="pt-3 row justify-content-center" id="tax_breakdown_inner_form">

                            {{-- Tipo de Impuesto --}}
                            <div class="mx-2 form-group row col-4">
                                <label for="tax_type_recorder" class="pt-2 text-center col-md-6">
                                    {{ __('entity_fields')['tax_prod_serv']['tax_profile']['tax_name'] }}
                                </label>
                                <div class="col-md-6">
                                    <select id="tax_type_recorder" class="form-control">
                                        <option value="" disabled selected>- {{ __('common_actions')['select'] }} -</option>

                                        @foreach ($tax_types_catalog as $tax_type)
                                            <option value="{{ $tax_type->item_key }}">{{ $tax_type->item_key }} - {{ $tax_type->label }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            {{-- Tasa o Cuota --}}
                            <div class="mx-2 form-group row col-4">
                                <label for="tax_rate_recorder" class="pt-2 text-center col-md-6">
                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['rate'] }}
                                </label>
                                <div class="col-md-6">
                                    <select id="tax_rate_recorder" class="form-control">
                                        <option value="" disabled selected>- {{ __('common_actions')['select'] }} -</option>

                                        @foreach ($tasa_o_cuotas_catalog as $tasa_o_cuota)
                                            <option value="{{ $tasa_o_cuota->item_key }}">
                                                {{ \App\Helpers\Formats\QuantityConverterHelper::str_toStrPercentage($tasa_o_cuota->label,2) }} {{-- ({{ $tasa_o_cuota->label }}) --}}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>

                            {{-- Inner Submit Button --}}
                            <div class="pt-1 mx-2 col-2">
                                <button type="button" id="tax_recorder_button" onclick="addTaxProfile()"
                                    class="btn-secondary btn btn-block"
                                >
                                    ✚ {{ __('common_actions')['add'] }}
                                </button>
                            </div>

                        </div>

                        {{-- Tax Profile Summary --}}
                        <div class="pt-3 mx-auto col-11">
                            <div class="cardtitle-nota">
                                <div class="table-responsive" id="profile-taxes-table">
                                    <table
                                        class="table mb-0 text-center align-middle table-borderless"
                                        style="max-height: 18.5em !important; overflow-y: auto;"
                                    >

                                        {{-- Header --}}
                                        <thead class="sticky-top" id="profile-taxes-table-header">
                                            <tr>
                                                <th scope="col" class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['tax_prod_serv']['tax_profile']['tax_type'] }}
                                                </th>
                                                <th scope="col"class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['tax_prod_serv']['tax_profile']['tax_name'] }}
                                                </th>
                                                <th scope="col" class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['tax_prod_serv']['tax_profile']['tax_rate'] }}
                                                </th>
                                                <th scope="col" width="20%" class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['common']['actions'] }}
                                                </th>
                                            </tr>
                                        </thead>

                                        {{-- Body --}}
                                        <tbody id="profile-taxes-table-body"></tbody>

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

                    </section>

                    {{-- Local Tax Breakdown --}}
                    <section class="px-3 mb-4">
                        {{-- Header --}}
                        <p class="mt-2 text-muted section-title full-bottom-border">
                            {{ __('entity_forms')['tax_prod_serv']['sections']['local_tax_breakdown'] }}
                        </p>

                        {{-- Inner Forms --}}
                        <div class="pt-1 row justify-content-center">

                            {{-- Nombre --}}
                            <div class="px-2 form-group row col-12">
                                <label for="local_tax_name" class="pt-2 text-center col-md-3">
                                    {{ __('entity_fields')['tax_prod_serv']['local_tax_profile']['tax_name'] }}
                                </label>

                                <div class="col-md-9">
                                    <input type="text" id="local_tax_name"
                                        minlength="1" maxlength="150" class="form-control tax-text"
                                        placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_name'] }}"/>
                                </div>
                            </div>

                            {{-- Forma de Aplicación --}}
                            <div class="px-2 form-group row col-5">
                                <label for="local_tax_application_form" class="pt-2 text-center col-md-6">
                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_application_form'] }}
                                </label>

                                <div class="col-md-6">
                                    <select id="local_tax_application_form" class="form-control">
                                        <option value="{{ QuantityApplicationType::Percentage->value }}">Porcentaje (%)</option>
                                        {{-- <option value="{{ QuantityApplicationType::Amount->value }}">Monto ({{ session('currency.symbol') }})</option> --}}
                                    </select>
                                </div>
                            </div>

                            {{-- Importe --}}
                            <div class="px-2 form-group row col-3">
                                <label for="local_tax_import" class="pt-2 text-center col-md-5">
                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_import'] }}
                                </label>

                                <div class="col-md-7">
                                    <input type="number" id="local_tax_import"
                                        min='0.0' step="0.000001" value="0.000000" class="form-control"
                                        onchange="roundDecimals(this, 6)"
                                        placeholder="0.000000"/>
                                </div>
                            </div>

                            {{-- Tipo de Aplicación --}}
                            <div class="px-2 form-group row col-4">
                                <label for="local_tax_type_application" class="pt-2 text-center col-md-6">
                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_application_type'] }}
                                </label>

                                <div class="col-md-6">
                                    <select id="local_tax_type_application" class="form-control">
                                        <option value="tr">{{ __("neutral_words")['transfer'] }}</option>
                                        <option value="rt">{{ __("neutral_words")['withholding'] }}</option>
                                    </select>
                                </div>
                            </div>

                            {{-- Inner Submit Button --}}
                            <div class="pt-2 col-3">
                                <button type="button" id="tax_recorder_button" onclick="addLocalTaxProfile()"
                                    class="btn-secondary btn btn-block"
                                >
                                    ✚ {{ __('common_actions')['add'] }}
                                </button>
                            </div>

                        </div>

                        {{-- Local Tax Profile Summary --}}
                        <div class="pt-4 mx-auto col-11">
                            <div class="cardtitle-nota">
                                <div class="table-responsive" id="profile-local-taxes-table">
                                    <table
                                        class="table mb-0 text-center align-middle table-borderless"
                                        style="max-height: 18.5em !important; overflow-y: auto;"
                                    >

                                        {{-- Header --}}
                                        <thead class="sticky-top" id="profile-local-taxes-table-header">
                                            <tr>
                                                <th scope="col"class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['tax_prod_serv']['local_tax_profile']['tax_name'] }}
                                                </th>
                                                <th scope="col" class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['tax_prod_serv']['local_tax_profile']['tax_rate'] }}
                                                </th>
                                                <th scope="col" width="20%" class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['common']['type'] }}
                                                </th>
                                                <th scope="col" width="15%" class="border-harsi text-uppercase">
                                                    {{ __('entity_fields')['common']['actions'] }}
                                                </th>
                                            </tr>
                                        </thead>

                                        {{-- Body --}}
                                        <tbody id="profile-local-taxes-table-body"></tbody>

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

                    </section>

                </div>

                {{-- Buttons --}}
                <div class="modal-footer">

                    <section class="px-3 text-center w-100">
                        <h3>Total</h3>
                        <h4 id="total_illusionary"></h4>
                        <input type="hidden" id="total" name="total" value="0.0">
                    </section>

                    <section class="px-3 pt-2 text-center w-100">
                        {{-- Hidden Data --}}
                        <input type="hidden" name="hidden_id" id="hidden_id" />

                        {{-- Action Controls --}}
                        <input type="hidden" id="action"/>
                        <button id="action_message" type="submit" class="p-1 btn boton">
                            {{ __('common_actions')['add'] }}
                        </button>
                    </section>

                </div>
            </form>

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

{{-- Scripts --}}
<script>
  //* Constants
    // Catalogs
    const tax_types_keys = {
        isr: '001',
        iva: '002',
        ieps: '003',
    }
    const format_types_keys = {
        withholding: 'rt',
        transfer: 'tr',
    }

    const quantity_application_types = {
        percentage : "{{ QuantityApplicationType::Percentage->value }}",
        amount : "{{ QuantityApplicationType::Amount->value }}",
    }

    // Tax Summary Control
    window.table_summary = {
        taxes : {
            iva : false,
            ieps : false,
        },
        withholding_taxes : {
            iva : false,
            isr : false,
        },
    }

  //* CRUD Control
    $(document).ready(function () {
      //- On close ProdServ form
        $('#taxProdServFormModal').on('hide.bs.modal', function () {
            document.activeElement.blur();
        });

      //- On change important texts
        $('.tax-text').on('input change keyup paste', function () {
            $(this).val($(this).val().toUpperCase());
        });

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

        $('#profile-local-taxes-table').on('scroll', function () {
            if ($(this).scrollTop() > 30) {
                $('#profile-local-taxes-table-header').addClass('glass-background');
            } else {
                $('#profile-local-taxes-table-header').removeClass('glass-background');
            }
        });

      // Open For Create
        $('#create_record').click(function () {
            // Modal Titles
            $('.modal_title').text("{{ __('entities')['invoicing']['prod_serv'] }}");

            // Action Controls
            $('#action_message').text("{{ __('common_actions')['add'] }}");
            $('#action').val("Store");

            // Form Cleaning
            $('#tax_prod_serv_form')[0].reset();
            $('#prod_serv_key, #unit_key').val('').trigger('change')
            $('#object_tax').val("02");
            resetTable({reset_block: true, reset_total: true});
            resetLocalTaxTable();
            $('#taxProdServFormModal').modal('show');
        });

      // Open For Edit
        $(document).on('click', '.edit', function () {
            var id = $(this).attr('id');

            // Reset Form
            resetTable({reset_block: true, reset_total: true});
            resetLocalTaxTable();
            $('#tax_prod_serv_form')[0].reset();
            $('#prod_serv_key, #unit_key').val('').trigger('change');

            // Seed Form
            $.ajax({
                url: `/invoicing/products-and-services/${id}/edit`,
                dataType: "json",

                success: async function (result) {
                    const data = result.data;
                    console.log(data);

                  // Fill Fields
                    $('#hidden_id').val(data.id);

                    $('#sku').val(data.sku);
                    $('#name').val(data.name);
                    $('#description').val(data.description);

                    preloadSelect2('#prod_serv_key', data.prod_serv_key, {fetchUrl: "{{ route('catalogs.prod-serv.find') }}"});
                    $('#sat_description').val(data.sat_description);
                    preloadSelect2('#unit_key', data.unit_key, {fetchUrl: "{{ route('catalogs.units.find') }}"});

                    $('#object_tax').val(data.object_tax).trigger('change');

                  // Fill Federal Taxes Table
                    const taxes = data.tax_profile.taxes;
                    const wh_taxes = data.tax_profile.withholding_taxes;

                        if(taxes.iva !== null && data.object_tax != "04") // IVA Trasladado (Solo se dibuja si el ObjetoImpuesto no es 04-Si objeto, no impuestos)
                            await buildTaxRow(tax_types_keys.iva, taxes.iva.rate, {show_toast: false});
                        if(taxes.ieps !== null) // IEPS Trasladado
                            await buildTaxRow(tax_types_keys.ieps, taxes.ieps.rate, {show_toast: false});

                        if(wh_taxes.isr !== null) // ISR Retenido
                            await buildTaxRow(tax_types_keys.isr, wh_taxes.isr.rate, {show_toast: false});
                        if(wh_taxes.iva !== null) // IVA Retenido
                            await buildTaxRow(tax_types_keys.iva, wh_taxes.iva.rate, {is_iva_tr: false, show_toast: false});

                  // Fill Local Taxes Table
                    const local_taxes = data.local_tax_profile.transferred;
                    local_taxes.forEach(ltx => {
                        buildLocalTaxRow(ltx.name, "tr", ltx.rate, {tax_application_form = quantity_application_types.percentage, show_toast = false} = {})
                    });

                    const wh_local_taxes = data.local_tax_profile.withheld;
                    wh_local_taxes.forEach(ltx => {
                        buildLocalTaxRow(ltx.name, "rt", ltx.rate, {tax_application_form = quantity_application_types.percentage, show_toast = false} = {})
                    });


                  // Fill Totals and Prices
                    $('#total_illusionary').text(data.total);
                    $('#total').val(data.total);

                    $('#unit_price').val(data.unit_price).trigger('change');

                  // Modal Titles
                    $('.modal_title').text("{{ __('entities')['invoicing']['prod_serv'] }}");

                  // Display Modal
                    $('#action').val("Update");
                    $('#action_message').text("{{ __('common_actions')['update'] }}");
                    $('#taxProdServFormModal').modal('show');
                }
            })
        });

      // Open For Delete
        $(document).on('click', '.delete', function () {
            var id = $(this).attr('id');
            Swal.fire({
                type: 'warning',
                title: "{{ __('common_responses_and_messages')['confirm_deletion'] }}",
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['confirm_deletion'] }}",
                confirmButtonColor: `#0d6889`,
                showCancelButton: true,
                cancelButtonText: `{{ __('common_actions')['cancel'] }}`,
                cancelButtonColor: `#c82333`
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.value) {
                    $.ajax({
                        url: `/invoicing/products-and-services/${id}/destroy`,
                        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                        type: 'DELETE',
                        success: function (data) {
                            setTimeout(function () {
                                Swal.fire(
                                    "{{ __('common_responses_and_messages')['deleted'] }}",
                                    "{{ __('common_responses_and_messages')['deleted_successfully'] }}",
                                    'success'
                                );
                                $('#tax_prod_servs_table').DataTable().ajax.reload(null, false);
                            }, 200);
                        }
                    });
                }
            });
        });

      // Submit Form
        $('#tax_prod_serv_form').on('submit', function (event) {
            event.preventDefault();

            if ($('#action').val() == 'Store') {
                $.ajax({
                    url: "{{ route('tax-prod-servs.store') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function (data) {
                        Swal.fire(
                            "{{ __('common_responses_and_messages')['success'] }}",
                            "{{ __('common_responses_and_messages')['created_successfully'] }}",
                            'success'
                        );

                        $('#tax_prod_serv_form')[0].reset();
                        $('#tax_prod_servs_table').DataTable().ajax.reload(null, false);
                        $('#taxProdServFormModal').modal('hide');
                    },

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

                        // Record limit reached
                        if (response.limit_message) {
                            Swal.fire({
                                title: "{{ __('common_responses_and_messages')['rejected_action'] }}",
                                text: response.limit_message,
                                type:'error'
                            });

                            $('#taxProdServFormModal').modal('hide');
                            return;
                        }

                        // Validator Errors
                        const errors = response.errors;
                        Object.keys(errors).forEach(key => {
                            errors[key].forEach(message => showToast(message, "#C34808", "#78350F"));
                        });

                        return;
                    },
                })
            }

            if ($('#action').val() == "Update") {
                $.ajax({
                    url: "{{ route('tax-prod-servs.update') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function (data) {
                        Swal.fire(
                            "{{ __('common_responses_and_messages')['success'] }}",
                            "{{ __('common_responses_and_messages')['updated_successfully'] }}",
                            'success'
                        );

                        $('#tax_prod_serv_form')[0].reset();
                        $('#taxProdServFormModal').modal('hide');
                        $('#tax_prod_servs_table').DataTable().ajax.reload(null, false);
                    },

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

                        // Validator Errors
                        const errors = response.errors;
                        Object.keys(errors).forEach(key => {
                            errors[key].forEach(message => showToast(message, "#C34808", "#78350F"));
                        });

                        return;
                    },
                });
            }
        });
    });

  //* Seed Form Data
    $(function () {
      //* SAT Catalogs
        // Productos y Servicios
        $('#prod_serv_key').select2({
            placeholder: "{{ __('common_actions')['select'] }}...",
            allowClear: false,
            minimumInputLength: 3,
            dropdownParent: $('#taxProdServFormModal'),

            ajax: {
                url: "{{ route('catalogs.prod-serv.search') }}",
                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
            },
            width: '100%',
        });

        $('#prod_serv_key').on('select2:select', function (e) {
            const prod_serv_name = e.params.data.full_text || e.params.data.text || ""; // Extract ProdServ Name
            $('#sat_description').val(prod_serv_name);
        });

        // Unidades de Medida
        $('#unit_key').select2({
            placeholder: "{{ __('common_actions')['select'] }}...",
            allowClear: false,
            minimumInputLength: 2,
            dropdownParent: $('#taxProdServFormModal'),

            ajax: {
            url: "{{ route('catalogs.units.search') }}",
            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
            },
            width: '100%'
        });

      //* Taxes
        $(function () {
            $('#object_tax').on('change', defineTaxProfile);
        });
    });

  //* Support Function

    // Interactions
        function defineTaxProfile() {
          //* Control Data
            const value = $(this).val();

            // Visual Controls
            const $pu_indications   = $('#pu_indications');
            const $tax_block = $('#tax_breakdown_block');
            const $tax_form  = $('#tax_breakdown_inner_form');
            const $tax_form_inputs = $('#tax_recorder_button, #tax_type_recorder, #tax_rate_recorder');

            // Cases
            const wt_text = "{{ __('entity_forms')['tax_prod_serv']['without_taxes'] }}";
            const wto_text = "{{ __('entity_forms')['tax_prod_serv']['with_taxes'] }}";
            const cases = {
                "01": { ind: wt_text, block: false, form: false, iva0: false },
                "02": { ind: wt_text, block: true,  form: true,  iva0: false },
                "03": { ind: wto_text, block: false, form: false, iva0: false },
                "04": { ind: wt_text, block: true,  form: false, iva0: true  }
            };

          //* Define States
            const tax_object = cases[value] || cases["01"];

            $pu_indications.text(tax_object.ind);
            tax_object.block ? $tax_block.show() : $tax_block.hide();
            tax_object.form  ? $tax_form.show()  : $tax_form.hide();
            $tax_form_inputs.prop('disabled', !tax_object.form);

            // reset de tabla
            resetTable()

            // Case 04: Insertar IVA 0% una sola vez
            if (tax_object.iva0) setNullTaxes();

            launchSwalToast(
                'success',
                "{{ __('entity_forms')['tax_prod_serv']['messages']['tax_table_updated'] }}",
            );
        }

    // Totals
        function calculateTotal() {
          //* Control Variables
            // Price control
            const unit_price = parseFloat($('#unit_price').val());
            let total_price = unit_price;

            // Accumulators Control
            let ieps_transferred = 0.0; // 003 IEPS (trasladado)
            let iva_transferred  = 0.0; // 002 IVA trasladado
            let iva_withheld     = 0.0; // 002 IVA retenido
            let isr_withheld     = 0.0; // 001 ISR retenido

            let local_transfers   = 0.0; // Trasladados locales (Incrementan el Total)
            let local_withholdings = 0.0; // Trasladados locales (Decrementan el Total)

            // Visual controls
            const $tax_tbody = $('#profile-taxes-table-body'); // Body of Table (Federal Taxes)
            const $local_tax_tbody = $('#profile-local-taxes-table-body'); // Body of Table (Local Taxes)

          //* Calculate total with Federal Taxes (SAT)
            // 1) IEPS trasladado (VAT base)
                const $ieps_tr = $tax_tbody.find('input[name="tax_summary[]"][value="003"]').closest('tr');
                const ieps_app = $ieps_tr.find('input[name="tax_application_summary[]"]').val();

                if (ieps_app === format_types_keys.transfer) {
                    const ieps_quote = parseFloat($ieps_tr.find('input[name="rate_quotes_summary[]"]').val()) || 0;
                    ieps_transferred = unit_price * ieps_quote; // IEPS % on base price
                }
                $ieps_tr.find('input[name="tax_charges_summary[]"]').val(ieps_transferred.toFixed(6));


            // 2) Calculate VAT on the basis that includes IEPS
                const iva_base = unit_price + ieps_transferred; // VAT base = UnitPrice + IEPS trasladado
                const $iva_rows = $tax_tbody.find('tr:has(input[name="tax_summary[]"][value="002"])');

                const $iva_transfer_tr  = $iva_rows.filter(function () { // Trasladado
                    return $(this).find('input[name="tax_application_summary[]"]').val() === format_types_keys.transfer;
                });
                const $iva_withheld_tr  = $iva_rows.not($iva_transfer_tr); // Retenido

                const iva_transfer_quote = parseFloat($iva_transfer_tr.find('input[name="rate_quotes_summary[]"]').val()) || 0;
                const iva_withheld_quote = parseFloat($iva_withheld_tr.find('input[name="rate_quotes_summary[]"]').val()) || 0;

                iva_transferred = iva_base * iva_transfer_quote;
                iva_withheld    = iva_base * iva_withheld_quote;

                $iva_transfer_tr.find('input[name="tax_charges_summary[]"]').val(iva_transferred.toFixed(6));
                $iva_withheld_tr.find('input[name="tax_charges_summary[]"]').val(iva_withheld.toFixed(6));

            // 3) Calculate income tax withheld on UnitPrice
                const $isr_tr = $tax_tbody.find('input[name="tax_summary[]"][value="001"]').closest('tr');
                const isr_app  = $isr_tr.find('input[name="tax_application_summary[]"]').val();

                if (isr_app !== format_types_keys.transfer) {
                    const isr_quote = parseFloat($isr_tr.find('input[name="rate_quotes_summary[]"]').val()) || 0;
                    isr_withheld = unit_price * isr_quote;
                }
                $isr_tr.find('input[name="tax_charges_summary[]"]').val(isr_withheld.toFixed(6));

            // 4) Total: precio unitario + IEPS + IVA trasladado - IVA retenido - ISR retenido
            total_price = unit_price + ieps_transferred + iva_transferred - iva_withheld - isr_withheld;

          //* Calculate total with Local Taxes
            $local_tax_tbody.find('tr').each(function () {
                const $row = $(this);
                const rate = parseFloat($row.find('input[name="local_rate_quotes_summary[]"]').val()) || 0;
                const application_type = $row.find('input[name="local_tax_application_summary[]"]').val();

                // Calcular el importe del impuesto local sobre el total obtenido por los impuestos federales
                const amount = parseFloat((unit_price * (rate/100)).toFixed(6));
                $row.find('input[name="local_tax_charges_summary[]"]').val(amount.toFixed(6));

                // Asignar a su respectiva categoría
                if (application_type === format_types_keys.transfer) {
                    local_transfers += amount;
                } else if (application_type === format_types_keys.withholding) {
                    local_withholdings += amount;
                }
            });

            // Aplica impuestos locales el Total (sumas traslados, restas retenciones)
            total_price = total_price + local_transfers - local_withholdings;

          //* Render and Save Total
            total_price = removeUnnecessaryDecimal(total_price.toFixed(6));
            $('#total_illusionary').text( formatCurrency( total_price) );
            $('#total').val( total_price);
        }

    // Tax Profile Table Interactions
      // Dynamic Content
        function resetTable({reset_block = false, reset_total = false} = {}) {
            // Clean Table Content
            $('#profile-taxes-table-body').empty();

            // Reset Tax Summary
            window.table_summary = {
                taxes : {
                    iva : false,
                    ieps : false,
                },
                withholding_taxes : {
                    iva : false,
                    isr : false,
                },
            }

            // Reset Total
            if (reset_total) {
                $('#total_illusionary').text( formatCurrency("0.00") );
                $('#total').val(0.00);
            }

            // Reset Tax Block visualization
            if (reset_block){
                $('#pu_indications').text("Sin Impuestos");
                $('#tax_breakdown_block').show();
                $('#tax_breakdown_inner_form').show();
                $('#tax_recorder_button, #tax_type_recorder, #tax_rate_recorder').prop('disabled', false);
            }
        }

        async function setNullTaxes() {
            const tax_type = tax_types_keys.iva;
            const tax_rate = {{ $tasa_o_cuotas_catalog[0]['item_key'] }};
            buildTaxRow(tax_type, tax_rate, {show_toast: false, display_actions: false});
        }

      // Form Interactions
        // Base
        async function addTaxProfile() {
          // Validate Data
            $('#tax_type_recorder, #tax_rate_recorder').attr('required', true); // Add required to TaxForm
            if(!validateTaxForm()) {
                setTimeout(() => {
                    $('#tax_type_recorder, #tax_rate_recorder').attr('required', false); // Remove required to TaxForm
                }, 1500);

                return; // Stop function
            }
            $('#tax_type_recorder, #tax_rate_recorder').attr('required', false); // Remove required to TaxForm

          // Build Row
            // Extract Values
            const tax_type = $('#tax_type_recorder').val();
            const tax_rate = $('#tax_rate_recorder').val();

            // If tax type is IVA, chose format
            let is_iva_tr = true;

            if (tax_type === tax_types_keys.iva) {
                const { value: ivaType } = await Swal.fire({
                    type: "question",
                    html: `
                        <p class="mb-0 harsi-color ota-indications">
                            ${translateAndReplace('entity_forms.tax_prod_serv.select_vat_type')}
                        </p>
                    `,

                    showCancelButton: true,
                    confirmButtonText: "{{ __('common_actions')['accept'] }}",
                    cancelButtonText: "{{ __('common_actions')['cancel'] }}",

                    input: 'select',
                    inputOptions: {
                        tr: "{{ __('neutral_words')['transfer'] }}",
                        rt: "{{ __('neutral_words')['withholding'] }}",
                    },
                    inputValidator: (value) => {
                        return new Promise((resolve) => {
                            if (value) {
                                resolve()
                            } else {
                                resolve("{{ __('validation.required', ['attribute' => '']) }}")
                            }
                        })
                    },
                });

                if (!ivaType) { // Si el usuario cancela el Swal, abortamos todo el proceso
                    avoidTaxRegistration();
                    return;
                }

                if (ivaType === 'rt') is_iva_tr = false;
            }

            // Build row and re-calculate total
            await buildTaxRow(tax_type, tax_rate, {is_iva_tr});
            calculateTotal();

          // Reset InnerForm
            $('#tax_type_recorder, #tax_rate_recorder').val('');
        }

        function removeTaxRow(row) {
          // Obtenemos la fila a eliminar
            const row_to_delete = $(row).closest('tr');

          // Actualizamos el Tax Summary
            const tax_application = row_to_delete.find('input[name="tax_application_summary[]"]').val(); // ¿Retención(rt) o Traslado(tr)?
            const tax_type_key = row_to_delete.find('input[name="tax_summary[]"]').val(); // Key del Impuesto (SAT Catalog)
            const tax_type = Object.keys(tax_types_keys).find(key => tax_types_keys[key] === tax_type_key); // Nombre del Impuesto (SAT Catalog)

            window.table_summary[tax_application === "tr" ? "taxes" : "withholding_taxes"][tax_type] = false;

          // Eliminamos Fila
            row_to_delete.remove(); // Eliminar Fila
            calculateTotal(); // Re-calcular Total

            launchSwalToast(
                'success',
                "{{ __('common_responses_and_messages')['deleted_successfully'] }}",
            );
        }

        function validateTaxForm() {
            // Inputs to Validate (ID)
            const tax_form_inputs = ['#tax_type_recorder', '#tax_rate_recorder'];

            // Validate each input
            for (const id of tax_form_inputs) {
                const input = $(id)[0];
                if (!input.checkValidity()) {
                    input.reportValidity();
                    input.focus();
                    return false; // Detiene la validación al primer error
                }
            }

            return true; // Si todos son válidos
        }

        // Complementary
        async function buildTaxRow(tax_type, rate_quote, {is_iva_tr = true, show_toast = true, display_actions = true} = {}) {
          //* Control Variables
            const tax_types = @json($tax_types_catalog);
            const tax_applications = {
                rt : `${translateAndReplace('neutral_words.withholding')} <input type="hidden" name="tax_application_summary[]" value="${format_types_keys.withholding}">`,
                tr : `${translateAndReplace('neutral_words.transfer')} <input type="hidden" name="tax_application_summary[]" value="${format_types_keys.transfer}">`,
            };
            let tax_application_col = "";

            switch (tax_type) {
                case tax_types_keys.isr: // ISR (Retención)
                  // Update Tax Summary Control
                    ({will_be_draw, has_been_replaced, new_status} = await controlTaxStatus(
                        format_types_keys.withholding,
                        tax_types_keys.isr,
                        window.table_summary.withholding_taxes.isr,
                    ));
                    window.table_summary.withholding_taxes.isr = new_status;

                  // Define select content
                    tax_application_col = tax_applications.rt;
                    break;

                case tax_types_keys.ieps: // IEPS (Traslado)
                  // Update Tax Summary Control
                    ({will_be_draw, has_been_replaced, new_status} = await controlTaxStatus(
                        format_types_keys.transfer,
                        tax_types_keys.ieps,
                        window.table_summary.taxes.ieps,
                    ));
                    window.table_summary.taxes.ieps = new_status;

                  // Define select content
                    tax_application_col = tax_applications.tr;
                    break;

                default:    // IVA (Traslado por defecto)
                  // Update Tax Summary Control
                    const iva_format_key = is_iva_tr ? "taxes" : "withholding_taxes";
                    const iva_format_type = is_iva_tr ? format_types_keys.transfer : format_types_keys.withholding;

                    ({will_be_draw, has_been_replaced, new_status} = await controlTaxStatus(
                        iva_format_type,
                        tax_types_keys.iva,
                        window.table_summary[iva_format_key].iva
                    ));
                    window.table_summary[iva_format_key].iva = new_status;

                  // Define select content
                        if(is_iva_tr) tax_application_col = tax_applications.tr;
                        if (!is_iva_tr) tax_application_col = tax_applications.rt;
                    break;
            }

          // Build and render row
            if(!will_be_draw) return;

            const tax_row = `
                <tr>
                    <td>
                        ${tax_application_col}
                    </td>
                    <td>
                        ${tax_types.find(i => i.item_key === tax_type)?.label || null}
                        <input type="hidden" name="tax_summary[]" value="${tax_type}">
                    </td>
                    <td>
                        ${strToStrPercentage(rate_quote)}
                        <input type="hidden" name="rate_quotes_summary[]" value="${rate_quote}">
                        <input type="hidden" name="tax_charges_summary[]" value="0.0">
                    </td>

                    <td>
                        ${!display_actions ? "-- -- --" : `
                            <button type="button" class="btn-eliminar btn btn-danger btn-sm" onclick="removeTaxRow(this)">
                                <i class='fas fa-trash'></i>
                            </button>
                        `}
                    </td>
                </tr>
            `;
            $('#profile-taxes-table-body').append(tax_row);

            if(show_toast)
                launchSwalToast(
                    'success',
                    has_been_replaced
                        ? "{{ __('common_responses_and_messages')['updated_successfully'] }}"
                        : "{{ __('common_responses_and_messages')['created_successfully'] }}",
                );
            return;
        }

        async function controlTaxStatus (format_type, tax_type, already_assigned = false) {
            if (!already_assigned) return {will_be_draw: true, has_been_replaced: false, new_status: true}; // Renderizar por primera vez el impuesto

          // ¿El usuario desea que el impuesto actual sea remplazado?
            const result = await Swal.fire({
                type: 'question',
                title: "{{ __('common_responses_and_messages')['existing_record'] }}",
                text: "{{ __('entity_forms')['tax_prod_serv']['messages']['existing_tax_type'] }}",
                showCancelButton: true,
                reverseButtons: true,
                confirmButtonText: "{{ __('common_actions')['approve'] }} {{ __('common_actions')['accept'] }}",
                cancelButtonText: "{{ __('common_actions')['cancel'] }}",
            });

            if (result.value) { // Remplazar el impuesto actual
                $('#profile-taxes-table-body tr').each(function () {
                    const tax_application = $(this).find('td:eq(0) input[name="tax_application_summary[]"]').val();
                    const tax_key = $(this).find('td:eq(1) input[name="tax_summary[]"]').val();

                    if (tax_application === format_type && tax_key === tax_type) {
                        removeTaxRow(this);
                        return false; // Stop cycle
                    }
                });

                return { will_be_draw: true, has_been_replaced: true , new_status: true};
            } else { // Cancelar registro
                avoidTaxRegistration();
                return { will_be_draw: false, has_been_replaced: false, new_status: already_assigned };
            }
        }

        function avoidTaxRegistration() {
            launchSwalToast(
                'warning',
                "{{ __('common_responses_and_messages')['cancelled_action'] }}",
            );

            $('#tax_type_recorder, #tax_rate_recorder').val('');
        }

    // Local Tax Profile
      // Dynamic Content
        function resetLocalTaxTable() {
            // Clean Table Content
            $('#profile-local-taxes-table-body').empty();

            // Reset Fields
            resetLocalTaxInputs();
        }

        function resetLocalTaxInputs() {
            $('#local_tax_import').val('0.0').trigger('change');
            $('#local_tax_name').val('');

            $('#local_tax_application_form').val(quantity_application_types.percentage);
            $('#local_tax_type_application').val("tr");
        }

      // Form Interactions
        // Base
        async function addLocalTaxProfile() {
          // Validate Data
            const $locaTaxFields = $('#local_tax_name, #local_tax_application_form, #local_tax_import, #local_tax_type_application');

            $locaTaxFields.attr('required', true); // Add required to TaxForm
            if(!validateLocalTaxForm()) {
                setTimeout(() => {
                    $locaTaxFields.attr('required', false); // Remove required to TaxForm
                }, 1500);
                return; // Stop function
            }
            $locaTaxFields.attr('required', false); // Remove required to TaxForm

          // Build Row
            // Extract Values
            const name = $('#local_tax_name').val();
            const tax_type_application = $('#local_tax_type_application').val();
            const tax_application_form = $('#local_tax_application_form').val();
            const tax_import = $('#local_tax_import').val();

            // Build row and re-calculate total
            await buildLocalTaxRow(name, tax_type_application, tax_import, {tax_application_form});
            calculateTotal();

          // Reset InnerForm
            resetLocalTaxInputs();
        }

        function removeLocalTaxRow(row) {
          // Obtenemos la fila a eliminar
            const row_to_delete = $(row).closest('tr');
            const tbody = row_to_delete.closest('tbody'); // TBody Correspondiente

          // Eliminamos Fila
            row_to_delete.remove(); // Eliminar Fila
            calculateTotal(); // Re-calcular Total

            launchSwalToast(
                'success',
                "{{ __('common_responses_and_messages')['deleted_successfully'] }}",
            );
        }

        function validateLocalTaxForm() {
            // Inputs to Validate (ID)
            const local_tax_form_inputs = [ '#local_tax_name', '#local_tax_application_form', '#local_tax_import', '#local_tax_type_application' ];

            // Validate each input
            for (const id of local_tax_form_inputs) {
                const input = $(id)[0];
                if (!input.checkValidity()) {
                    input.reportValidity();
                    input.focus();
                    return false; // Detiene la validación al primer error
                }
            }

            return true; // Si todos son válidos
        }

        // Complementary
        async function buildLocalTaxRow(name, tax_type_application, tax_import, {tax_application_form = quantity_application_types.percentage, show_toast = true, display_actions = true} = {}) {
          //* Control Variables
            const tax_applications = {
                rt : `${translateAndReplace('neutral_words.withholding')} <input type="hidden" name="local_tax_application_summary[]" value="${format_types_keys.withholding}">`,
                tr : `${translateAndReplace('neutral_words.transfer')} <input type="hidden" name="local_tax_application_summary[]" value="${format_types_keys.transfer}">`,
            };

          // Build and render row
            const local_tax_row = `
                <tr>
                    <td>
                        ${name}
                        <input type="hidden" name="local_tax_names_summary[]" value="${name}">
                    </td>

                    <td>
                        ${strToStrPercentage(tax_import, {is_low_decimal: false})}
                        <input type="hidden" name="local_rate_quotes_summary[]" value="${tax_import}">
                        <input type="hidden" name="local_tax_charges_summary[]" value="0.0">
                    </td>

                    <td>
                        ${tax_applications[tax_type_application]}
                    </td>

                    <td>
                        ${!display_actions ? "-- -- --" : `
                            <button type="button" class="btn-eliminar btn btn-danger btn-sm" onclick="removeLocalTaxRow(this)">
                                <i class='fas fa-trash'></i>
                            </button>
                        `}
                    </td>
                </tr>
            `;

            // Define if its first record
                const $tbody = $('#profile-local-taxes-table-body');
                const $firstTd = $tbody.find('tr:first').find('td:first');

                ($firstTd.length && $firstTd.attr('colspan'))
                    ? $tbody.html(local_tax_row) // Substitute default row message & Append row
                    : $tbody.append(local_tax_row); // Append row

            return;
        }

</script>
