<div id="calendar"></div>

@push('scripts')
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.6.0/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.6.0/locales-all.min.js"></script>

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

            const initLib = function() {
                $('.timepicker').timepicker({
                    timeFormat: 'hh:mm p',
                    interval: 60,
                    minTime: '7',
                    maxTime: '11:30pm',
                    defaultTime: '7',
                    startTime: '7:00',
                    dynamic: false,
                    dropdown: true,
                    scrollbar: true
                });

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

                $('.timepicker').mask('00:00 AM', {
                    'translation': {
                        A: {
                            pattern: /[Aa]/
                        },
                        M: {
                            pattern: /[MmPp]/
                        },
                    }
                });

                $('.timepicker').mask('00:00 PM', {
                    'translation': {
                        P: {
                            pattern: /[Pp]/
                        },
                        M: {
                            pattern: /[Mm]/
                        },
                    }
                });

                $('.datepicker').mask('00/00/0000', {
                    'translation': {
                        0: {
                            pattern: /[0-9*]/
                        }
                    }
                });
            };

            //Get calendar init
            var calendar = getCalendar();

            $('#calendarModalSubmit').on('click', function() {
                $('#calendarModalDelete').prop('disabled', true);
                $(this).html('<i class="fas fa-circle-notch fa-spin"></i> Procesando...').prop('disabled',
                    true);
                var $calendarModal = $('#calendarModal');
                var fecha = $calendarModal.find('[name="fecha"]').val();
                var desde = $calendarModal.find('[name="desde"]').val();
                desde = desde.toUpperCase();
                var hasta = $calendarModal.find('[name="hasta"]').val();
                hasta = hasta.toUpperCase();
                var start = fecha + ' ' + desde;
                var end = fecha + ' ' + hasta;
                start = moment(start, 'DD/MM/YYYY hh:mm A').format('YYYY-MM-DD HH:mm:ss');
                end = moment(end, 'DD/MM/YYYY hh:mm A').format('YYYY-MM-DD HH:mm:ss');
                $calendarModal.find('[name="start"]').val(start);
                $calendarModal.find('[name="end"]').val(end);

                let datos = {
                    type: $calendarModal.find('[name="type"]').val(),
                    start: $calendarModal.find('[name="start"]').val(),
                    end: $calendarModal.find('[name="end"]').val(),
                    title: $calendarModal.find('[name="title"]').val(),
                    id: $calendarModal.find('[name="id"]').val(),
                    fecha: $calendarModal.find('[name="fecha"]').val(),
                    desde: $calendarModal.find('[name="desde"]').val(),
                    hasta: $calendarModal.find('[name="hasta"]').val()
                }
                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 => {
                        if (response.error) {
                            $('#calendarModalAlert').html('');
                            var errors = response.error;
                            errors.forEach(element => {
                                $('#calendarModalAlert').append(`<p>${element}</p>`);
                            });
                            $('#calendarModalAlert').removeClass('d-none');
                            $(this).html('Guardar EVento').prop('disabled', false);
                        } else {
                            
                            calendar.refetchEvents();
                            $calendarModal.modal('hide');
                            if ($calendarModal.find('[name="type"]').val() == 'add') var msj =
                                'Evento agregado!';
                            else var msj = 'Evento actualizado!';
                            Swal.fire(
                                'Evento',
                                msj,
                                'success'
                            );
                        }
                    });
            });

            $('#calendarModalDelete').on('click', function() {
                Swal.fire({
                    title: '¿Estás seguro?',
                    text: "¡No podrás revertir esto!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#ff5b5c',
                    cancelButtonColor: '#a3afbd',
                    confirmButtonText: '¡Sí, eliminar!',
                    cancelButtonText: 'Cancelar'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('#calendarModalSubmit').prop('disabled', true);
                        $('#calendarModalDelete').html(
                            '<i class="fas fa-circle-notch fa-spin"></i> Procesando...').prop(
                            'disabled', true);
                        var $calendarModal = $('#calendarModal');
                        let datos = {
                            type: 'delete',
                            start: $calendarModal.find('[name="start"]').val(),
                            end: $calendarModal.find('[name="end"]').val(),
                            title: $calendarModal.find('[name="title"]').val(),
                            id: $calendarModal.find('[name="id"]').val()
                        }
                        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();
                                $calendarModal.modal('hide');
                                var msj = 'Evento eliminado!';
                                Swal.fire(
                                    'Evento',
                                    msj,
                                    'success'
                                );
                            });
                    }
                });
            });

            initLib();
        });
    </script>

    <link href='https://cdn.jsdelivr.net/npm/fullcalendar@5.3.1/main.min.css' rel='stylesheet' />
    <style>
        /* html, body {
                        margin: 0;
                        padding: 0;
                        font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
                        font-size: 14px;
                    } */

        #external-events {
            position: fixed;
            z-index: 2;
            top: 20px;
            left: 20px;
            width: 150px;
            padding: 0 10px;
            border: 1px solid #ccc;
            background: #eee;
        }

        .demo-topbar+#external-events {
            /* will get stripped out */
            top: 60px;
        }

        #external-events .fc-event {
            cursor: move;
            margin: 3px 0;
        }

        #calendar-container {
            position: relative;
            z-index: 1;
            margin-left: 200px;
        }

        #calendar {
            max-width: 1100px;
            margin: 20px auto;
        }

    </style>
@endpush
