<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.quote-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 Cotización
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-content">
                        <div class="card-body">
                            @if ($quotes->count())
                                <div class="table-responsive min-height-500">
                                    <table class="table">
                                        <thead class="thead-light">
                                            <tr>
                                                <th style="min-width: 100px;">Cotización</th>
                                                <th style="min-width: 225px;">Fecha de creación</th>
                                                <th style="min-width: 150px;">Cédula / RNC</th>
                                                <th style="min-width: 200px;">Nombre del cliente</th>
                                                @if (Auth::user()->type == 'admin')
                                                    <th style="min-width: 200px;">Nombre del agente</th>
                                                @endif
                                                <th style="min-width: 225px;">Producto</th>
                                                <th style="min-width: 100px;">Más Info</th>
                                                <th style="min-width: 100px;">Atender</th>
                                                <th style="min-width: 100px;">Estatus</th>
                                                <th class="text-center" style="min-width: 100px;">Acciones</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach ($quotes as $key => $value)
                                                <tr>
                                                    <td>{{ $value->code }}</td>
                                                    <td>{{ $value->datetime_formatted }}</td>
                                                    <td>{{ $value->user->document }}</td>
                                                    <td>{{ $value->user->fullname }}</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 class="text-center">
                                                        @if ($value->more_info)
                                                            <i class="fas fa-check color-success"
                                                                style="font-size: 1rem;"></i>
                                                        @endif
                                                    </td>
                                                    <td class="text-center" id="td_{{ $value->id }}">
                                                        @if ($value->more_info)
                                                            @if ($value->attended)
                                                                <i class="fas fa-check color-success"
                                                                    style="font-size: 1rem;"></i>
                                                            @else
                                                                <a href="javascript:" class=""
                                                                    wire:click="$emit('attended', {{ $value->id }})">
                                                                    <i class="far fa-circle"
                                                                        style="font-size: 1rem;"></i>
                                                                </a>
                                                            @endif
                                                        @endif
                                                    </td>
                                                    <td>
                                                        <span
                                                            class="badge bg-{{ config('const.quote-status-badges')[$value->status] }} text-white">{{ $value->status_name }}</span>
                                                    </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 == 'created' || $value->status == 'processing' || ($value->status == 'sent' && $value->more_info))
                                                                    <button wire:click="edit({{ $value->id }})"
                                                                        class="dropdown-item">
                                                                        <i class="fas fa-pencil-alt mr-1"></i> Editar
                                                                    </button>
                                                                @endif
                                                                @if ($value->status == 'sent' && !$value->more_info)
                                                                    <button
                                                                        wire:click="edit_approve({{ $value->id }})"
                                                                        class="dropdown-item text-success">
                                                                        <i class="far fa-thumbs-up"></i> Aprobar
                                                                    </button>
                                                                    <button
                                                                        wire:click="edit_reject({{ $value->id }})"
                                                                        class="dropdown-item text-danger">
                                                                        <i class="far fa-thumbs-down"></i> Rechazar
                                                                    </button>
                                                                @endif
                                                                @if ($value->status == 'approved')
                                                                    <button
                                                                        wire:click="$emit('checkList',{{ $value->id }})"
                                                                        class="dropdown-item text-success">
                                                                        <i class="fas fa-tasks"></i> Tareas
                                                                    </button>
                                                                @endif
                                                                @if ($value->status == 'created')
                                                                    <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="10">
                                                    {{ $quotes->links() }}
                                                </th>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            @else
                                <div class="alert alert-secondary" role="alert">
                                    No se encontraron cotizaciones
                                </div>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @elseif ($mode == "show" || $mode == "approve" || $mode == "reject")
        @include('livewire.quotes.show')
    @else
        @include('livewire.quotes.form')
    @endif

    <!-- Modal -->
    <div class="modal fade" id="modalChecklist" data-backdrop="static" data-keyboard="false" tabindex="-1"
        aria-labelledby="modalChecklistLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalChecklistLabel">Tareas</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="content"></div>
                </div>
                <div class="modal-footer d-flex justify-content-between align-items-center">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                </div>
            </div>
        </div>
    </div>
