{{-- Modal --}}
<div id="clientFormModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body special-modal-body">

                {{-- Title --}}
                <div class="row justify-content-center align-items-baseline border-bottom">
                    <div class="pt-1 text-center col-11">
                        <h4 class="modal_title"></h4>
                        <h6 class="modal_subtitle"></h6>
                    </div>
                    <div class="pt-1 text-center col-1">
                        <button type="button" class="mt-0 close" data-dismiss="modal" style="float: none; font-size: 2.3rem;">&times;</button>
                    </div>
                </div>

                {{-- Form --}}
                <form method="post" id="client_form" enctype="multipart/form-data"
                    class="px-4 pt-3 form-horizontal"
                >@csrf

                    {{-- Basic Data --}}
                    <section>
                        {{-- Header --}}
                        <p class="mb-3 border-bottom text-secondary fw-semi-bold">
                            {{ __('entity_forms')['client']['basic_data_section'] }}
                        </p>

                        {{-- Name --}}
                        <div class="form-group row justify-content-center">
                            <label for="client_name" class="text-center col-md-3 adjusted_label">
                                {{ __('entity_fields')['common']['name'] }}
                            </label>

                            <div class="col-md-8">
                                <input type="text" id="client_name" name="client_name" required
                                    class="form-control" placeholder="{{ __('entity_forms')['client']['name'] }}">
                            </div>
                        </div>

                        {{-- Phone --}}
                        <div class="form-group row justify-content-center">
                            <label for="client_phone" class="text-center col-md-3 adjusted_label">
                                {{ __('entity_fields')['common']['phone'] }}
                            </label>

                            <div class="col-md-8">
                                <input type="tel" id="client_phone" name="client_phone"
                                    class="form-control" placeholder="+() 000-000-0000">
                            </div>
                        </div>

                        {{-- Email --}}
                        <div class="form-group row justify-content-center">
                            <label for="client_email" class="text-center col-md-3 adjusted_label">
                                {{ __('entity_fields')['common']['email'] }}
                            </label>

                            <div class="col-md-8">
                                <input type="text" id="client_email" name="client_email"
                                    class="form-control" placeholder="ejemplo@gmail.com">
                            </div>
                        </div>

                        {{-- State --}}
                        <div class="form-group row justify-content-center">
                            <label for="client_state" class="text-center col-md-3 adjusted_label">
                                {{ __('entity_fields')['client']['state'] }}
                            </label>

                            <div class="col-md-8">
                                <input type="text" id="client_state" name="client_state"
                                    class="form-control" placeholder="{{ __('entity_forms')['client']['state'] }}">
                            </div>
                        </div>
                    </section>

                    {{-- Identity Documents --}}
                    <section>
                        {{-- Header --}}
                        @if ($has_identity_documents)
                            <p class="my-3 border-bottom text-secondary fw-semi-bold">
                                {{ __('entity_forms')['client']['identity_document_section'] }}
                            </p>
                        @endif

                        {{-- Identity Document Type --}}
                        <div class="form-group row justify-content-center @if(!$has_identity_documents) d-none @endif">
                            <label for="document_type" class="text-center col-md-3 adjusted_label">
                                {{ __('entity_fields')['client']['identity_document_type'] }}
                            </label>

                            <div class="col-8">
                                <select id="document_type" name="document_type" required
                                    class="form-control form-control-harsi"
                                >
                                    <option value="none">
                                        {{ __('entity_forms')['client']['none'] }}
                                    </option>
                                    <option value="voter_id">
                                        {{ __('entity_forms')['client']['voter_id'] }}
                                    </option>
                                    <option value="passport">
                                        {{ __('entity_forms')['client']['passport'] }}
                                    </option>
                                    <option value="drivers_license">
                                        {{ __('entity_forms')['client']['drivers_license'] }}
                                    </option>
                                </select>
                            </div>
                        </div>

                        {{-- Identity Document Number --}}
                        <div class="form-group row justify-content-center @if(!$has_identity_documents) d-none @endif">
                            <label for="document_number" class="text-center col-md-3 adjusted_label">
                                {{ __('entity_fields')['client']['identity_document_number'] }}
                            </label>

                            <div class="col-md-8">
                                <input type="text" id="document_number" name="document_number" required
                                    class="form-control" placeholder="{{ __('entity_forms')['client']['document_number'] }}">
                            </div>
                        </div>
                    </section>

                    {{-- Behavior Controls --}}
                    <section>
                        {{-- Header --}}
                        <p class="my-3 border-bottom text-secondary fw-semi-bold">
                            {{ __('entity_forms')['client']['behavior_section'] }}
                        </p>

                        {{-- Guest Segment --}}
                        <div class="form-group row justify-content-center">
                            <label for="customer_segment" class="text-center col-md-4 adjusted_label">
                                {{ __('entity_fields')['client']['customer_segment'] }}
                            </label>

                            <div class="col-7">
                                <select id="customer_segment" name="customer_segment" required
                                    class="form-control form-control-harsi"
                                >
                                    @foreach ($custom_segments as $segments)
                                        <option value="{{ $segments->value }}">
                                            {{ $segments->label() }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                        {{-- Behavior Reports --}}
                        <div class="form-group row justify-content-center">
                            <label for="behavior_report" class="text-center col-md-5 adjusted_label">
                                {{ __('entity_fields')['client']['behavior_report'] }}
                            </label>

                            <div class="col-6">
                                <select id="behavior_report" name="behavior_report" required
                                    class="form-control form-control-harsi"
                                >
                                    @foreach ($behavior_reports as $reports)
                                        <option value="{{ $reports->value }}">
                                            {{ $reports->label() }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>

                    </section>

                    {{-- Loyalty Data --}}
                    <section>
                        {{-- Header --}}
                        @if ($has_discounts)
                            <p class="my-3 border-bottom text-secondary fw-semi-bold">
                                {{ __('entity_forms')['client']['loyalty_section'] }}
                            </p>
                        @endif

                        {{-- Discount per Loyalty --}}
                        <div class="form-group row justify-content-center @if(!$has_discounts) d-none @endif">
                            <label for="discount_per_loyalty" class="text-center col-md-6 adjusted_label">
                                {{ __('entity_forms')['client']['discount_per_loyalty'] }}
                            </label>

                            <div class="col-md-5">
                                <input type="number" id="discount_per_loyalty" name="discount_per_loyalty"
                                    step="0.01" min="0" value="0.00" required class="form-control"
                                    onkeydown="return event.key !== '-'" onchange="roundDecimals(this);"
                                    placeholder="0.0 %">
                            </div>
                        </div>
                    </section>

                    {{-- Buttons --}}
                    <section class="mt-5 form-group" align="center">
                        <input type="hidden" name="action" id="action"/>
                        <input type="hidden" name="hidden_id" id="hidden_id"/>

                        <input type="submit" name="action_button" id="action_button" class="p-1 btn boton"
                            value="{{ __('common_actions')['add'] }}" />
                    </section>
                </form>

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

{{-- Scripts --}}
<script>
  //* CRUD Control
    $(document).ready(function () {
        // Open For Create
        $('#create_record').click(function () {
            $('.modal_title').text("{{ __('entity_forms')['common']['modal_title'] }}");
            $('.modal_subtitle').text("- {{ __('entities')['hotel']['client'] }} -");
            $('#action_button').val("{{ __('common_actions')['add'] }}");

            $('#document_number').val("")
                .attr({
                    'readonly': true,
                    'required': false,
                }).css("background-color", "#E7E4E4");

            $('#action').val("Add");
            $('#clientFormModal').modal('show');
            $('#client_form')[0].reset();
        });

        // Open For Edit
        $(document).on('click', '.edit', function () {
            var id = $(this).attr('id');
            $('#form_result').html('');
            $.ajax({
                url: `/clients/${id}/edit`,
                dataType: "json",
                success: function (html) {
                  // Parse Data
                    const data = html.data;

                  // Fill Data
                    // Basic Data
                    $('#hidden_id').val(data.id);
                    $('#client_name').val(data.client_name);
                    $('#client_phone').val(data.client_phone);
                    $('#client_email').val(data.client_email);
                    $('#client_state').val(data.client_state);

                    // Identity Documents
                    $('#document_type').val(data.identity_document_type);
                    $('#document_number').val(data.identity_document_number);

                    // Behavior Control
                    $('#customer_segment').val(data.customer_segment);
                    $('#behavior_report').val(data.behavior_report);

                    // Loyalty
                    $('#discount_per_loyalty').val(data.discount_per_loyalty);

                  // Special Cases
                    const no_identity_document = data.identity_document_type === "none";
                    $('#document_number')
                        .prop('readonly', no_identity_document).prop('required', !no_identity_document)
                        .css("background-color", no_identity_document ? "#E7E4E4" : "#FFF");

                  // Render Modal
                    $('.modal_title').text("{{ __('entity_forms')['common']['modal_title_2'] }}");
                    $('.modal_subtitle').text(`{{ __('entities')['hotel']['client'] }} #${data.id}`);
                    $('#action_button').val("{{ __('common_actions')['update'] }}");
                    $('#action').val("Edit");
                    $('#clientFormModal').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: `/clients/${id}/destroy`,
                        success: function (data) {
                            setTimeout(function () {
                                Swal.fire(
                                    "{{ __('common_responses_and_messages')['deleted'] }}",
                                    "{{ __('common_responses_and_messages')['deleted_successfully'] }}",
                                    'success'
                                );
                                $('#clients_table').DataTable().ajax.reload(null, false);
                            }, 200);
                        },

                        error: function (error) {
                            Swal.fire(
                                "{{ __('common_responses_and_messages')['rejected_action'] }}",
                                error.responseJSON.message,
                                'error'
                            );
                        }
                    });
                }
            });
        });

        // Submit Form
        $('#client_form').on('submit', function (event) {
            event.preventDefault();
            if ($('#action').val() == 'Add') {
                $.ajax({
                    url: "{{ route('clients.store') }}",
                    method: "POST",
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    dataType: "json",
                    success: function (data) {
                        if (data.success) {
                            Swal.fire(
                                "{{ __('common_responses_and_messages')['success'] }}",
                                "{{ __('common_responses_and_messages')['created_successfully'] }}",
                                'success'
                            );
                            $('#client_form')[0].reset();
                            $('#clients_table').DataTable().ajax.reload(null, false);
                        }
                        $('#clientFormModal').modal('hide');
                    }
                })
            }

            if ($('#action').val() == "Edit") {
                $.ajax({
                    url: "{{ route('clients.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'
                        );
                        $('#clientFormModal').modal('hide');
                        $('#client_form')[0].reset();
                        $('#clients_table').DataTable().ajax.reload(null, false);
                    }
                });
            }
        });
    });

  //* Support Functions
    // Formatters
    function roundDecimals(input, decimal_limit = 2, default_value = 0.0) {
        let valor = parseFloat(input.value);

        if (isNaN(valor)) valor= default_value;

        const result = parseFloat(valor.toFixed(decimal_limit));
        const exceedsTwoDecimals = /\d\.\d{3,}/.test(valor);

        if (exceedsTwoDecimals) {
            input.value = Math.abs(result).toFixed(decimal_limit);
        } else {
            input.value = Math.abs(result === 0 ? 0 : valor).toFixed(decimal_limit);
        }

        return;
    }

    // Identity Document Control
    $(function () {
        $('#document_type').on('input', onSelectDocumentType);
    });

    function onSelectDocumentType() {
        var document_type = $(this).val();

        if(document_type === "none") {
            $('#document_number').val("")
                .attr({
                    'readonly': true,
                    'required': false,
                }).css("background-color", "#E7E4E4");
        }else {
            $('#document_number')
                .attr({
                    'readonly': false,
                    'required': true,
                }).css("background-color", "#FFF");
        }
    }

</script>
