<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
    @yield('metas')

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
        integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
        crossorigin="anonymous" />
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">

    <link href="https://unpkg.com/filepond@^4/dist/filepond.css" rel="stylesheet" />

    @stack('styles')

    @livewireStyles
</head>

<body>
    <div id="app">
        @yield('content')

        <!-- Modal -->
        <div class="modal fade" id="modalCalendarNotifications" data-backdrop="static" data-keyboard="false"
            tabindex="-1" aria-labelledby="modalCalendarNotificationsLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalCalendarNotificationsLabel">Notificaciones</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>
                </div>
            </div>
        </div>
    </div>

    <script src="{{ asset('js/feather-icons/feather.min.js') }}"></script>
    <script src="{{ asset('js/app.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>
    {{-- <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> --}}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"
        integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"
        integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE+sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX+lmPqPdxB47A0Nz0cMQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/timepicker/1.3.5/jquery.timepicker.min.js"></script>

    {{-- Activar editor si uno vence usar el otro --}}
    <script src="https://cdn.tiny.cloud/1/iobug34s3d8febr49q6z1fe5auluq13t8wdajrqhpfwwaywh/tinymce/5/tinymce.min.js"
        referrerpolicy="origin"></script>

        <!-- Place the first <script> tag in your HTML's <head> -->
    {{-- <script src="https://cdn.tiny.cloud/1/5hsephm4yw544joqhwv4uy08tbmrjmne5aklg75frjq5ac75/tinymce/7/tinymce.min.js" referrerpolicy="origin"></script> --}}

    <!-- Place the first <script> tag in your HTML's <head> -->
    {{-- <script src="https://cdn.tiny.cloud/1/m4r4w39h8iq1sji650tudkfqrlqng6my8fbdvenzxtmkc8jc/tinymce/7/tinymce.min.js" referrerpolicy="origin"></script> --}}

    <script src="{{ asset('vendor/libs/jquery.mask.min.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/npm/bs-custom-file-input/dist/bs-custom-file-input.min.js"></script>
    <script src="{{ asset('js/push.js') }}"></script>
    <script>
        var date_locale = {
            "format": "DD/MM/YYYY",
            "separator": " - ",
            "applyLabel": "Listo",
            "cancelLabel": "Limpiar",
            "fromLabel": "Desde",
            "toLabel": "Hasta",
            "customRangeLabel": "Custom",
            "weekLabel": "S",
            "daysOfWeek": [
                "Do",
                "Lu",
                "Ma",
                "Mi",
                "Ju",
                "Vi",
                "Sa"
            ],
            "monthNames": [
                "Enero",
                "Febrero",
                "Marzo",
                "Abril",
                "Mayo",
                "Junio",
                "Julio",
                "Agosto",
                "Septiembre",
                "Octubre",
                "Noviembre",
                "Diciembre"
            ],
            "firstDay": 1
        }
    </script>

    <script>
        (function($) {
            "use strict";

            var $modal = $('#modalCalendarNotifications');

            const Toast2 = Swal.mixin({
                toast: true,
                position: 'top',
                showConfirmButton: false,
                timer: 1000,
                timerProgressBar: true
            });

            setInterval(function() {
                // if (!$modal.hasClass('show')) {
                if (!$('.modal').hasClass('show')) {
                    fetch('/calendars/notifications', {
                            method: 'POST',
                            body: {},
                            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 => {

                            moment.locale('es');

                            var html = ``;

                            if (response[0]) {
                                response.forEach((element, index) => {
                                    html += `
                                <div class="wrapper-event">
                                    <div class="row">
                                        <div class="col">
                                            <label class="m-0">Evento</label>
                                            <p class="font-weight-bold">${element.title}</p>
                                        </div>
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <label class="m-0">Desde</label>
                                            <p class="font-weight-bold m-0">${moment(element.start).format('MMMM Do YYYY, h:mm a')}</p>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="m-0">Hasta</label>
                                            <p class="font-weight-bold m-0">${moment(element.end).format('MMMM Do YYYY, h:mm a')}</p>
                                        </div>
                                    </div>

                                    <div class="row my-4">
                                        <div class="col-md-10">
                                            <form class="form-inline">
                                                <div class="form-group mr-3">
                                                    <label>Posponer: </label>
                                                </div>
                                                <div class="form-group mr-3">
                                                    <input type="number" min="1" value="1" class="form-control" name="cantidad" placeholder="Cantidad" value="">
                                                </div>
                                                <div class="form-group mr-3">
                                                    <select class="form-control" name="tiempo">
                                                        <option value="minutos">Minutos</option>
                                                        <option value="horas">Horas</option>
                                                        <option value="dias">Dias</option>
                                                    </select>
                                                </div>
                                                <button type="button" data-id="${element.id}" class="btn btn-outline-light btn-posponer"><i class="far fa-clock"></i> Aplicar</button>
                                            </form>
                                        </div>
                                        <div class="col-md-2 text-right">
                                            <button type="button" data-id="${element.id}" class="btn btn-outline-success btn-complete" data-toggle="tooltip" data-placement="top" title="Completar evento">
                                                <i class="fas fa-check-double"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <hr>
                                </div>
                                `;

                                    //EVENTO BROWSER
                                    Push.Permission.DEFAULT;
                                    Push.create(element.title, {
                                        //body: "Tiene una notificación pendiente",
                                        timeout: 15000,
                                        onClick: function() {
                                            window.focus();
                                            this.close();
                                        }
                                    });

                                    //NOTIFICATION BROWSER SOUND
                                    var soundInterval;
                                    var contador = 0;
                                    soundInterval = setInterval(function() {
                                        let src =
                                            '{{ asset('sound/notification.mp3') }}';
                                        let audio = new Audio(src);
                                        audio.play();

                                        contador++;
                                        if (contador == 4) {
                                            clearInterval(soundInterval);
                                        }
                                    }, 2000);

                                });

                                $modal.find('.modal-body').html(html);
                                $modal.modal('show');
                                $('[data-toggle="tooltip"]').tooltip();

                            }
                        });
                }
            }, 15000);

            $("body").on("click", "#modalCalendarNotifications .btn-complete", function(event) {
                event.preventDefault();

                var $btn = $(this)
                $btn.html('<i class="fas fa-circle-notch fa-spin"></i>');
                var datos = {
                    id: $(this).data('id')
                };
                fetch('/calendars/notifications/complete', {
                        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 => {
                        $btn.parent().parent().parent().remove();
                        Toast2.fire({
                            icon: 'success',
                            title: 'Evento terminado'
                        });
                        if ($modal.find('.wrapper-event').length <= 0) {
                            $modal.modal('hide');
                        }
                    });
            });

            $("body").on("click", "#modalCalendarNotifications .btn-posponer", function(event) {
                event.preventDefault();

                var $btn = $(this)
                $btn.html('<i class="fas fa-circle-notch fa-spin"></i>');
                var datos = {
                    id: $(this).data('id'),
                    cantidad: $modal.find('[name="cantidad"]').val(),
                    tiempo: $modal.find('[name="tiempo"]').val(),
                };
                fetch('/calendars/notifications/posponer', {
                        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 calendarEl = document.getElementById('calendar');
                        if (calendarEl) {
                            //Reseteamos el calendar con el new value
                            getCalendar();
                        }


                        $btn.parent().parent().parent().parent().remove();
                        Toast2.fire({
                            icon: 'success',
                            title: 'Evento pospuesto'
                        });
                        if ($modal.find('.wrapper-event').length <= 0) {
                            $modal.modal('hide');
                        }
                    });
            });

            // cotizador de vehiculo
            window.addEventListener('submitted', event => {
            Swal.fire({
                title: 'Exito!',
                text: event.detail.message,
                icon: 'success',
                showCancelButton: false,
                confirmButtonText: 'Aceptar'
            }).then((result) => {
                location.href = event.detail.route;
            });
            });

            window.addEventListener('alert', event => {
                Swal.fire(
                    event.detail.title,
                    event.detail.message,
                    event.detail.icon
                );
            });

            window.addEventListener('toast', event => {
                $.notify(event.detail.message, { type: event.detail.type });
            });

        })(jQuery);

        //Calendar
        function getCalendar() {

            var Calendar = FullCalendar.Calendar;
            var calendarEl = document.getElementById('calendar');
            var calendar = new Calendar(calendarEl, {
                headerToolbar: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'dayGridMonth,timeGridWeek,timeGridDay'
                },

                editable: true,
                selectable: true,
                locale: 'es',
                events: './calendars',
                navLinks: true,

                eventClick: function(info) {
                    var $calendarModal = $('#calendarModal');
                    $('#calendarModalAlert').addClass('d-none');
                    $('#calendarModalLabel').html('Actualizar Evento');
                    $('#calendarModalSubmit').html('Actualizar Evento').prop('disabled', false);
                    $('#calendarModalDelete').html('Eliminar').removeClass('d-none').prop(
                        'disabled',
                        false);

                    var fecha = moment(info.event.start).format('DD/MM/YYYY');
                    var desde = moment(info.event.start).format('hh:mm A');
                    var hasta = moment(info.event.end).format('hh:mm A');

                    $calendarModal.find('[name="type"]').val('update');
                    $calendarModal.find('[name="start"]').val(info.event.start);
                    $calendarModal.find('[name="end"]').val(info.event.end);
                    $calendarModal.find('[name="title"]').val(info.event.title);
                    $calendarModal.find('[name="id"]').val(info.event.id);
                    $calendarModal.find('[name="fecha"]').val(fecha);
                    $calendarModal.find('[name="desde"]').val(desde);
                    $calendarModal.find('[name="hasta"]').val(hasta);
                    $calendarModal.modal('show');
                },

                select: function(day) {
                    var $calendarModal = $('#calendarModal');
                    let diff = 4 * 60 * 60 * 1000;
                    let start = day.start - diff;
                    let end = day.end - diff;
                    start = new Date(start).toISOString().slice(0, 19).replace('T', ' ');
                    end = new Date(end).toISOString().slice(0, 19).replace('T', ' ');

                    var fecha = moment(start).format('DD/MM/YYYY');
                    var desde = moment(start).format('hh:mm A');
                    var hasta = moment(end).format('hh:mm A');
                    if (desde == '12:00 AM' && hasta == '12:00 AM') {
                        var ahora = moment().endOf('hour').add(1, "minute");
                        desde = ahora.format('hh:mm A');
                        hasta = ahora.add(1, "hour").format('hh:mm A');
                    }

                    $('#calendarModalAlert').addClass('d-none');
                    $('#calendarModalLabel').html('Agregar Evento');
                    $('#calendarModalSubmit').html('Agregar Evento').prop('disabled', false);
                    $('#calendarModalDelete').html('Eliminar').addClass('d-none').prop('disabled',
                        true);
                    $calendarModal.find('[name="type"]').val('add');
                    $calendarModal.find('[name="start"]').val(start);
                    $calendarModal.find('[name="end"]').val(end);
                    $calendarModal.find('[name="title"]').val('');
                    $calendarModal.find('[name="id"]').val('');
                    $calendarModal.find('[name="fecha"]').val(fecha);
                    $calendarModal.find('[name="desde"]').val(desde);
                    $calendarModal.find('[name="hasta"]').val(hasta);
                    $calendarModal.modal('show');
                },

                eventChange: function(info) {
                    var start = moment(info.event.start).format('YYYY-MM-DD HH:mm:ss');
                    var end = moment(info.event.end).format('YYYY-MM-DD HH:mm:ss');

                    let datos = {
                        start: start,
                        end: end,
                        id: info.event.id,
                        type: 'change'
                    }
                    fetch('/calendars/actions', {
                            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 => {
                            calendar.refetchEvents();
                            Toast2.fire({
                                icon: 'success',
                                title: 'Calendario actualizado'
                            });
                        });
                }
            });
            calendar.render();

            return calendar;
        }
    </script>

    <script src="{{ asset('js/main.js') }}"></script>

    @livewireScripts
    <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.7.x/dist/alpine.min.js" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.7/jquery.inputmask.min.js"></script>
    @yield('js')
    @stack('scripts')
    @stack('scripts_policyholders')


</body>

</html>
