@php
    use App\Helpers\Formats\FormatCurrencyHelper;
    use \App\Helpers\Environment\SystemFeaturesHelper;
@endphp

{{-- Form Modal --}}
<div id="formModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="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" enctype="multipart/form-data" id="sample_form"
                    class="pt-3 form-horizontal" autocomplete="off"
                > @csrf

                    {{-- Category --}}
                    <div class="row justify-content-center form-group">
                        <label class="text-center control-label col-md-3">
                            {{ __('entity_fields')['product']['category'] }}
                        </label>
                        <div class="col-md-7">
                            <select type="text" id="category_id" name="category_id" class="form-control" required>
                                <option value="" disabled selected>-- {{ __('common_actions')['select'] }} --</option>

                                @foreach($categories as $cat)
                                    <option value="{{ $cat->id }}">{{ $cat->category_name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    {{-- Name --}}
                    <div class="row justify-content-center form-group">
                        <label class="text-center control-label col-md-2">
                            {{ __('entity_fields')['common']['name'] }}
                        </label>
                        <div class="col-md-8">
                            <input type="text" name="titulo" id="titulo" required
                                max="250" min="1" class="form-control"
                                placeholder="{{ __('entity_forms')['product']['name'] }}"/>
                        </div>
                    </div>

                    {{-- Price --}}
                    <div class="row justify-content-center form-group">
                        <label class="text-center control-label col-md-2">{{ __('entity_fields')['common']['price'] }}</label>
                        <div class="col-md-8">
                            <input type="number" name="precio" id="precio" required
                                step="0.01" onchange="roundDecimals(this)" class="form-control"
                                placeholder="{{ FormatCurrencyHelper::currencyPlaceHolder() }}"
                            />
                        </div>
                    </div>

                    {{-- Barcode --}}
                    @if (SystemFeaturesHelper::getFeatureStatus("product_barcodes"))
                        <div class="mb-4 row justify-content-center form-group">
                            <label class="text-center control-label col-md-4">
                                {{ __('entity_fields')['product']['barcode'] }}
                            </label>
                            <div class="col-md-6">
                                <input type="text" name="barcode" id="barcode"
                                    max="100" min="3" inputmode="numeric"
                                    autocomplete="off" class="form-control"
                                    placeholder="{{ __('entity_fields')['product']['barcode'] }}"/>
                            </div>

                            <small id="password_message" class="pt-2 pl-3 text-center" style="color:#0d6889; font-weight: 500">
                                <i class="pr-1 fas fa-info-circle"></i>
                                {{ __('entity_forms')['product']['barcode_indications'] }}
                            </small>
                        </div>
                    @endif

                    {{-- Buttons --}}
                    <div class="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="btn boton"
                            value="{{ __('common_actions')['add'] }}" />
                    </div>
                </form>

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

{{-- Scripts --}}
<script>
  //* CRUD Actions
    $(document).ready(function(){
      // Open For Create
        $('#create_record').click(function(){
          // Update titles
            $('.modal_title').text("{{ __('entity_forms')['common']['modal_title'] }}");
            $('.modal_subtitle').text("- {{ __('entities')['restaurant']['product'] }} -");

          // Define form action
            $('#action_button').val("{{ __('common_actions')['add'] }}");
            $('#action').val("Add");

          // Render Components
            $('#formModal').modal('show');
            $('#sample_form')[0].reset();
        });

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

            $.ajax({
                url:`/products/${id}/edit`,
                dataType:"json",
                success:function(html){
                  // Seed form
                    $('#category_id').val(html.data.category_id);
                    $('#titulo').val(html.data.product_name);
                    $('#barcode').val(html.data.product_barcode);
                    $('#precio').val(html.data.product_price);
                    $('#hidden_id').val(html.data.id);

                  // Update titles
                    $('.modal_title').text("{{ __('entity_forms')['common']['modal_title_2'] }}");
                    $('.modal_subtitle').text(`{{ __('entities')['restaurant']['product'] }} #${html.data.id}`);

                  // Render Components
                    $('#action_button').val("{{ __('common_actions')['update'] }}");
                    $('#action').val("Edit");
                    $('#formModal').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) => {
                if (result.value) {
                    $.ajax({
                        url: `/products/${id}/destroy`,
                        success:function(data) {
                            setTimeout(function () {
                                Swal.fire(
                                    "{{ __('common_responses_and_messages')['deleted'] }}",
                                    "{{ __('common_responses_and_messages')['deleted_successfully'] }}",
                                    'success'
                                );

                                $('#products_table').DataTable().ajax.reload(null, false);
                            }, 200);
                        }
                    });
                }
            });
        });

      // Submit Form
        $('#sample_form').on('submit', function(event){
            event.preventDefault();
            if($('#action').val() == 'Add') {
                $.ajax({
                    url:"{{ route('products.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'
                        );

                        $('#sample_form')[0].reset();
                        $('#products_table').DataTable().ajax.reload(null, false);
                        $('#formModal').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() == "Edit") {
                $.ajax({
                    url:"{{ route('products.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'
                        );

                        $('#sample_form')[0].reset();
                        $('#formModal').modal('hide');
                        $('#products_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;
                    }
                });
            }
        });

    });

  //* 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;
    }
</script>
