{{-- Modal --}}
<div id="taxFormatFormModal" class="mt-5 modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="p-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="text-center modal_subtitle"></h6>

                {{-- Dynamic Agency Logo --}}
                <div class="container p-3 my-4 center_image">
                    <img id="logo_preview" class="img-fluid dynamic_image"
                        style="max-width: 100%; border-radius: 15px" src="{{ $default_logo }}"
                        alt="Logo Preview">
                </div>

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

                    {{-- Serie --}}
                    <div class="form-group row justify-content-center">
                        <label for="serie" class="text-center col-md-3">
                            {{ __("entity_fields")['tax_format']['serie'] }}
                        </label>
                        <div class="col-md-9">
                            <input type="text" name="serie" id="serie" required
                                minlength="1" maxlength="15" class="form-control"
                                placeholder="HARSI-000000"/>
                        </div>
                    </div>

                    {{-- Base Color --}}
                    <div class="form-group row justify-content-center">
                        <label for="base_color" class="text-center col-md-3">
                            {{ __("entity_fields")['tax_format']['base_color'] }}
                        </label>

                        <div class="col-md-9">
                            <input type="color" name="base_color" id="base_color" class="form-control" value="#0D6889">
                        </div>

                        <div class="mt-2 col-12 offset-1">
                            <small class="text-muted">
                                <i class="fas fa-info-circle"></i>
                                &nbsp;{{ __("entity_forms")['tax_format']['base_color_indications'] }}
                            </small>
                        </div>
                    </div>

                    {{-- Logo --}}
                    <div class="mb-4 form-group row justify-content-center">
                        <label for="format_logo" style="padding-top: 0.25rem !important"
                            class="text-center col-md-3">{{ __("entity_fields")['common']['logo'] }}</label>
                        <div class="col-md-9">
                            <input type="file" name="format_logo" id="format_logo"
                                accept="image/*" aria-label="Select a Logo" class="border"/>
                        </div>

                        <div id="logo_message" class="mt-2 col-12 offset-1">
                            <small class="indications harsi-color">
                                <i class="fas fa-info-circle"></i>
                                &nbsp;{{ __("entity_forms")['tax_format']['logo_indications'] }}
                            </small>
                        </div>
                    </div>

                    {{-- Buttons --}}
                    <div class="form-group" align="center">
                        {{-- 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>
  //* CRUD Control
    $(document).ready(function () {
      //- On close Establishment/Settings form
        $('#taxFormatFormModal').on('hide.bs.modal', function () {
            document.activeElement.blur();
        });

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

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

            // Form Cleaning
            $('#logo_message').hide();
            $('#taxFormatFormModal').modal('show');
            $('#tax_format_form')[0].reset();
            $("#logo_preview").attr("src", "{{ $default_logo }}");
        });

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

                success: function (result) {
                    const data = result.data;
                    // Fill Fields
                    $('#hidden_id').val(data.id);
                    $('#serie').val(data.serie);
                    $('#base_col').val(data.base_color);
                    $("#logo_preview").attr("src", data.url_logo);

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

                    // Form Cleaning
                    $('#logo_message').show();
                    $('#action').val("Update");
                    $('#action_message').text("{{ __('common_actions')['update'] }}");
                    $('#taxFormatFormModal').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/formats/${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_format_table').DataTable().ajax.reload(null, false);
                            }, 200);
                        }
                    });
                }
            });
        });

      // Submit Form
        $('#tax_format_form').on('submit', function (event) {
            event.preventDefault();
            if ($('#action').val() == 'Store') {
                $.ajax({
                    url: "{{ route('tax-formats.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_format_form')[0].reset();
                        $('#tax_format_table').DataTable().ajax.reload(null, false);
                        $('#taxFormatFormModal').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-formats.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_format_form')[0].reset();
                        $('#taxFormatFormModal').modal('hide');
                        $('#tax_format_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;
                    },
                });
            }
        });
    });

    // On change Input logo
    $(document).ready(function () {
        // Input File
        const format_logo = document.getElementById('format_logo');
        // IMG tag
        const logo_preview = document.getElementById('logo_preview');

        format_logo.addEventListener('change', function (e) {
            const reader = new FileReader();

            reader.onload = function (e) {
                $("#logo_preview").attr("src", e.target.result);
            };

            reader.readAsDataURL(e.target.files[0]);
        });
    });
</script>