</div>

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

    {{-- Script para user_main --}}
    <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>

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

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

            // $(document).on('change', '.detail_date_max', function() {
            //     var i = $(this).data('index');
            //     @this.set('detail_date_max.'+i, $(this).val());
            // });
        });
        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
            });

            $('.attended').on('click', function() {
                var id = $(this).data('id');
                Swal.fire({
                    title: '¿Estás seguro?',
                    text: "¡No podrás revertir esto!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ff5b5c',
                    cancelButtonColor: '#a3afbd',
                    confirmButtonText: '¡Sí, atender!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        @this.call('attended', id);
                        $('#td_' + id).html(
                            '<i class="fas fa-check color-success" style="font-size: 1rem;"></i>');
                    }
                });
            });
        }

        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>

    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const Toast2 = Swal.mixin({
                toast: true,
                position: 'top',
                showConfirmButton: false,
                timer: 1000,
                timerProgressBar: true
            });

            @this.on('attended', id => {
                Swal.fire({
                    title: '¿Estás seguro?',
                    text: "¡No podrás revertir esto!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ff5b5c',
                    cancelButtonColor: '#a3afbd',
                    confirmButtonText: '¡Sí, atender!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        @this.call('attended', id);
                        $('#td_' + id).html(
                            '<i class="fas fa-check color-success" style="font-size: 1rem;"></i>'
                            );
                    }
                });
            });

            // Check list
            @this.on('checkList', id => {
                checkList(id)
            });

            function checkList(id) {
                var $modal = $('#modalChecklist');
                $modal.find('.btn-complete').remove();
                let datos = {
                    id: id
                }
                fetch('/cotizaciones/checklist', {
                        method: 'POST',
                        body: JSON.stringify(datos),
                        credentials: "same-origin",
                        headers: {
                            "X-CSRF-TOKEN": document.getElementsByTagName('meta')['csrf-token'].content,
                            'Content-Type': 'application/json',
                            "X-Requested-With": "XMLHttpRequest",
                        }
                    })
                    .then(res => res.json())
                    .catch(error => console.error('Error:', error))
                    .then(response => {
                        var checklist = response.checklist;
                        var quote = response.quote;
                        var items = ``;
                        var check = '';
                        var next = false;
                        var pendiente = false;
                        checklist.forEach((element, index) => {
                            if (element.check) {
                                check = '<i class="fas fa-check-square text-success"></i>';
                                next = true;
                            } else {
                                if (index == 0 || next) {
                                    check = `
                                    <div class="form-check p-0">
                                        <input class="form-check-input m-0" type="checkbox" data-id="${id}" value="${element.id}" style="position:initial">
                                    </div>
                                `;
                                    next = false;
                                    pendiente = true;
                                } else {
                                    if (pendiente) {
                                        var clase = 'pendiente';
                                        pendiente = false;
                                    } else var clase = 'danger';
                                    check = `<i class="far fa-minus-square text-danger ${clase}"></i>`;
                                }
                            }

                            var name = element.name;
                            if (name == "[file]") {
                                if (element.check) {
                                    name = `
                                    <a href="${element.file}" download class="d-inline-flex align-items-center">
                                        <i class="fas fa-download mr-2"></i> Descargar Archivo
                                    </a>
                                `;
                                    if (!quote.completed) {
                                        $modal.find('.modal-footer').append(`
                                        <button data-id="${id}" class="btn btn-success btn-complete d-inline-flex align-items-center justify-content-center">
                                            <i class="fas fa-tasks mr-2"></i> Completar Proceso
                                        </button>
                                    `);
                                    }
                                } else {
                                    var disabled = "disabled";
                                    if (pendiente) disabled = '';
                                    name = `
                                    <form id="frm-task-file">
                                        <div class="custom-file">
                                            <input type="file" class="custom-file-input" name="archivo" id="input-task-file" ${disabled} accept="application/pdf">
                                            <label class="custom-file-label" for="input-task-file">Subir archivo</label>
                                        </div>
                                    </form>
                                `;
                                }
                            }

                            items += `
                            <tr>
                                <td class="text-center align-middle" style="width:75px;">${check}</td>
                                <td class="align-middle">${name}</td>
                            </tr>
                        `;
                        });

                        var html = `
                        <table class="table">
                            <thead>
                                <tr>
                                    <th class="text-center"><i class="fas fa-check"></i></th>
                                    <th>Item</th>
                                </tr>
                            </thead>
                            <tbody>${items}</tbody>
                        </table>
                    `;
                        $modal.find('.content').html(html);
                        $modal.find('.btn-submit').attr('data-id', id);
                        $modal.modal('show');
                        bsCustomFileInput.init();

                        $modal.find('.form-check-input').on('click', function() {
                            checkTask($(this));
                        });

                        $modal.find('.btn-complete').on('click', function() {
                            checkTaskComplete($(this));
                        });
                    });
            }

            function checkTask($this) {
                var id = $this.val();
                var quote_id = $this.data('id');
                $this.parents('td').html('<i class="fas fa-circle-notch fa-spin"></i>');

                var formData = new FormData(document.getElementById('frm-task-file'));
                formData.append('id', id);
                formData.append('quote_id', quote_id);
                fetch('/cotizaciones/checktask', {
                        method: 'POST',
                        body: formData,
                        credentials: "same-origin",
                        headers: {
                            "X-CSRF-TOKEN": document.getElementsByTagName('meta')['csrf-token'].content,
                            "X-Requested-With": "XMLHttpRequest",
                        }
                    })
                    .then(res => res.json())
                    .catch(error => console.error('Error:', error))
                    .then(response => {
                        $('#modalChecklist').find('.alert').remove();
                        if (response.errors) {
                            $('#modalChecklist').find('.modal-body').append(`
                            <div class="alert alert-danger" role="alert">
                                ${response.errors[0]}
                            </div>
                        `);
                        }
                        checkList(quote_id);
                    });
            }

            function checkTaskComplete($this) {
                var quote_id = $this.data('id');
                $this.html('<i class="fas fa-circle-notch fa-spin"></i> Procesado...').prop('disabled', true);

                var formData = new FormData();
                formData.append('quote_id', quote_id);
                fetch('/cotizaciones/checktask/complete', {
                        method: 'POST',
                        body: formData,
                        credentials: "same-origin",
                        headers: {
                            "X-CSRF-TOKEN": document.getElementsByTagName('meta')['csrf-token'].content,
                            "X-Requested-With": "XMLHttpRequest",
                        }
                    })
                    .then(res => res.json())
                    .catch(error => console.error('Error:', error))
                    .then(response => {
                        $('#modalChecklist').find('.alert').remove();
                        if (response.errors) {
                            $this.html('<i class="fas fa-tasks mr-2"></i> Completar Proceso');
                            $('#modalChecklist').find('.modal-body').append(`
                            <div class="alert alert-danger" role="alert">
                                ${response.errors[0]}
                            </div>
                        `);
                        } else {
                            $('#modalChecklist').modal('hide');

                            Toast2.fire({
                                icon: 'success',
                                title: 'Proceso completado'
                            });
                        }
                    });
            }

            Livewire.hook('component.initialized', (component) => {})
            Livewire.hook('element.initialized', (el, component) => {})
            Livewire.hook('element.updating', (fromEl, toEl, component) => {})
            Livewire.hook('element.updated', (el, component) => {})
            Livewire.hook('element.removed', (el, component) => {})
            Livewire.hook('message.sent', (message, component) => {})
            Livewire.hook('message.failed', (message, component) => {})
            Livewire.hook('message.received', (message, component) => {})
            Livewire.hook('message.processed', (message, component) => {})
        });
    </script>

@endsection
