{{-- Modal --}}
<div id="taxBranchFormModal" class="mt-5 modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="px-3 py-4 modal-body special-modal-body">

                {{-- Close Buttons --}}
                <div class="text-end d-flex justify-content-end align-items-end">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="float: none">
                        <span>
                            <img src="{{ asset('icons/close_modal.svg') }}" aria-hidden="true"
                                style="margin-bottom: -2.5rem; width: 2.3rem;">
                        </span>
                    </button>
                </div>

                {{-- Title --}}
                <h4 class="pt-3 text-center modal_title"></h4>
                <h6 class="mb-3 text-center modal_subtitle"></h6>

                {{-- Form --}}
                <form method="post" id="tax_branch_form" class="px-3 mt-2 form-horizontal"
                    autocomplete="off" enctype="multipart/form-data"
                >@csrf

                    {{-- Header --}}
                    <p class="mb-3" style="font-weight: 600; font-size: 1.2rem; color: #006b8fd1;">
                        {{ __('entity_forms')['establishment']['fiscal_form']['fiscal_identity']['section_1'] }}
                    </p>

                    {{-- Legal Name --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-3">
                            {{ __('entity_fields')['common']['name'] }} <span style="color: #dc3742af;">*</span>
                        </label>
                        <div class="col-md-9">
                            <input type="text" name="legal_name" id="legal_name" required
                                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>

                    {{-- Fiscal Email --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-3">
                            {{ __('entity_fields')['common']['email'] }} <span style="color: #dc3742af;">*</span>
                        </label>
                        <div class="col-md-9">
                            <input type="email" name="hotel_fake_email" id="hotel_fake_email" required
                                maxlength="200" class="form-control" autocomplete="off"
                                placeholder="ejemplo@gmail.com"/>
                        </div>
                    </div>


                    {{-- Header --}}
                    <p class="mb-3" style="font-weight: 600; font-size: 1.2rem; color: #006b8fd1;">
                        {{ __('entity_forms')['establishment']['fiscal_form']['fiscal_identity']['section_2'] }}
                    </p>

                    {{-- Postal Code --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-3">
                            {{ __('entity_fields')['common']['zip_compact'] }} <span style="color: #dc3742af;">*</span>
                        </label>
                        <div class="col-md-9">
                            <input type="text" name="individual_zip" id="individual_zip" required
                                autocomplete="off" class="form-control" placeholder=" {{ __('entity_fields')['common']['zip'] }}"/>
                        </div>
                    </div>

                    {{-- Street --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-3">
                            {{ __('entity_fields')['common']['tax_address']['street'] }}
                        </label>
                        <div class="col-md-9">
                            <input type="text" name="individual_street" id="individual_street"
                                pattern="^[A-Za-zÀ-ÿÑñ0-9 .,'#\-\/]{2,80}$"
                                title="{{ __('entity_forms')['pattern_titles']['address']['street'] }}"
                                minlength="2" maxlength="80" autocomplete="off"
                                class="form-control tax-text" placeholder="{{ __('entity_fields')['common']['tax_address']['street'] }} ..."/>
                        </div>
                    </div>

                    {{-- Numbers --}}
                    <div class="row">
                        <div class="pr-3 form-group row col-6">
                            <label class="pt-2 pl-3 text-start control-label col-md-6">
                                {{ __('entity_fields')['common']['tax_address']['ext_number'] }}
                            </label>
                            <div class="col-md-6">
                                <input type="text" name="individual_ext_number" id="individual_ext_number"
                                    maxlength="50" pattern="^(S\/N|SN|s\/n|sn|[A-Za-z0-9\-\/# ]{1,50})$"
                                    title="{{ __('entity_forms')['pattern_titles']['address']['ext_number'] }}"
                                    class="form-control tax-text" autocomplete="off" placeholder="00"/>
                            </div>
                        </div>

                        <div class="pl-3 form-group row col-6">
                            <label class="pt-2 pl-3 text-start control-label col-md-6">
                                {{ __('entity_fields')['common']['tax_address']['int_number'] }}
                            </label>
                            <div class="col-md-6">
                                <input type="text" name="individual_int_number" id="individual_int_number"
                                    maxlength="50" pattern="^(S\/N|SN|s\/n|sn|[A-Za-z0-9\-\/# ]{1,50})$"
                                    title="{{ __('entity_forms')['pattern_titles']['address']['int_number'] }}"
                                    class="form-control tax-text" autocomplete="off" placeholder="00"/>
                            </div>
                        </div>
                    </div>

                    {{-- Neighborhood --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-4">
                            {{ __('entity_fields')['common']['tax_address']['neighborhood'] }}
                        </label>
                        <div class="col-md-8">
                            <input type="text" name="individual_neighborhood" id="individual_neighborhood"
                                minlength="2" maxlength="60" autocomplete="off"
                                pattern="^[A-Za-zÀ-ÿÑñ0-9 .,'\-]{2,60}$" class="form-control tax-text"
                                title="{{ __('entity_forms')['pattern_titles']['address']['neighborhood'] }}"
                                placeholder="{{ __('entity_fields')['common']['tax_address']['neighborhood'] }} ..."/>
                        </div>
                    </div>

                    {{-- City --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-3">
                            {{ __('entity_fields')['common']['tax_address']['city'] }}
                        </label>
                        <div class="col-md-9">
                            <input type="text" name="individual_city" id="individual_city"
                                class="form-control tax-text" autocomplete="off"
                                placeholder="{{ __('entity_fields')['common']['tax_address']['city'] }} ..."/>
                        </div>
                    </div>

                    {{-- Municipality --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-4">
                            {{ __('entity_fields')['common']['tax_address']['municipality'] }}
                        </label>
                        <div class="col-md-8">
                            <input type="text" name="individual_municipality" id="individual_municipality"
                                minlength="2" maxlength="60" autocomplete="off"
                                pattern="^[A-Za-zÀ-ÿÑñ .,'\-]{2,60}$" class="form-control tax-text"
                                title="{{ __('entity_forms')['pattern_titles']['address']['municipality'] }}"
                                placeholder="{{ __('entity_fields')['common']['tax_address']['municipality'] }} ..."/>
                        </div>
                    </div>

                    {{-- State --}}
                    <div class="form-group row">
                        <label class="pl-3 text-start control-label col-md-3">
                            {{ __('entity_fields')['common']['tax_address']['state'] }}
                        </label>
                        <div class="col-md-9">
                            <input type="text" name="individual_state" id="individual_state"
                                minlength="2" maxlength="60" autocomplete="off"
                                pattern="^[A-Za-zÀ-ÿÑñ .,'\-]{2,60}$" list="tx-mx-states"
                                title="{{ __('entity_forms')['pattern_titles']['address']['state'] }}"
                                class="form-control tax-text" placeholder="{{ __('entity_fields')['common']['tax_address']['state'] }} ..."/>
                        </div>

                        <datalist id="tx-mx-states"></datalist>
                    </div>

                    {{-- Buttons --}}
                    <div class="pt-3 text-center form-group col-12">
                        {{-- Hidden Data --}}
                        <input type="hidden" name="hidden_id" id="hidden_id" />

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

                </form>

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

{{-- Scripts --}}
<script src="{{ asset('js/invoicing/tax-formats.js') }}"></script>

<script>
  //* CRUD Control
    $(document).ready(function () {
      //- On load page
        defineOptionalStates();
        definePostalCodeFormat("individual_zip");

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

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

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

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

            // Form Cleaning
            $('#taxBranchFormModal').modal('show');
            $('#tax_branch_form')[0].reset();
        });

      // Open For Edit
        $(document).on('click', '.edit', function () {
            var id = $(this).attr('id');
            $.ajax({
                url: `/invoicing/branches/${id}/edit`,
                dataType: "json",

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

                    // Fill Fields
                    $('#hidden_id').val(data.id);
                    $('#legal_name').val(data.legal_name);
                    $('#hotel_fake_email').val(data.email);
                    $('#individual_zip').val(data.zip);

                    $('#individual_street').val(data.tax_address.street);
                    $('#individual_ext_number').val(data.tax_address.exterior);
                    $('#individual_int_number').val(data.tax_address.interior);
                    $('#individual_neighborhood').val(data.tax_address.neighborhood);
                    $('#individual_city').val(data.tax_address.city);
                    $('#individual_municipality').val(data.tax_address.municipality);
                    $('#individual_state').val(data.tax_address.state);

                    // Modal Titles
                    $('.modal_title').text("{{ __('entity_forms')['common']['modal_title_2'] }}");
                    $('.modal_subtitle').text(`{{ __('entities')['invoicing']['branch'] }} (${data.legal_name})`);

                    // Form Cleaning
                    $('#action').val("Update");
                    $('#action_message').text("{{ __('common_actions')['update'] }}");
                    $('#taxBranchFormModal').modal('show');
                }
            })
        });

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

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

                        $('#tax_branch_form')[0].reset();
                        $('#tax_branch_table').DataTable().ajax.reload(null, false);
                        $('#taxBranchFormModal').modal('hide');
                    },

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

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

                        return;
                    },
                })
            }

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

                        $('#tax_branch_form')[0].reset();
                        $('#taxBranchFormModal').modal('hide');
                        $('#tax_branch_table').DataTable().ajax.reload(null, false);
                    },

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

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

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

</script>

{{-- Special Cases --}}
<script>
    function defineOptionalStates() {
        if (getCountrySettings() !== "MEX") {
            $('#tx-mx-states').html("");
            return;
        }

        // Only México States for now
        const tax_mx_states = [
            "Aguascalientes",
            "Baja California",
            "Baja California Sur",
            "Campeche",
            "Chiapas",
            "Chihuahua",
            "Ciudad de México",
            "Coahuila de Zaragoza",
            "Colima",
            "Durango",
            "Guanajuato",
            "Guerrero",
            "Hidalgo",
            "Jalisco",
            "México",
            "Michoacán de Ocampo",
            "Morelos",
            "Nayarit",
            "Nuevo León",
            "Oaxaca",
            "Puebla",
            "Querétaro",
            "Quintana Roo",
            "San Luis Potosí",
            "Sinaloa",
            "Sonora",
            "Tabasco",
            "Tamaulipas",
            "Tlaxcala",
            "Veracruz de Ignacio de la Llave",
            "Yucatán",
            "Zacatecas",
        ];

        let state_options = "";
        tax_mx_states.forEach(state => {
            state_options += `<option value="${state}"></option>`;
        });
        $('#tx-mx-states').html(state_options);
    }
</script>
