<div>
    @include('parts.loading')
    @include('parts.alerts')


    @if ($mode == 'list')
        <div class="row mt-5">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-gray-100">
                        <div class="form-row form-row-filter">
                            <div class="col-xl-2 col-lg-4 col-sm-6">
                                <select class="form-control" wire:model="search_status">
                                    <option value="">.:: Estatus ::.</option>
                                    @foreach (config('const.claim-status') as $key => $value)
                                        <option value="{{ $key }}">{{ $value }}</option>
                                    @endforeach

                                </select>
                            </div>
                            <div class="col-xl-2 col-lg-4 col-sm-6">
                                <select class="form-control" wire:model="search_product">
                                    <option value="">.:: Producto ::.</option>
                                    @foreach ($products_list as $item)
                                        <option value="{{ $item->id }}">
                                            @if (count($item->product->details) > 1)
                                                {{ $item->product->name }} -
                                            @endif
                                            {{ $item->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            @if (Auth::user()->type == 'admin')
                                <div class="col-xl-2 col-lg-4 col-sm-6">
                                    <select class="form-control" wire:model="search_agent">
                                        <option value="">.:: Agente ::.</option>
                                        @foreach ($agents_list as $agent)
                                            <option value="{{ $agent->id }}">{{ $agent->fullname }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            @endif

                            <div class="col-xl-2 col-lg-4 col-sm-6">
                                <input type="text" class="form-control" wire:model="search_date" id="search_date"
                                    placeholder="Fecha de creación">
                            </div>
                            <div
                                class="{{ Auth::user()->type == 'admin' ? 'col-xl-2 col-lg-4 col-sm-6' : 'col-xl-4 col-lg-8 col-sm-12' }}">
                                <div class="wrapper-search">
                                    <input type="text" id="search" class="form-control"
                                        wire:model.debounce.1000ms="search" placeholder="Buscar...">
                                    @if (!empty($search))
                                        <button type="button" class="btn" id="btn-search">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    @endif
                                </div>
                            </div>
                            <div class="col-xl-2 col-lg-4 col-sm-6">
                                <button wire:click="create()"
                                    class="btn btn-primary btn-block float-right btn-add-quote">
                                    <i class="fas fa-plus"></i>
                                    Crear Reclamación
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-content">
                        <div class="card-body">
                            @if ($claims->count())
                                <div class="table-responsive min-height-500">
                                    <table class="table">
                                        <thead class="thead-light">
                                            <tr>
                                                <th style="min-width: 50px;">Reclamación</th>
                                                <th style="min-width: 200px;">Fecha de creación</th>
                                                <th style="min-width: 150px;">Cédula / RNC</th>
                                                <th style="min-width: 160px;">Nombre del cliente</th>
                                                @if (Auth::user()->type == 'admin')
                                                    <th style="min-width: 160px;">Nombre del agente</th>
                                                @endif
                                                <th style="min-width: 200px;">Producto</th>
                                                <th style="min-width: 210px;">Última actualización</th>
                                                <th style="min-width: 50px;">Estatus</th>
                                                <th style="min-width: 50px;">Archivos</th>
                                                <th style="min-width: 50px;">Reabierto</th>
                                                <th class="text-center" style="min-width: 100px;">Acciones</th>
                                            </tr>
                                        </thead>
                                        <tbody>

                                            @foreach ($claims as $key => $value)
                                                <tr>
                                                    <th>{{ $value->code }}</th>
                                                    <td>{{ $value->datetime_formatted }}</td>
                                                    <td>{{ $value->user->document }}</td>
                                                    <td>{{ $value->user->fullname }} <span class="d-block font-weight-bold">{{ $value->policy_number ? '#' : '' }}{{ $value->policy_number }}</span> </td>

                                                    @if (Auth::user()->type == 'admin')
                                                        <td>{{ !empty($value->admin->fullname) ? $value->admin->fullname : '' }}
                                                        </td>
                                                    @endif

                                                    <td>
                                                        @if (count($value->product_detail->product->details) > 1)
                                                            {{ $value->product_detail->product->name }} -
                                                        @endif
                                                        {{ $value->product_detail->name }}
                                                    </td>
                                                    <td>{{ $value->update_datetime }}</td>
                                                    <td>
                                                        <span
                                                            class="badge bg-{{ config('const.claim-status-badges')[$value->status] }} text-white">{{ $value->status_name }}</span>
                                                    </td>
                                                    <td class="text-center" id="td_{{ $value->id }}">
                                                        <i class="fas fa-cloud-upload-alt files_claim text-{{ count($value->files) > 0 ? 'blue' : 'red' }}"
                                                            style="font-size: 1.3rem; cursor:pointer;"
                                                            data-toggle="tooltip" data-placement="bottom"
                                                            title="{{ count($value->files) > 0 ? 'Con documento' : 'Sin documento' }}"
                                                            onclick="show({{ $value->files }}, '{{ $value->status }}')"
                                                            wire:click='addClaimFiles({{ $value->id }})'></i>
                                                    </td>
                                                    <td>
                                                        <div class="text-center">
                                                            <span>
                                                                @if ($value->reopened == 0)
                                                                    No
                                                                @else
                                                                    Si
                                                                @endif
                                                            </span>
                                                        </div>
                                                    </td>
                                                    <td class="text-center">
                                                        <div class="btn-group btn-group-sm">
                                                            <a href="#" class="dropdown-toggle" data-toggle="dropdown"
                                                                aria-haspopup="true" aria-expanded="false">
                                                                <i class="fas fa-ellipsis-h"></i>
                                                            </a>
                                                            <div class="dropdown-menu dropdown-menu-right">
                                                                <button wire:click="show({{ $value->id }})"
                                                                    class="dropdown-item">
                                                                    <i class="fas fa-eye"></i> Ver
                                                                </button>
                                                                @if ($value->status == 'open' && ((int) $value->reopened === 0 || (int) $value->reopened === 1))
                                                                    <button wire:click="edit({{ $value->id }})"
                                                                        class="dropdown-item">
                                                                        <i class="fas fa-pencil-alt mr-1"></i> Editar
                                                                    </button>
                                                                @endif

                                                                @if ($value->status == 'open' && ((int) $value->reopened === 0 || (int) $value->reopened === 1))
                                                                    <button @php
                                                                        $arr = ['id' => $value->id, 'full_name' => $value->user->fullname];
                                                                    @endphp
                                                                        wire:click="$emit('triggerApproved', ['{{ $value->id }}', '{{ $value->user->fullname }}', '{{ formatDecimal($value->amount_approved) }}'])"
                                                                        class="dropdown-item text-success">
                                                                        <i class="far fa-thumbs-up"></i> Cerrar
                                                                    </button>
                                                                    <button
                                                                        wire:click="edit_reject({{ $value->id }})"
                                                                        class="dropdown-item text-danger rejected">
                                                                        <i class="far fa-thumbs-down"></i> Rechazar
                                                                    </button>
                                                                @endif

                                                                @if ((int) $value->reopened === 0 && $value->status == 'rejected')
                                                                    <button wire:click="open({{ $value->id }})"
                                                                        class="dropdown-item text-success">
                                                                        <i class="fas fa-lock-open"></i> Abrir
                                                                    </button>
                                                                @endif
                                                                <button class="dropdown-item"
                                                                    wire:click="get_pdf({{ $value->id }})">
                                                                    <i class="fas fa-download mr-1"></i>Descargar PDF
                                                                </button>
                                                                {{-- @if ($value->status == 'open' && ((int) $value->reopened === 0 || (int) $value->reopened === 1))
                                                                    <button
                                                                        wire:click="$emit('triggerDestroy',{{ $value->id }})"
                                                                        class="dropdown-item text-danger">
                                                                        <i class="far fa-trash-alt mr-1"></i> Eliminar
                                                                    </button>
                                                                @endif --}}
                                                            </div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <th colspan="11">
                                                    {{ $claims->links() }}
                                                </th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                    <div class="position-relative">

                                    </div>
                                    {{-- Snipper --}}
                                    <div class="spinner-border text-primary position-absolute spinner_pdf {{ $none_spinner_pdf }}"
                                        role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>

                                </div>
                            @else
                                <div class="alert alert-secondary" role="alert">
                                    No se encontraron reclamaciones
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @elseif ($mode == "show")
        @include('livewire.claims.show')
    @else
        @include('livewire.claims.form')
    @endif
</div>

<!-- Modal rechazar reclamacion-->
<x-modal modalId="rejectedModal" modalNameDetalleLabel="modalListGenericDetalleLabel" bodyId="" footerId="">
    @slot('modalTitle')
        Rechazar reclamación
    @endslot
    @slot('modalContent')
        <div class="form-group">
            <label for="calendarModalInput">Detalle del rechazo de la reclamación</label>
            <textarea wire:model.defer="description" id="description" class="form-control"></textarea>
            @error('description') <span class="text-danger">{{ $message }}</span>@enderror
            <div class="mt-2"></div>
            <span class="text-danger d-none" id="err_descr_rejec">El campo descripción es obligatorio.</span>
        </div>
    @endslot
    @slot('modalFooter')
        <button wire:ignore type="button" class="btn btn-danger d-none" id="calendarModalDelete">Eliminar</button>
        <div>
            <button wire:ignore type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
            <button type="button" class="btn btn-danger" id="acc_reject">¡Sí,
                rechazar!</button>
        </div>
    @endslot
</x-modal>
<!-- Modal -->
<!-- Modal -->
<script src="https://unpkg.com/filepond@^4/dist/filepond.js"></script>
<!-- Modal files reclamacion-->
<x-modal modalId="filesModal" modalNameDetalleLabel="modalfilesDetalleLabel" bodyId="" footerId="">
    @slot('modalTitle')
        Subir archivos
    @endslot
    @slot('modalContent')
        <div class="form-group" id="hiddenUpload">
            <div>
                {{-- <input wire:model="newDocument" type="file"> --}}
                @error('upload')
                    {{ $message }}
                @enderror
                <div wire:ignore x-data x-init="
                                                                                        FilePond.setOptions({
                                                                                                server: {
                                                                                                process: (fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
                                                                                                    $('.files_err').html('');
                                                                                                         @this.upload('files', file, load, error, progress, fieldName);
                                                                                                        },
                                                                                                        revert: (filename, load) => {
                                                                                                             $('.files_err').html('');
                                                                                                            @this.removeUpload('files', filename, load)
                                                                                                        },
                                                                                                    },

                                                                                                });
                                                                                                window.Pond = FilePond.create($refs.input);
                                                                                                this.addEventListener('pondReset', e => {
                                                                                                    Pond.removeFiles();
                                                                                                });
                                                                            ">

                    <input wire:model="files" type="file" x-ref="input" accept="image/png, image/gif, image/jpeg">
                    <div class="files_err mb-3" wire:model='$validation_errors'>

                    </div>

                    <button wire:click="upload" class="btn btn-primary" id="upload">Subir</button>


                    @error('files')
                        <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

            </div>

        </div>
        <div class="row mt-5">
            <div class="col-12">
                <div class="card">
                    <div class="card-header bg-gray-100">


                    </div>



                    <div class="card-content">
                        <div class="spinner-border text-primary addFiles d-none" role="status" style="
                                                                                                position: absolute;
                                                                                                left: 45%;
                                                                                                top: 50%;
                                                                                                height: 3rem;
                                                                                                width: 3rem;
                                                                                                z-index: 999;
                                                                                            ">
                            <span class="visually-hidden">Loading...</span>
                        </div>

                        <div class="card-body files-content" id="files-content">

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

        </div>
    @endslot
    @slot('modalFooter')
        <button wire:ignore type="button" class="btn btn-danger d-none" id="calendarModalDelete">Eliminar</button>
        <div>
            <button wire:ignore type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Cerrar</button>
        </div>
    @endslot
</x-modal>
<script>
    window.addEventListener('err_files', event => {

        $('.addFiles').addClass('d-none');

        var newHTML = "";
        if (event.detail.files.files) {
            for (var i = 0; i < event.detail.files.files.length; i++) {
                newHTML = newHTML + '<span class="text-danger">' + event.detail.files.files[i] + '</span>';
            }
        }

        if (event.detail.files.extension) {
            for (var i = 0; i < event.detail.files.extension.length; i++) {
                newHTML = newHTML + '<span class="text-danger">' + event.detail.files.extension[i] + '</span>';
            }
        }

        $(".files_err").html(newHTML);
    })

    window.addEventListener('files', event => {
        show(event.detail.files);
    })

    function show(files, status = null) {
        // Resetear pond
        if (typeof Pond !== 'undefined')
            Pond.removeFiles();

        var hidden;
        if (status != 'open' && status != null) {
            hidden = 'd-none';
            document.getElementById('hiddenUpload').style.display = 'none';
        } else {
            document.getElementById('hiddenUpload').style.display = 'block';
        }


        $('.files_err').html('');

        if (files.length > 0) {
            var claim_files = ``;
            files.forEach(element => {
                claim_files += `
                    <tr>
                        <td>
                           ${element.datetime_formatted}
                        </td>
                        <td>
                            <a href="{{ asset('storage/claims/files/') }}/${element.code}/${element.file}" download class="p-0 btn btn-link btn-link2 text-primary ">
                            ${element.file}
                            </a>
                        </td>
                        <td class="${hidden}">
                            <button onclick="files(${element.id})"  class="dropdown-item btn-link text-danger">
                                <i class="far fa-trash-alt mr-1"></i> Eliminar
                             </button>
                         </td>
                    </tr>
                `;
            });
            document.getElementById('files-content').innerHTML = `
                <table class="table">
                    <thead class="thead-light">
                        <tr>
                            <th>Fecha de creación</th>
                            <th>Archivo</th>
                            <th class="text-center ${hidden}" style="width: 100px;">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>${claim_files}</tbody>
                </table>
            `;

        } else {
            document.getElementById('files-content').innerHTML = `
                <p style='padding:10px'>
                    La reclamación aún no tiene archivos disponibles
                </p>
            `;
        }

        $('.addFiles').addClass('d-none');

        //Modal files
        $('#filesModal').modal('show');
    }

    function files(id) {
        Swal.fire({
            title: '¿Estás seguro?',
            text: "¡No podrás revertir esto!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ff5b5c',
            cancelButtonColor: '#a3afbd',
            confirmButtonText: '¡Sí, bórralo!'
        }).then((result) => {
            if (result.isConfirmed) {
                $('.addFiles').removeClass('d-none');

                @this.call('destroyFiles', id);
            }
        });

    }
</script>

@section('js')
    @include('parts.js-destroy')
    @include('parts.js-preview')
    @include('parts.js-search')

    {{-- Script para quickly a reclamaciones --}}
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    {{-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.1.2/tailwind.min.css"
        integrity="sha512-RntatPOhEcQEA81gC/esYoCkGkL7AYV7TeTPoU+R9zE44/yWxVvLIBfBSaMu78rhoDd73ZeRHXRJN5+aPEK53Q=="
        crossorigin="anonymous" /> --}}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/2.3.0/alpine.js"
        integrity="sha512-nIwdJlD5/vHj23CbO2iHCXtsqzdTTx3e3uAmpTm4x2Y8xCIFyWu4cSIV8GaGe2UNVq86/1h9EgUZy7tn243qdA=="
        crossorigin="anonymous"></script>

    <script>
        document.addEventListener('livewire:load', function() {
            init();

            $(document).on('change', '#search_date', function() {
                @this.set('search_date', $(this).val());
            });

            //TRADUDIR FILEPOINT ES
            const labels_es_ES = {
                labelIdle: 'Arrastra y suelta tus archivos o <span class = "filepond--label-action"> Examinar <span>',
                labelInvalidField: "El campo contiene archivos inválidos",
                labelFileWaitingForSize: "Esperando tamaño",
                labelFileSizeNotAvailable: "Tamaño no disponible",
                labelFileLoading: "Cargando",
                labelFileLoadError: "Error durante la carga",
                labelFileProcessing: "Cargando",
                labelFileProcessingComplete: "Carga completa",
                labelFileProcessingAborted: "Carga cancelada",
                labelFileProcessingError: "Error durante la carga",
                labelFileProcessingRevertError: "Error durante la reversión",
                labelFileRemoveError: "Error durante la eliminación",
                labelTapToCancel: "toca para cancelar",
                labelTapToRetry: "tocar para volver a intentar",
                labelTapToUndo: "tocar para deshacer",
                labelButtonRemoveItem: "Eliminar",
                labelButtonAbortItemLoad: "Abortar",
                labelButtonRetryItemLoad: "Reintentar",
                labelButtonAbortItemProcessing: "Cancelar",
                labelButtonUndoItemProcessing: "Deshacer",
                labelButtonRetryItemProcessing: "Reintentar",
                labelButtonProcessItem: "Cargar",
                labelMaxFileSizeExceeded: "El archivo es demasiado grande",
                labelMaxFileSize: "El tamaño máximo del archivo es {filesize}",
                labelMaxTotalFileSizeExceeded: "Tamaño total máximo excedido",
                labelMaxTotalFileSize: "El tamaño total máximo del archivo es {filesize}",
                labelFileTypeNotAllowed: "Archivo de tipo no válido",
                fileValidateTypeLabelExpectedTypes: "Espera {allButLastType} o {lastType}",
                imageValidateSizeLabelFormatError: "Tipo de imagen no compatible",
                imageValidateSizeLabelImageSizeTooSmall: "La imagen es demasiado pequeña",
                imageValidateSizeLabelImageSizeTooBig: "La imagen es demasiado grande",
                imageValidateSizeLabelExpectedMinSize: "El tamaño mínimo es {minWidth} × {minHeight}",
                imageValidateSizeLabelExpectedMaxSize: "El tamaño máximo es {maxWidth} × {maxHeight}",
                imageValidateSizeLabelImageResolutionTooLow: "La resolución es demasiado baja",
                imageValidateSizeLabelImageResolutionTooHigh: "La resolución es demasiado alta",
                imageValidateSizeLabelExpectedMinResolution: "La resolución mínima es {minResolution}",
                imageValidateSizeLabelExpectedMaxResolution: "La resolución máxima es {maxResolution}",
            };
            FilePond.setOptions(labels_es_ES)

        });
        window.addEventListener('init-libs', event => {
            init();
        });

        function init() {
            $('#search_date').daterangepicker({
                autoUpdateInput: false,
                "locale": date_locale
            }, function(start, end, label) {});
            $('#search_date').on('apply.daterangepicker', function(ev, picker) {
                $(this).val(picker.startDate.format('DD/MM/YYYY') + ' - ' + picker.endDate.format('DD/MM/YYYY'));
                @this.set('search_date', $(this).val());
            });
            $('#search_date').on('cancel.daterangepicker', function(ev, picker) {
                $(this).val('');
                @this.set('search_date', $(this).val());
            });

            if (tinyMCE.get('description')) {
                tinymce.remove('#description');
            }
            tinyMCE.init({
                selector: '#description',
                plugins: 'contextmenu preview paste importcss searchreplace directionality code visualchars fullscreen  link codesample table charmap hr pagebreak nonbreaking anchor toc advlist lists  textpattern noneditable help charmap emoticons image',
                menubar: 'edit view format tools table help insert', //insert
                toolbar: 'undo redo | bold italic underline strikethrough |  formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons | fullscreen  preview save print | ltr rtl | image', //insertfile image media template link anchor codesample |
                toolbar_sticky: true,
                contextmenu: false,
                height: 400,
                paste_data_images: false,
                automatic_uploads: true,
                setup: function(editor) {
                    editor.on('init change', function() {
                        editor.save();
                    });
                    editor.on('blur', function(e) {
                        @this.set('description', editor.getContent());
                    });

                }
            });

            $('.datepicker').daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                // autoUpdateInput: false,
                minYear: 1901,
                maxYear: parseInt(moment().format('YYYY'), 10),
                "locale": date_locale
            }, function(start, end, label) {
                var years = moment().diff(start, 'years');
            });

            $('.money').mask("#,##0.00", {
                reverse: true
            });

            //tooltip
            $(function() {
                $('[data-toggle="tooltip"]').tooltip()
            })

        }


        function checkextension(el, ext) {
            var file = document.querySelector("#" + el);
            //if ( /\.(pdf)$/i.test(file.files[0].name) === false ) { alert("not an image!");file.value = ""; }
            var myRegex = new RegExp(ext, "i");
            if (myRegex.test(file.files[0].name) === false) {
                alert("Formato no permitido");
                file.value = "";
            }
        }
    </script>

@endsection

@push('scripts')
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            //ApprovedButton -> triggers the sweetAlert
            @this.on('triggerApproved', arr => {
                Swal.fire({
                    title: 'Cerrar reclamación!',
                    text: 'Cerrar la reclamación del cliente ' + arr[1],
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: '#39da8a',
                    cancelButtonColor: '#a3afbd',
                    confirmButtonText: '¡Sí, cerrar!',
                    cancelButtonText: 'Cancelar'
                }).then((result) => {
                    //if user clicks on delete
                    if (result.value) {
                        console.log(arr[2] > 0)
                        if (arr[2] > 0) {
                            // calling destroy method to delete
                            @this.call('approve', arr[0])
                            // success response
                            Swal.fire(
                                'Cerrado!',
                                'La reclamación ha sido cerrada.',
                                'success'
                            )
                        } else {
                            Swal.fire(
                                'No cerrado!',
                                'La reclamación aún no tiene monto de aprobación .',
                                'warning'
                            )
                        }

                    } else if (result.dismiss === Swal.DismissReason.cancel) {
                        // Swal.fire(
                        //     'Cancelled',
                        //     'Your imaginary file is safe :)',
                        //     'error'
                        // )
                    }
                });
            });

            //Actualizar cada vex que render
            Livewire.hook('element.updated', (el, component) => {
                //tooltip
                $(function() {
                    $('[data-toggle="tooltip"]').tooltip()
                })
            });

        })
    </script>
    <script>
        //Event mostrar modal
        window.addEventListener('rejectedModal', event => {
            $('#rejectedModal').modal('show');
        })


        //Event validar modal emit reject
        $("#acc_reject").on('click', function() {
            var myContent = tinymce.get("description").getContent();
            if (myContent) {
                $('#err_descr_rejec').addClass('d-none');
                $('#rejectedModal').modal('hide');
                Livewire.emit('reject')
            } else {
                $('#err_descr_rejec').removeClass('d-none');
            }

        })
    </script>

    <script>
        //Evento para sweetalert2 claims
        window.addEventListener('sweetalert2_claim', event => {
            if (event.detail.value == 'rejected') {
                tinymce.get("description").setContent('');
                Swal.fire(
                    'Rechazado',
                    'Reclamación rechazada exitosamente.',
                    'success'
                )
            } else if (event.detail.value == 'open') {
                Swal.fire(
                    'Abrir',
                    'La reclamación ha sido abierta exitosamente.',
                    'success'
                )
            }
        })
    </script>

    {{-- Script para descargar PDF --}}
    <script src="{{ asset('js/pdf.js') }}"></script>
    <script src="{{ asset('js/downloadjs.js') }}"></script>
    <script type="text/javascript">
        window.addEventListener('user_data_pdf', event => {
            if (event.detail.err) {
                document.querySelector('.spinner_pdf').classList.add("d-none");
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Error al descargar el PDF!',
                })
            } else {
                // function modificar pdf
                fillForm(event.detail.dateTime, event.detail.user, event.detail.fullName);
            }

        })

        async function fillForm(dateTime, user, fullName) {

            window.PDFDocument = PDFDocument;
            // Fetch the PDF with form fields
            //const formUrl = 'https://pdf-lib.js.org/assets/dod_character.pdf';
            const formUrl = "{{ asset('images/pdf/Solicitud-de-Reembolso-humano_optimize.pdf') }}";
            const formPdfBytes = await fetch(formUrl).then(res => res.arrayBuffer())

            // Load a PDF with form fields
            const pdfDoc = await PDFDocument.load(formPdfBytes)
            // Get the form containing all the fields
            const form = pdfDoc.getForm()

            // Get all fields in the PDF by their names
            const nameField = form.getTextField('name');
            const phoneField = form.getTextField('phone');
            const documentField = form.getTextField('document');
            const documentTypeField = form.getRadioGroup('document_type');
            const emailField = form.getTextField('email');
            const daylField = form.getTextField('day');
            const monthField = form.getTextField('month');
            const yearField = form.getTextField('year');

            // Fill in the basic info fields
            nameField.setText(fullName);
            phoneField.setText(user.phone);
            documentField.setText(user.document);
            documentTypeField.select('Yes');
            emailField.setText(user.email);
            daylField.setText(dateTime.day);
            monthField.setText(dateTime.month);
            yearField.setText(dateTime.year);

            // Serialize the PDFDocument to bytes (a Uint8Array)
            const pdfBytes = await pdfDoc.save();

            // Trigger the browser to download the PDF document
            window.download = download;
            download(pdfBytes, user.name + '-' + user.lastname + ".pdf", "application/pdf");

            //Ocultar el load
            @this.set('none_spinner_pdf', 'd-none');

            Swal.fire(
                'PDF',
                'El PDF ha sido descargado.',
                'success'
            )
        }
    </script>

@endpush
<script>
    document.getElementById('upload').addEventListener('click', function() {

        $('.addFiles').removeClass('d-none');
        if (!Livewire) {
            window.Livewire = new Livewire();
        }
        window.Livewire.emit('upload');
    });
</script>
<style>
    #filesModal .modal-dialog {
        max-width: 800px !important;
    }

</style>
