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

{{-- Modal --}}
<div id="conceptFormModal" class="modal fade" tabindex="-1"
    role="dialog" aria-labelledby="modal-title" aria-hidden="true"
    data-bs-backdrop="static" data-bs-keyboard="false"
>
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content special-modal-body">

            {{-- Header --}}
            <div class="pt-4 pb-3 pl-3 modal-header">
                {{-- Titles --}}
                <div class="px-3 col-11">
                    <h4 class="text-uppercase visual-modal-title">
                        <span id="concept-modal-title-action">{{ __('common_actions.add') }}</span> Concepto
                    </h4>
                </div>

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

                </div>
            </div>

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

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

                    {{-- Product/Service Data --}}
                    <section class="accordion accordion-flush" id="accordion-fiscal-data">
                        <div class="bg-transparent accordion-item">

                            {{-- Title --}}
                            <div class="accordion-header" id="fiscal-data-unique-header">
                                <button type="button" class="bg-transparent accordion-button fs-5 secondary-accordion-button ps-0 pe-3"
                                    data-bs-toggle="collapse" data-bs-target="#fiscal-data-unique"
                                    aria-expanded="true" aria-controls="fiscal-data-unique"
                                >
                                    Datos Fiscales
                                </button>
                            </div>

                            {{-- Content --}}
                            <div id="fiscal-data-unique"
                                class="px-2 accordion-collapse collapse show row justify-content-center"
                                aria-labelledby="fiscal-data-unique-header"
                            ><div class="px-3 accordion-body" id="fiscal-data-concept-form">

                                {{-- Datos Fiscales --}}
                                <div class="px-1 mb-3 row justify-content-center">

                                    {{-- SKU --}}
                                    <div class="flex-shrink-0 px-3 col-6" id="sku_concept_block">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="sku" class="input-group-text disabled-fields-pale">
                                                    SKU
                                                </label>
                                            </div>

                                            <input type="text" id="sku" readonly disabled
                                                minlength="3" maxlength="16" class="form-control disabled-fields-pale"
                                                placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['sku'] }}"/>

                                                <input type="hidden" id="concept_prod_serv_id" name="concept_prod_serv_id" readonly>
                                        </div>
                                    </div>

                                    {{-- Clave Fiscal --}}
                                    <div class="flex-shrink-0 px-3 col-6">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_prod_serv_key" class="input-group-text">
                                                    {{ __('entity_fields')['tax_prod_serv']['prod_serv_key'] }} {!! $required_field !!}
                                                </label>
                                            </div>

                                            <select name="concept_prod_serv_key" id="concept_prod_serv_key" required
                                                class="form-control"
                                            ></select>
                                        </div>
                                    </div>

                                    {{-- Nombre (Local) --}}
                                    <div class="flex-shrink-0 px-3 col-6">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_name" class="input-group-text">
                                                    Nombre {!! $required_field !!}
                                                </label>
                                            </div>

                                            <input type="text" name="concept_name" id="concept_name" required
                                                class="form-control" placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['name'] }}"/>

                                        </div>
                                    </div>

                                    {{-- Descripción (SAT) --}}
                                    <div class="flex-shrink-0 px-3 col-6">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_sat_description" class="input-group-text disabled-fields-pale">
                                                    Descripción Fiscal {!! $required_field !!}
                                                </label>
                                            </div>

                                            <input type="text" name="concept_sat_description" id="concept_sat_description"
                                                class="form-control disabled-fields-pale" required readonly
                                                placeholder="{{ __('entity_forms')['tax_prod_serv']['placeholders']['sat_description'] }}"/>

                                        </div>
                                    </div>

                                    {{-- Objeto de Impuesto --}}
                                    <div class="flex-shrink-0 px-3 col-6">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_object_tax" class="input-group-text">
                                                    {{ __('entity_fields')['tax_prod_serv']['object_tax'] }} {!! $required_field !!}
                                                </label>
                                            </div>

                                            <select name="concept_object_tax" id="concept_object_tax" required
                                                class="form-control" onchange="calculateConceptTotal()"
                                            >
                                                @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>

                                </div>

                                {{-- Precios y Unidades --}}
                                <div class="px-3 mb-3 row justify-content-center">

                                    {{-- Unidad de Medida --}}
                                    <div class="flex-shrink-0 px-3 col-5">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_unit_key" class="input-group-text">
                                                    {{ __('entity_fields')['tax_prod_serv']['unit_key'] }} {!! $required_field !!}
                                                </label>
                                            </div>

                                            <select name="concept_unit_key" id="concept_unit_key" required
                                                class="form-control"
                                            ></select>
                                        </div>
                                    </div>

                                    {{-- Precio unitario --}}
                                    <div class="flex-shrink-0 px-3 col-4">
                                        <div class="mb-1 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_unit_price" class="input-group-text">
                                                    {{ __('entity_fields')['tax_prod_serv']['unit_price'] }} {!! $required_field !!}
                                                </label>
                                            </div>

                                            <input type="number" name="concept_unit_price" id="concept_unit_price" required
                                                min='0.0' step="0.0000001" value="0.0" class="form-control"
                                                onchange="roundDecimals(this, 6); calculateConceptTotal()"
                                                placeholder="{{ \App\Helpers\Formats\FormatCurrencyHelper::currencyPlaceHolder() }}"/>

                                        </div>

                                        <small class="text-center ps-5 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>

                                    {{-- Cantidad --}}
                                    <div class="flex-shrink-0 px-3 col-3">
                                        <div class="mb-1 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_quantity" class="input-group-text">
                                                    Cantidad {!! $required_field !!}
                                                </label>
                                            </div>

                                            <input type="number" name="concept_quantity" id="concept_quantity" required
                                                min='0.0' step="0.0000001" value="1.00" class="form-control"
                                                onchange="roundDecimals(this, 6, 1.00); calculateConceptTotal()"
                                                placeholder="0.000"/>

                                        </div>
                                    </div>

                                    {{-- Subtotal (Importe sin Impuestos) --}}
                                    <div class="flex-shrink-0 px-3 pt-4 pb-3 text-center col-11">
                                        <h4 class="pt-2 fw-normal">Importe</h4>
                                        <h4 id="subtotal_illusionary">
                                            {{ \App\Helpers\Formats\FormatCurrencyHelper::currencyPlaceHolder() }}
                                        </h4>

                                        <input type="hidden" id="subtotal" name="subtotal" value="0.0">
                                    </div>

                                    {{-- Forma de Aplicación --}}
                                    <div class="flex-shrink-0 col-4">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="discount_format" class="input-group-text">
                                                    Formato de Descuento
                                                </label>
                                            </div>

                                            <select name="discount_format" id="discount_format" class="form-control" onchange="calculateConceptTotal()">
                                                <option value="{{ QuantityApplicationType::Percentage->value }}">Porcentaje (%)</option>
                                                <option value="{{ QuantityApplicationType::Amount->value }}">Monto ({{ session('currency.symbol') }})</option>
                                            </select>
                                        </div>
                                    </div>

                                    {{-- Descuento --}}
                                    <div class="flex-shrink-0 px-3 col-4">
                                        <div class="mb-1 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_discount" class="input-group-text">
                                                    Descuento
                                                </label>
                                            </div>

                                            <input type="number" name="concept_discount" id="concept_discount" required
                                                min='0.0' step="0.0000001" value="0.0000" class="form-control"
                                                onchange="roundDecimals(this, 6); calculateConceptTotal()"
                                                placeholder="0.000"/>

                                            <input type="number" name="concept_discount_rate" id="concept_discount_rate" hidden required
                                                min='0.0' step="0.0000001" value="0.0000" class="form-control"
                                                onchange="roundDecimals(this, 6);"
                                                placeholder="0.000"/>

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

                                {{-- Datos Adicionales --}}
                                <div class="px-3 pt-2 row justify-content-center">
                                    {{-- Descripción --}}
                                    <div class="flex-shrink-0 px-3 col-12">
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_description" class="px-0 bg-transparent input-group-text textarea-label">
                                                    {{ __('entity_fields')['tax_prod_serv']['description'] }} ({{ __('neutral_words')['optional'] }})
                                                </label>
                                            </div>

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

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

                    {{-- Tax Profile --}}
                    <section class="accordion accordion-flush" id="accordion-tax-breakdown">
                        <div class="bg-transparent accordion-item">

                            {{-- Title --}}
                            <div class="accordion-header" id="tax-breakdown-unique-header">
                                <button type="button" class="bg-transparent accordion-button fs-5 secondary-accordion-button ps-0 pe-3"
                                    data-bs-toggle="collapse" data-bs-target="#tax-breakdown-unique"
                                    aria-expanded="true" aria-controls="tax-breakdown-unique"
                                >
                                    Impuestos
                                </button>
                            </div>

                            {{-- Content --}}
                            <div id="tax-breakdown-unique"
                                class="px-2 accordion-collapse collapse show row justify-content-start"
                                aria-labelledby="tax-breakdown-unique-header"
                            ><div class="px-4 accordion-body" id="concept-taxes-form">

                                {{-- Inner Forms --}}
                                <div class="py-3 d-flex justify-content-center" id="tax_breakdown_inner_form">

                                    {{-- Tipo de Impuesto --}}
                                    <div class="flex-shrink-0 col-4">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="tax_type_recorder" class="input-group-text">
                                                    {{ __('entity_fields')['tax_prod_serv']['tax_profile']['tax_name'] }}
                                                </label>
                                            </div>

                                            <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="flex-shrink-0 mx-3 col-4 ">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="tax_rate_recorder" class="input-group-text">
                                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['rate'] }}
                                                </label>
                                            </div>

                                            <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="flex-shrink-0 col-2">
                                        <button type="button" id="tax_recorder_button" onclick="addTaxProfile()"
                                            class="btn-secondary btn w-100"
                                        >
                                            ✚ {{ __('common_actions')['add'] }}
                                        </button>
                                    </div>

                                </div>

                                {{-- Tax Profile Summary --}}
                                <div class="py-3 mx-auto col-12">
                                    <div class="p-2 card table-cards">
                                        <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="15%" class="border-harsi text-uppercase">
                                                            {{ __('entity_fields')['common']['actions'] }}
                                                        </th>
                                                    </tr>
                                                </thead>

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

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

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

                    {{-- Local Tax Profile --}}
                    <section class="accordion accordion-flush" id="accordion-local-tax-breakdown">
                        <div class="bg-transparent accordion-item">

                            {{-- Title --}}
                            <div class="accordion-header" id="local-tax-breakdown-unique-header">
                                <button type="button" class="bg-transparent accordion-button fs-5 secondary-accordion-button ps-0 pe-3"
                                    data-bs-toggle="collapse" data-bs-target="#local-tax-breakdown-unique"
                                    aria-expanded="true" aria-controls="local-tax-breakdown-unique"
                                >
                                    Impuestos Locales
                                </button>
                            </div>

                            {{-- Content --}}
                            <div id="local-tax-breakdown-unique"
                                class="px-2 accordion-collapse collapse show row justify-content-start"
                                aria-labelledby="local-tax-breakdown-unique-header"
                            ><div class="px-4 accordion-body" id="concept-local-taxes-form">

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

                                    {{-- Nombre --}}
                                    <div class="flex-shrink-0 col-12">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="local_tax_name" class="input-group-text">
                                                    {{ __('entity_fields')['tax_prod_serv']['local_tax_profile']['tax_name'] }}
                                                </label>
                                            </div>

                                            <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="flex-shrink-0 col-4">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="local_tax_application_form" class="input-group-text">
                                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_application_form'] }}
                                                </label>
                                            </div>

                                            <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="flex-shrink-0 px-3 col-4">
                                        <div class="mb-1 input-group">
                                            <div class="input-group-prepend">
                                                <label for="local_tax_import" class="input-group-text">
                                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_import'] }}
                                                </label>
                                            </div>

                                            <input type="number" name="local_tax_import" 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="flex-shrink-0 col-4">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="local_tax_type_application" class="input-group-text">
                                                    {{ __('entity_forms')['tax_prod_serv']['placeholders']['local_tax_application_type'] }}
                                                </label>
                                            </div>

                                            <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="flex-shrink-0 pt-3 col-3">
                                        <button type="button" onclick="addLocalTaxProfile()"
                                            class="btn-secondary btn w-100"
                                        >
                                            ✚ {{ __('common_actions')['add'] }}
                                        </button>
                                    </div>

                                </div>

                                {{-- Tax Profile Summary --}}
                                <div class="py-3 mx-auto col-12">
                                    <div class="p-2 card table-cards">
                                        <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>

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

                    {{-- Third Party Account --}}
                    <section class="accordion accordion-flush" id="accordion-third-account">
                        <div class="bg-transparent accordion-item">

                            {{-- Title --}}
                            <div class="accordion-header" id="third-account-unique-header">
                                <button type="button" class="bg-transparent accordion-button fs-5 secondary-accordion-button ps-0 pe-3"
                                    data-bs-toggle="collapse" data-bs-target="#third-account-unique"
                                    aria-expanded="true" aria-controls="third-account-unique"
                                >
                                    A Cuenta de Terceros
                                </button>
                            </div>

                            {{-- Content --}}
                            <div id="third-account-unique"
                                class="px-2 accordion-collapse collapse show row justify-content-center"
                                aria-labelledby="third-account-unique-header"
                            ><div class="px-3 accordion-body" id="concept-third_account-form">

                                {{--  --}}
                                <div class="px-1 mb-3 row justify-content-center">

                                    {{-- RFC --}}
                                    <div class="flex-shrink-0 col-4">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="third_account_tax_identifier" class="input-group-text">
                                                    RFC
                                                </label>
                                            </div>

                                            <input type="text" name="third_account_tax_identifier" id="third_account_tax_identifier"
                                                class="form-control tax-text" autocomplete="off" title=""
                                                placeholder="RFC">
                                        </div>
                                    </div>

                                    {{-- Razón Social --}}
                                    <div class="flex-shrink-0 col-6">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="third_account_legal_name" class="input-group-text">
                                                    {{ __('entity_fields')['common']['legal_name'] }}
                                                </label>
                                            </div>

                                            <input type="text" name="third_account_legal_name" id="third_account_legal_name"
                                                maxlength="200" pattern="^[A-ZÁÉÍÓÚÜÑ0-9 .,'&\-]{3,200}$"
                                                title="{{ __('entity_forms')['pattern_titles']['fiscal_data']['legal_name'] }}"
                                                class="form-control tax-text" autocomplete="off"
                                                placeholder="{{ __('entity_fields')['common']['legal_name'] }}">
                                        </div>
                                    </div>

                                    {{-- Regimen Fiscal --}}
                                    @if ($is_mex_hotel)
                                        <div class="flex-shrink-0 col-5">
                                            <div class="mb-3 input-group">
                                                <div class="input-group-prepend">
                                                    <label for="third_account_tax_system" class="input-group-text">
                                                        {{ __('entity_fields')['common']['tax_system'] }}
                                                    </label>
                                                </div>

                                                <select id="third_account_tax_system" name="third_account_tax_system" class="form-control">
                                                    <option value="" selected>-- {{ __('common_actions')['select'] }} --</option>

                                                    @foreach ($tax_systems as $ts)
                                                        @php
                                                            $ts_label = $ts->item_key.' - '.\App\Helpers\Formats\TextTransformHelper::trimText($ts->label, 35);
                                                        @endphp

                                                        <option value="{{ $ts->item_key }}">{{ $ts_label }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>
                                    @endif

                                    {{-- Postal Code --}}
                                    <div class="flex-shrink-0 col-4">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="third_account_zip" class="input-group-text">
                                                    {{ __('entity_fields')['common']['zip_compact'] }}
                                                </label>
                                            </div>

                                            <input type="text" name="third_account_zip" id="third_account_zip"
                                                autocomplete="off" class="form-control" placeholder=" {{ __('entity_fields')['common']['zip'] }}"/>
                                        </div>
                                    </div>

                                </div>

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

                    {{-- Property Tax Account --}}
                    <section class="accordion accordion-flush" id="accordion-property-tax-account">
                        <div class="bg-transparent accordion-item">

                            {{-- Title --}}
                            <div class="accordion-header" id="property-tax-account-unique-header">
                                <button type="button" class="bg-transparent accordion-button fs-5 secondary-accordion-button ps-0 pe-3"
                                    data-bs-toggle="collapse" data-bs-target="#property-tax-account-unique"
                                    aria-expanded="true" aria-controls="property-tax-account-unique"
                                >
                                    Cuenta Predial
                                </button>
                            </div>

                            {{-- Content --}}
                            <div id="property-tax-account-unique"
                                class="px-2 accordion-collapse collapse show row justify-content-center"
                                aria-labelledby="property-tax-account-unique-header"
                            ><div class="px-3 accordion-body" id="concept-property_tax_account-form">
                                <div class="px-1 mb-3 row justify-content-center">

                                    {{-- Property Tax Account Number --}}
                                    <div class="flex-shrink-0 col-6">
                                        <div class="mb-3 input-group">
                                            <div class="input-group-prepend">
                                                <label for="concept_property_tax_account" class="input-group-text">
                                                    Número
                                                </label>
                                            </div>

                                            <input type="text" name="concept_property_tax_account" id="concept_property_tax_account"
                                                maxlength="50" pattern="^[A-Za-z0-9\s\-\/\.]+$"
                                                title="Solo letras, espacios, números, guiones (-) y barras (/)"
                                                class="form-control tax-text" autocomplete="off"
                                                placeholder="Cuenta Predial del Producto/Servicio">
                                        </div>
                                    </div>

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

                </div>

                {{-- Buttons --}}
                <div class="modal-footer border-top-1 border-secondary">

                    <section class="mb-4 text-center w-100">
                        <h3>Total</h3>
                        <h4 id="total_illusionary" class="text-dark">
                            {{ \App\Helpers\Formats\FormatCurrencyHelper::currencyPlaceHolder() }}
                        </h4>

                        <input type="hidden" id="total" name="total" value="0.0">
                    </section>

                    <section class="text-center w-100">
                        <button type="button" class="px-5 mx-3 btn-block btn btn-secondary" data-bs-dismiss="modal">
                            {{ __('common_actions')['cancel'] }}
                        </button>

                        <button type="submit" id="external_concept_submit" class="px-5 mx-3 btn-block btn btn-harsi">
                            {{ __('common_actions')['add'] }}
                        </button>
                    </section>
                </div>

            </form>

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

{{-- Main 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 }}",
    }

    const tax_types = @json($tax_types_catalog);

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

    // Concepts counter
    function syncLineCounter(){
        // Extract existing line numbers from table
        const existing_lines = $('input[name="line_numbers[]"]').map(function(){
            return parseInt($(this).val() || 0);
        }).get();

        // Save and Increment local count
        window.conceptLineCounter = Math.max(0, ...existing_lines) +1;
    }

    // Visual Structures
    const default_tax_tables_content = `
        <tr>
            <td colspan="4" class="pt-4 pb-3">
                {{ __('data_tables')['sEmptyTable'] }}
            </td>
        </tr>
    `;

  //* CRUD Control
    $(document).ready(function () {
      //- On load view
        restoreConceptForm();
        defineMoralTaxIdFormat("third_account_tax_identifier");
        definePostalCodeFormat("third_account_zip");

      //- On open Concept form
        $('#conceptFormModal').on('shown.bs.modal', function () {
          //* Initialize Select2
            window.conceptModalContext.skipResetOnOpen = false;
            window.conceptModalContext.lastAutoProdServKey = null;
            initConceptSelect2Once();
        });

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

      //- After close Concept Form
        $('#conceptFormModal').on('hidden.bs.modal', function () {
            restoreConceptForm();

            $('#concept_prod_serv_key').val(null).trigger('change');
            $('#concept_unit_key').val(null).trigger('change');
        });

      //- 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');
            }
        });

      //- Main Form Submit
        $('#external_concept_form').on('submit', async function(event){
          // Parse Data
            event.preventDefault();
                if (!validateConceptForm()) return;

          // Build Row
            const form_data = parseFormData( $(this).serializeArray() );

            if(!window.conceptModalContext.lineNumber){
                syncLineCounter();
                window.conceptModalContext.lineNumber = window.conceptLineCounter++;
            }

                await buildConceptRow(form_data, window.conceptModalContext.lineNumber);

          // Store data
            if (window.conceptModalContext.allowDbStorage) {
                $.ajax({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    },
                    url: "{{ route('tax-prod-servs.store') }}",
                    method: "POST",
                    data: mapConceptFormData(form_data),
                    dataType: "json",

                    success: function (response) {
                        window.conceptModalContext.allowDbStorage = false;
                    },

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

                        if (response?.errors) {
                            Object.values(response.errors).flat().forEach(msg =>
                                showToast(msg, "#C34808", "#78350F")
                            );
                        }
                    }

                });
            }

            launchSwalToast(
                'success',
                translateAndReplace(`common_responses_and_messages.${window.conceptModalContext.allowDbStorage ? "created_successfully" : "saved_successfully"}`)
            );
            window.conceptModalContext.lineNumber = "";

            $('#conceptFormModal').modal('hide');
            restoreConceptForm();

            setTimeout(() => syncDraftData(false), 1000);
        });
    });

  //* Support Functions
    // Components Initialization
    function initConceptSelect2Once() {
      // SAT Catalogs (Productos y Servicios)
        const $prodServ = $('#concept_prod_serv_key');
        if (!$prodServ.hasClass('select2-hidden-accessible')) {
            $prodServ.select2({
            placeholder: "{{ __('common_actions')['select'] }}...",
            allowClear: true,
            minimumInputLength: 3,
            dropdownParent: $('#conceptFormModal'),
            dropdownAutoWidth: true,
            width: '75%',
            ajax: {
                url: "{{ route('catalogs.prod-serv.search') }}",
                dataType: 'json',
                delay: 250,
                data: params => ({ q: params.term || '', page: params.page || 1, suggest_last_usage: true }),
                processResults: (data, params) => ({
                    results: data.results,
                    pagination: { more: (params.page = params.page || 1) && data.pagination.more }
                }),
                cache: true
            }
            });
        }

      // SAT Catalogs (Unidades de Medida)
        const $unit = $('#concept_unit_key');
        if (!$unit.hasClass('select2-hidden-accessible')) {
            $unit.select2({
            placeholder: "{{ __('common_actions')['select'] }}...",
            allowClear: false,
            minimumInputLength: 2,
            dropdownParent: $('#conceptFormModal'),
            dropdownAutoWidth: true,
            width: '58%',
            ajax: {
                url: "{{ route('catalogs.units.search') }}",
                dataType: 'json',
                delay: 250,
                data: params => ({ q: params.term || '', page: params.page || 1 }),
                processResults: (data, params) => ({
                    results: data.results,
                    pagination: { more: (params.page = params.page || 1) && data.pagination.more }
                }),
                cache: true
            }
            });
        }
    }

    // Form Controls
    function softConceptFormReset() {
        // Reset Tables
        resetTaxTable({reset_block: true});
        resetLocalTaxTable();

        // Reset Input
        $('#concept_quantity').val(1).trigger('change');
        $('#concept_unit_price, #concept_discount, #concept_discount_rate').val('0.0').trigger('change');
        $(`
            #sku, #concept_prod_serv_id, #concept_name,
            #third_account_tax_identifier, #third_account_legal_name, #third_account_zip,
            #concept_property_tax_account
        `).val('');

        // Reset Selects
        $('#tax_type_recorder, #tax_rate_recorder, #third_account_tax_system').val('');
        $('#concept_unit_key').val('').trigger('change');
        $('#discount_format').val(quantity_application_types.percentage);
        $('#concept_object_tax').val("02");
    }

    function restoreConceptForm() {
        // Reset Form Action Status
        window.conceptModalContext.isEditing = false;

        // Toggle Visualization
        $('#sku_concept_block').hide();

        $('#external_concept_submit, #concept-modal-title-action').text("{{ __('common_actions')['add'] }}");

        // Reset Tables
        resetTaxTable({reset_block: true});
        resetLocalTaxTable();

        // Reset Input
        $('#concept_quantity').val(1).trigger('change');
        $('#concept_unit_price, #concept_discount, #concept_discount_rate').val('0.0').trigger('change');
        $(`
            #sku, #concept_prod_serv_id, #concept_name, #concept_sat_description,
            #third_account_tax_identifier, #third_account_legal_name, #third_account_zip,
            #concept_property_tax_account
        `).val('');
        $('#concept_description').val(translateAndReplace('neutral_words.none'));

        // Reset Selects
        $('#tax_type_recorder, #tax_rate_recorder, #third_account_tax_system').val('');
        $('#concept_prod_serv_key, #concept_unit_key').val('').trigger('change');
        $('#discount_format').val(quantity_application_types.percentage);
        $('#concept_object_tax').val("02");
    }

    function validateConceptForm() {
      // Validate Fiscal Data Section
        const {
            section_valid: fiscal_valid,
            show_error_detected: fiscal_show_error,
            section_error_message: fiscal_error_msg
        } = sharedSectionValidator('fiscal-data-concept-form');

            if (!fiscal_valid) {
                if (fiscal_show_error) showToast(fiscal_error_msg, "#C34808", "#78350F");
                return false;
            }

      // Validate Federal Taxes Summary Section
        const {taxes_valid, show_taxes_error, taxes_error_message} = validateConceptTaxes();
            if (!taxes_valid) {
                if (show_taxes_error) showToast(taxes_error_message, "#C34808", "#78350F");
                return false
            }

      // Validate Local Taxes Summary Section
        const {local_taxes_valid, show_local_taxes_error, local_taxes_error_message} = validateConceptLocalTaxes();
            if (!local_taxes_valid) {
                if (show_local_taxes_error) showToast(local_taxes_error_message, "#C34808", "#78350F");
                return false
            }

      // Validate Third Account Section
        const $third_account_inputs = $('#third_account_tax_identifier, #third_account_legal_name, #third_account_tax_system, #third_account_zip');
        const some_filled = $third_account_inputs.toArray().some(i => $(i).val()?.trim());
            if(some_filled) $third_account_inputs.attr('required', true); // Add required to Fields

        const {
            section_valid: third_valid,
            show_error_detected: third_show_error,
            section_error_message: third_error_msg
        } = sharedSectionValidator('concept-third_account-form');
        $third_account_inputs.attr('required', false); // Remove required to Fields

            if (!third_valid) {
                if (third_show_error) showToast(third_error_msg, "#C34808", "#78350F");
                return false;
            }

      // Validate Concept Property Tax Account Section
        const {
            section_valid: property_valid,
            show_error_detected: property_show_error,
            section_error_message: property_error_msg
        } = sharedSectionValidator('concept-property_tax_account-form');

            if (!property_valid) {
                if (property_show_error) showToast(property_error_msg, "#C34808", "#78350F");
                return false;
            }

        return true;
    }

    // Specific Form Section
    function validateConceptTaxes() {
      //* Control Data
        // Structures
        const $tax_table_records = $('#profile-taxes-table-body');
        const $firstTd = $tax_table_records.find('tr:first').find('td:first');

        const rowCount = $firstTd.length && $firstTd.attr('colspan')
            ? 0 // Case: No Taxes Registered
            : $tax_table_records.find("tr").length;

        const $tax_applications  = $tax_table_records.find('input[name="tax_application_summary[]"]');
        const $recorded_taxes  = $tax_table_records.find('input[name="tax_summary[]"]');
        const $rate_quotes = $tax_table_records.find('input[name="rate_quotes_summary[]"]');
        const $tax_charges = $tax_table_records.find('input[name="tax_charges_summary[]"]');

        // Control Variables
        let is_valid = true;
        let taxes_error_message = "";

        if (
            $tax_applications.length !== rowCount
            || $recorded_taxes.length !== rowCount
            || $rate_quotes.length !== rowCount
            || $tax_charges.length !== rowCount
        ) {
            is_valid = false;
            taxes_error_message = "Alteración de Campos Detectada";
        }

        // Validación secundaria de Tipos de Aplicación de Impuestos
        if (is_valid) {
            $tax_applications.each(function(i, el) {
                const val = (el.value || "").trim();

                if (![format_types_keys.transfer, format_types_keys.withholding].includes(val)) {
                    taxes_error_message = `El impuesto #${i+1} no cuenta con un Tipo de Impuesto válido`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // Validación secundaria de Tipos de Impuesto
        if (is_valid) {
            $recorded_taxes.each(function(i, el) {
                const val = (el.value || "").trim();
                const found = val && tax_types.find(t => t.item_key === val);

                if (!found) {
                    is_valid = false;
                    taxes_error_message = `El impuesto #${i + 1} no cuenta con un Impuesto válido`;
                    return false;
                }
            });
        }

        // Validación secundaria de Tasas o Cuotas
        if (is_valid) {
            $rate_quotes.each(function(i, el) {
                const val = (el.value || "").trim();

                if (!val) {
                    taxes_error_message = `El impuesto #${i+1} no cuenta con una Tasa/Cuota asignada`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // Validación secundaria de Cargos por Impuestos
        if (is_valid) {
            $tax_charges.each(function(i, el) {
                const val = (el.value || "").trim();

                if (!val) {
                    taxes_error_message = `El impuesto #${i+1} ha sido alterada sin permiso`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // If section is invalid display accordion
        if(!is_valid) {
            const $accordion = $tax_table_records.closest('.accordion-collapse.collapse');
                if ($accordion.length) $accordion.collapse('show');

            $tax_table_records[0]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
            $tax_table_records[0]?.focus({ preventScroll: true });
        }

        return {taxes_valid: is_valid, show_taxes_error: true, taxes_error_message};
    }

    function validateConceptLocalTaxes()  {
      //* Control Data
        // Structures
        const $local_tax_table_records = $('#profile-local-taxes-table-body');
        const $firstTd = $local_tax_table_records.find('tr:first').find('td:first');

        const rowCount = $firstTd.length && $firstTd.attr('colspan')
            ? 0 // Case: No Taxes Registered
            : $local_tax_table_records.find("tr").length;

        const $local_tax_names  = $local_tax_table_records.find('input[name="local_tax_names_summary[]"]');
        const $local_rate_quotes = $local_tax_table_records.find('input[name="local_rate_quotes_summary[]"]');
        const $local_tax_charges = $local_tax_table_records.find('input[name="local_tax_charges_summary[]"]');
        const $local_tax_applications  = $local_tax_table_records.find('input[name="local_tax_application_summary[]"]');

        // Control Variables
        let is_valid = true;
        let local_taxes_error_message = "";

        if (
            $local_tax_names.length !== rowCount
            || $local_rate_quotes.length !== rowCount
            || $local_tax_charges.length !== rowCount
            || $local_tax_applications.length !== rowCount
        ) {
            is_valid = false;
            local_taxes_error_message = "Alteración de Campos Detectada";
        }

        // Validación secundaria de Tipos de Impuesto
        if (is_valid) {
            $local_tax_names.each(function(i, el) {
                const val = (el.value || "").trim();

                if (!val) {
                    local_taxes_error_message = `El impuesto local #${i+1} no cuenta con un Nombre asignado`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // Validación secundaria de Tasas o Cuotas
        if (is_valid) {
            $local_rate_quotes.each(function(i, el) {
                const val = (el.value || "").trim();

                if (!val) {
                    local_taxes_error_message = `El impuesto local #${i+1} no cuenta con una Tasa/Cuota asignada`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // Validación secundaria de Cargos por Impuestos
        if (is_valid) {
            $local_tax_charges.each(function(i, el) {
                const val = (el.value || "").trim();

                if (!val) {
                    local_taxes_error_message = `El impuesto local #${i+1} ha sido alterada sin permiso`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // Validación secundaria de Tipos de Aplicación de Impuestos
        if (is_valid) {
            $local_tax_applications.each(function(i, el) {
                const val = (el.value || "").trim();

                if (![format_types_keys.transfer, format_types_keys.withholding].includes(val)) {
                    local_taxes_error_message = `El impuesto local #${i+1} no cuenta con un Tipo de Impuesto válido`;
                    is_valid = false;

                    const $row = el.closest('tr');
                    $row[0]?.focus({ preventScroll: true });

                    return false;
                }
            });
        }

        // If section is invalid display accordion
        if(!is_valid) {
            const $accordion = $local_tax_table_records.closest('.accordion-collapse.collapse');
                if ($accordion.length) $accordion.collapse('show');

            $local_tax_table_records[0]?.scrollIntoView({ behavior: 'smooth', block: 'center' });
            $local_tax_table_records[0]?.focus({ preventScroll: true });
        }

        return {local_taxes_valid: is_valid, show_local_taxes_error: true, local_taxes_error_message};
    }

  //* Complementary Functions
    function generateRandomSku(){
        return Math.floor(Math.random() * 999999999999) + 1;
    }

    function mapConceptFormData(form_data) {
        return {
            sku: `Har-${generateRandomSku()}`,
            name: form_data.concept_name,
            description: form_data.concept_description ?? form_data.concept_sat_description ?? "{{ __('neutral_words')['none'] }}",
            prod_serv_key: form_data.concept_prod_serv_key,
            sat_description: form_data.concept_sat_description,
            unit_key: form_data.concept_unit_key,
            object_tax: form_data.concept_object_tax,
            unit_price: form_data.concept_unit_price,

            tax_application_summary: form_data.tax_application_summary,
            tax_summary: form_data.tax_summary,
            rate_quotes_summary: form_data.rate_quotes_summary,
            tax_charges_summary: form_data.tax_charges_summary,

            local_tax_names_summary: form_data.local_tax_names_summary,
            local_rate_quotes_summary: form_data.local_rate_quotes_summary,
            local_tax_charges_summary: form_data.local_tax_charges_summary,
            local_tax_application_summary: form_data.local_tax_application_summary,

            total: form_data.total
        };
    }

    function parseFormData(brute_data) {
        const result = {};

        brute_data.forEach(({ name, value }) => {
            const cleanName = name.replace(/\[\]$/, ""); // Remove "[]" from input groups

            // Si ya existe y es un array → agregamos
            if (result.hasOwnProperty(cleanName)) {
                if (Array.isArray(result[cleanName])) {
                    result[cleanName].push(value);
                } else {
                    // Convertir valor previo a array
                    result[cleanName] = [result[cleanName], value];
                }
            } else {
                // Si el nombre termina con [] => crear como array
                if (name.endsWith("[]")) {
                    result[cleanName] = [value];
                } else {
                    result[cleanName] = value;
                }
            }
        });

        return result;
    }

    async function buildConceptRow(concept_data, line_number = null) {
      //* Clean Data
        delete concept_data._token;
        delete concept_data.local_tax_import;

      //* Support
        const define_tax_application_type = (type) => {
            return type === format_types_keys.transfer
                ? translateAndReplace('neutral_words.transfer')
                : translateAndReplace('neutral_words.withholding')
        }

      //* Formatted Presentation
        // Concept Data
        const encrypted_data = CryptoJS.AES.encrypt(JSON.stringify(concept_data), window.tax_decrypt_data).toString();

        // Fiscal Description
        const sat_description = truncateString(concept_data.concept_sat_description, 30);
        const concept_name = truncateString(concept_data.concept_name, 30);

        // Object Tax
        const code = concept_data.concept_object_tax;
        const label = window.tax_objects[code] ?? '';
        const object_tax = `${code} - ${truncateString(label, 31)}`;

        // Federal Taxes
        let federal_taxes_structure = "";
        const federal_taxes_length = concept_data.tax_summary?.length;
        for (let index = 0; index < federal_taxes_length; index++) {
            const quote_description = parseFloat( concept_data.rate_quotes_summary[index] ).toFixed(2) === '0.00'
                ? '0.00%' // 'Exento'
                : strToStrPercentage(concept_data.rate_quotes_summary[index]);

            federal_taxes_structure += `
                <li>
                    <span class="concept-table-lists">${defineTaxName(concept_data.tax_summary[index])}</span>
                    (${
                        define_tax_application_type(concept_data.tax_application_summary[index])
                    }):<br>
                    ${quote_description}
                </li>
            `;
        }

        // Local Taxes
        let local_taxes_structure = "";
        const local_taxes_length = concept_data.local_tax_names_summary?.length;
        for (let index = 0; index < local_taxes_length; index++) {
            const quote_description = parseFloat( concept_data.local_rate_quotes_summary[index] ).toFixed(2) === '0.00'
                ? '0.00%' // 'Exento'
                : strToStrPercentage(concept_data.local_rate_quotes_summary[index], {is_low_decimal: false});

            local_taxes_structure += `
                <li>
                    <span class="concept-table-lists">${concept_data.local_tax_names_summary[index]}</span>
                    (Local, ${
                        define_tax_application_type(concept_data.local_tax_application_summary[index])
                    }):<br>
                    ${quote_description}
                </li>
            `;
        }

        // Amounts Summary
        const is_discount_percentage = concept_data.discount_format === quantity_application_types.percentage;
        const concept_has_discount = parseFloat( concept_data.concept_discount ).toFixed(2) != '0.00';
        const base_amount = parseFloat(concept_data.concept_unit_price) * parseFloat(concept_data.concept_quantity);

        let amounts_summary = `
            <ul class="text-start warning-messages">
                <li>
                    <span class="concept-table-lists">Precio Unitario:</span><br>
                    ${removeUnnecessaryDecimal(concept_data.concept_unit_price)}
                </li>
                <li>
                    <span class="concept-table-lists">Importe Base:</span><br>
                    ${removeUnnecessaryDecimal(base_amount.toFixed(6))}
                </li>
            </ul>
        `;

        if (concept_has_discount) {
            amounts_summary += `
                <ul class="text-start warning-messages">
                    <li>
                        <span class="concept-table-lists">Descuento (${is_discount_percentage ? '%' : '$'}):</span><br>
                        ${
                            is_discount_percentage
                                ? strToStrPercentage(concept_data.concept_discount, {decimals: 6, is_low_decimal: false})
                                : removeUnnecessaryDecimal(concept_data.concept_discount)
                        }
                    </li>
                    <li>
                        <span class="concept-table-lists">Cantidad Descontada:</span><br>
                        ${removeUnnecessaryDecimal(concept_data.concept_discount_rate)}
                    </li>
                </ul>
            `;
        }

        // Total
        const total_with_discount = parseFloat(concept_data.subtotal) - parseFloat(concept_data.concept_discount_rate);

      //* Build and render row
        const concept_row = `
            <tr>

                <td class="text-center align-middle">
                    <div class="gap-2 d-flex flex-column align-items-center justify-content-center">
                        <button type='button' class='mx-1 btn btn-secondary btn-sm' onclick="editConcept(this, '${encrypted_data}', false)">
                            <i class='fas fa-copy'></i>
                        </button>
                        <button type='button' class='mx-1 btn btn-harsi btn-sm' onclick="editConcept(this, '${encrypted_data}')">
                            <i class='fas fa-pen'></i>
                        </button>
                        <button type='button' class='mx-1 btn btn-danger btn-sm' onclick="removeRow(this, 8, {is_concepts_table: true}); calculateInvoiceTotal()">
                            <i class='fas fa-trash'></i>
                        </button>
                    </div>
                </td>

                <td class="dynamic-id">
                    <input type="hidden" name="concept_summary[]" value='${encrypted_data}'/>
                    <input type="hidden" name="line_numbers[]" value="${line_number}"/>
                </td>

                <td>
                    ${concept_data.concept_quantity}
                </td>

                <td>
                    ${concept_data.concept_unit_key}
                </td>

                <td class="ps-0"><ul class="text-start warning-messages">
                    <li>
                        <span class="concept-table-lists">Nombre del Producto/Servicio:</span><br>
                        ${concept_name}
                    </li>

                    <li>
                        <span class="concept-table-lists">Clave Fiscal:</span><br>
                        ${concept_data.concept_prod_serv_key}
                    </li>

                    <li>
                        <span class="concept-table-lists">Descripción Fiscal:</span><br>
                        ${sat_description}
                    </li>

                    <li>
                        <span class="concept-table-lists">Descripción Adicional:</span><br>
                        ${concept_data.concept_description}
                    </li>

                    <li>
                        <span class="concept-table-lists">Objeto Impuesto:</span><br>
                        ${object_tax}
                    </li>
                </ul></td>

                <td class="text-start warning-messages ps-0">
                    <ul class="text-start warning-messages">
                        ${federal_taxes_structure}
                    </ul>
                    <ul class="text-start warning-messages">
                        ${local_taxes_structure}
                    </ul>
                </td>

                <td class="text-start warning-messages ps-0">
                    ${amounts_summary}
                </td>

                <td class="warning-messages fw-bold">
                    ${removeUnnecessaryDecimal(total_with_discount.toFixed(6))}
                </td>

            </tr>
        `;

        // Define action
        if( // Update Concept
            window.conceptModalContext.isEditing // ¿Se esta editando un concepto?
            && window.conceptModalContext.lineNumber !== ""  // ¿Tiene un numero en la lista?
        ) {
            // Replace edited row
            let row_found = false;
            const target_line = window.conceptModalContext.lineNumber;

            $('#concepts-table-body tr').each(function () {
                const current_line = $(this).find('input[name="line_numbers[]"]').val();

                if (current_line == target_line) {
                    $(this).replaceWith(concept_row);

                    row_found = true;
                    return false;
                }
            });

            // Si no halló la fila
            if(!row_found){
                $('#concepts-table-body').append(concept_row);
            }
        } else { // Register Concept
            // Define if its first record
            const $tbody = $('#concepts-table-body');
            const $firstTd = $tbody.find('tr:first').find('td:first');

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

      //* Update Totals
        calculateInvoiceTotal();

        return;
    }

    function calculateConceptTotal() {
        //* Control Variables
          // Price control
            const unit_price = parseFloat($('#concept_unit_price').val());
            const concept_quantity = parseFloat($('#concept_quantity').val());

          // Defined base amount (exclude taxes and discount)
            let subtotal_price = unit_price * concept_quantity;
            let subtotal_illusionary = removeUnnecessaryDecimal(subtotal_price.toFixed(6));

            $('#subtotal_illusionary').text( formatCurrency(subtotal_illusionary) );
            $('#subtotal').val(subtotal_illusionary);

            // Apply Discount
            const discount_as_percentage = $('#discount_format').val() === quantity_application_types.percentage;
            const concept_discount = parseFloat($('#concept_discount').val());

            const discount_rate = discount_as_percentage
                ? removeUnnecessaryDecimal((subtotal_price * concept_discount) / 100)
                : parseFloat( removeUnnecessaryDecimal(concept_discount.toFixed(6)) );

            $('#concept_discount_rate').val(discount_rate).trigger('change');
            subtotal_price -= discount_rate;

          // 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 = subtotal_price * ieps_quote; // IEPS % on base price
            }
            $ieps_tr.find('input[name="tax_charges_summary[]"]').val( removeUnnecessaryDecimal(ieps_transferred.toFixed(6)) );


          // 2) Calculate VAT on the basis that includes IEPS
            const iva_base = subtotal_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( removeUnnecessaryDecimal(iva_transferred.toFixed(6)) );
            $iva_withheld_tr.find('input[name="tax_charges_summary[]"]').val( removeUnnecessaryDecimal(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 = subtotal_price * isr_quote;
            }
            $isr_tr.find('input[name="tax_charges_summary[]"]').val( removeUnnecessaryDecimal(isr_withheld.toFixed(6)) );

          // 4) Total: precio unitario + IEPS + IVA trasladado - IVA retenido - ISR retenido
            let total_price = subtotal_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((subtotal_price * (rate/100)).toFixed(6));
                $row.find('input[name="local_tax_charges_summary[]"]').val( removeUnnecessaryDecimal(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);
    }
</script>

{{-- Fiscal Data Scripts --}}
<script>
  //* Triggers
    // SAT Catalogs
    $(function () {
        $('#concept_object_tax').on('change', defineTaxProfile);

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

            const has_last_usage = e.params.data.has_last_usage || false; // The ProductServKey has been used
            const last_usage = e.params.data.last_usage?.data || null; // Last record where key has been used

          // Update SAT Description
            $('#concept_sat_description').val(prod_serv_name);

          // Init Usage Process
            if (has_last_usage) {
                seedWithLastUsage(prod_serv_key, last_usage, has_last_usage, window.conceptModalContext.isEditing);
            } else {
                softConceptFormReset();
                autoAssignConceptName(prod_serv_key);
            }
        });
    });

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

        // Visual Controls
        const $pu_indications = $('#pu_indications');
        const $tax_block = $('#accordion-tax-breakdown');
        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
        resetTaxTable();
        calculateConceptTotal();

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

        if(!window.conceptModalContext.skipResetOnOpen ) // Don't display on load concept data
            launchSwalToast(
                'success',
                "{{ __('entity_forms')['tax_prod_serv']['messages']['tax_table_updated'] }}",
            );
    }

    async function autoAssignConceptName(prod_serv_key) {
        // Define concept name if its not already assigned
        const $concept_name_field = $('#concept_name');

        const current_key = ($concept_name_field.val() || '').trim();
        const last_key = window.conceptModalContext.lastAutoProdServKey;

        const is_empty = current_key === '';
        const was_auto_filled = (last_key != null) && (current_key === String(last_key).trim());

        if (is_empty || was_auto_filled) {
            $concept_name_field.val(prod_serv_key);
            window.conceptModalContext.lastAutoProdServKey = prod_serv_key;
        }

        return;
    }

    async function seedWithLastUsage (prod_serv_key, last_usage = null, has_last_usage = false, currently_editing = false) {
        if (!has_last_usage) return; // La clave fiscal nunca ha sido utilizada

        // ¿El usuario desea reutilizar el ultimo uso/registro con la Clave Fiscal?
        const result = await Swal.fire({
            icon: 'info',
            title: translateAndReplace('entity_forms.tax_invoice.messages.used_prod_serv_title'),
            html: `
                <div style="text-align:left">
                    ${translateAndReplace('entity_forms.tax_invoice.messages.used_prod_serv_message')}
                    ${translateAndReplace('entity_forms.tax_invoice.messages.used_prod_serv_suggest')}
                    ${translateAndReplace('entity_forms.tax_invoice.messages.used_prod_serv_option')}
                </div>
            `,
            showCancelButton: true,
            reverseButtons: true,
            confirmButtonText: `{{ __('common_actions')['approve'] }} ${translateAndReplace('entity_forms.tax_invoice.messages.used_prod_serv_accept')}`,
            cancelButtonText: `{{ __('common_actions')['deny'] }} ${translateAndReplace('entity_forms.tax_invoice.messages.used_prod_serv_deny')}`,
        });

        if (result.value) { // Cargar datos del Ultimo uso
            const parsed_taxes = buildTaxSummaries(last_usage);
            const concept_data = {
                concept_prod_serv_id: last_usage?.prod_serv_id,
                concept_name: last_usage?.name,
                concept_prod_serv_key: last_usage?.prod_serv_key,
                concept_sat_description: last_usage?.sat_description,
                concept_object_tax: last_usage?.object_tax,
                concept_unit_key: last_usage?.unit_key,
                concept_unit_price: last_usage?.unit_price,
                concept_quantity: last_usage?.quantity ?? 1.000,
                subtotal: last_usage?.subtotal,
                discount_format: last_usage?.discount_type ?? @json(QuantityApplicationType::Percentage->value),
                concept_discount: last_usage?.discount_value ?? 0.0000,
                concept_discount_rate: last_usage?.discount_total ?? 0.0000,
                concept_description: last_usage?.description,

                tax_application_summary: parsed_taxes.tax_application_summary,
                tax_summary: parsed_taxes.tax_summary,
                rate_quotes_summary: parsed_taxes.rate_quotes_summary,
                tax_charges_summary: parsed_taxes.tax_charges_summary,

                local_tax_names_summary: parsed_taxes.local_tax_names_summary,
                local_rate_quotes_summary: parsed_taxes.local_rate_quotes_summary,
                local_tax_charges_summary: parsed_taxes.local_tax_charges_summary,
                local_tax_application_summary: parsed_taxes.local_tax_application_summary,

                third_account_tax_identifier: last_usage?.third_party_account?.tax_identifier,
                third_account_legal_name: last_usage?.third_party_account?.legal_name,
                third_account_tax_system: last_usage?.third_party_account?.tax_system,
                third_account_zip: last_usage?.third_party_account?.zip,

                concept_property_tax_account: last_usage?.property_tax_account,

                total: last_usage?.total
            };

            const encrypted_data = CryptoJS.AES.encrypt(JSON.stringify(concept_data), window.tax_decrypt_data).toString();
            editConcept(null, encrypted_data, currently_editing);
        } else { // Iniciar un nuevo registro
            softConceptFormReset();
            autoAssignConceptName(prod_serv_key);
        }
    }
</script>

{{-- Tax Profile Scripts --}}
<script>
    // Tax Profile Table Interactions
      // Dynamic Content
        function resetTaxTable({reset_block = false} = {}) {
            // Clean Table Content
            $('#profile-taxes-table-body').html(default_tax_tables_content);

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

            // Reset Tax Block visualization
            if (reset_block){
                $('#pu_indications').text("Sin Impuestos");
                $('#accordion-tax-breakdown').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({
                    icon: "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});
            calculateConceptTotal();

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

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

          // 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.tax_table_summary[tax_application === "tr" ? "taxes" : "withholding_taxes"][tax_type] = false;

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

          // Revisamos si aun hay filas en la tabla
            const remaining_rows = tbody.find('tr').length;

            // Si no quedan filas, dibujar mensaje por defecto
            if (remaining_rows === 0) {
                $(`#${tbody.attr('id')}`).html(`
                    <tr>
                        <td colspan="4" class="pt-4 pb-3">
                            ${translateAndReplace('data_tables.sEmptyTable')}
                        </td>
                    </tr>
                `)
            }

            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_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.tax_table_summary.withholding_taxes.isr,
                    ));
                    window.tax_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.tax_table_summary.taxes.ieps,
                    ));
                    window.tax_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.tax_table_summary[iva_format_key].iva
                    ));
                    window.tax_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>
                        ${defineTaxName(tax_type)}
                        <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>
            `;

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

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

            // Complementary message
            if(show_toast && !window.conceptModalContext.skipResetOnOpen ) // Don't display on load concept data
                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({
                icon: '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('');
        }
</script>

{{-- Local Tax Profile Scripts --}}
<script>
    // Tax Profile Table Interactions
      // Dynamic Content
        function resetLocalTaxTable() {
            // Clean Table Content
            $('#profile-local-taxes-table-body').html(default_tax_tables_content);

            // 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});
            calculateConceptTotal();

          // 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
            calculateConceptTotal(); // Re-calcular Total

          // Revisamos si aun hay filas en la tabla
            const remaining_rows = tbody.find('tr').length;

            // Si no quedan filas, dibujar mensaje por defecto
            if (remaining_rows === 0) {
                $(`#${tbody.attr('id')}`).html(`
                    <tr>
                        <td colspan="4" class="pt-4 pb-3">
                            ${translateAndReplace('data_tables.sEmptyTable')}
                        </td>
                    </tr>
                `)
            }

            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

            // Complementary message
            if(!window.conceptModalContext.skipResetOnOpen ) // Don't display on edit concept
                launchSwalToast(
                    'success',
                    "{{ __('common_responses_and_messages')['created_successfully'] }}",
                );

            return;
        }
</script>
