<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js" async></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" async></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.19/js/intlTelInput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.19/js/utils.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn3.devexpress.com/jslib/22.1.4/js/dx.all.js"></script>
<script src="https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/12.2.0/markdown-it.min.js"></script>
<script src="{{env('APP_URL').'/public/assets/js/audiorecorder.js'}}"></script>
<script>
    function logout() {
        const popup = window.open(
            'https://auth.zapehr.com/logout',
            'logoutPopup',
            'width=50,height=50'
        );
        setTimeout(() => {
            if (popup && !popup.closed) {
                popup.close();
            }
            window.location.href = "{{env('APP_URL')}}/logout";
        }, 1500);
    }
    
    document.getElementById('logoutButton').addEventListener('click', function() {
        logout();
    });
    
    let inactivityTimeout;
    const INACTIVITY_LIMIT = 15 * 60 * 1000;
    
    function resetInactivityTimer() {
        clearTimeout(inactivityTimeout);
        inactivityTimeout = setTimeout(handleInactivity, INACTIVITY_LIMIT);
    }
    
    function handleInactivity() {
        logout();
    }
    
    function setupActivityListeners() {
        document.addEventListener('mousemove', resetInactivityTimer);
        document.addEventListener('keydown', resetInactivityTimer);
        document.addEventListener('click', resetInactivityTimer);
        document.addEventListener('scroll', resetInactivityTimer);
    }
    
    function initInactivityTimer() {
        setupActivityListeners();
        resetInactivityTimer();
    }
    window.onload = initInactivityTimer;

    jQuery(document).ready(function(){
        var features = @json(session('features', []));
        $.ajaxSetup({
            timeout: parseInt("{{env('AJAX_TIMEOUT')}}"),
            beforeSend: function (xhr, settings) {
                xhr.setRequestHeader("Authorization", "Bearer {{ session('accessToken') }}, Medx {{ session('jwt_token') }}");
                if (settings.type === "POST" && settings.data instanceof FormData) {
                    settings.data.append('customer', "{{ session('customer') }}");
                    settings.data.append('practitionerId', "{{ session('PractitionerId') }}");
                }
            },
            error: function (xhr, status, error) {
                console.log(xhr);
                console.log(status);
                console.log(xhr);
                if (xhr.status === 401) {
                    const response = xhr.responseJSON;
                    Swal.fire({
                        position: "top-end",
                        text: response.message || "Authorization failed.",
                        showConfirmButton: false,
                        timer: 2000
                    });
                    setTimeout(() => {
                        logout();
                    }, 1000);
                }
                else if (xhr.status === 403) {
                    const response = xhr.responseJSON;
                    Swal.fire({
                        position: "top-end",
                        text: response.message || "You don't have permission to access the requested resource. Please contact the administrator.",
                        showConfirmButton: false,
                        timer: 2000
                    });
                }
            }
        });
        const md = window.markdownit();
        var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
       /* chatboat */
        $('#chatbot-icon').click(function () {
            if (features.includes('BENEFITEXPLAINER')) {
                $('#chatbot-screen').removeClass('d-none');
                $('#setting-screen').addClass('d-none');
                $('.menu__item').removeClass('menu__item--active');
                $(this).addClass('menu__item--active');
            }else{
                Swal.fire({
                    position: "top-end",
                    text: "You don't have permission to access the requested resource. Please contact the administrator.",
                    showConfirmButton: false,
                    timer: 2000
                });
            }

        });
        // Close chatbot screen
        $('#close-chatbot').click(function () {
            $('#chatbot-screen').addClass('d-none');
            $('.menu__item').removeClass('menu__item--active');
            var slug = window.location.href.split('/').filter(Boolean).pop();
            $('.'+slug).addClass('menu__item--active');
        });
        // Send message
        $('#chat-input').on('keydown', function(e) {
            if (e.key === 'Enter' || e.keyCode === 13) {
                e.preventDefault();
                submitSettings();
            }
        });
        
        $('#send-btn').on('click', function(e) {
            e.preventDefault();
            submitSettings();
        });
        
        function scrollToLastMessage() {
            const chatContainer = $('.messages');
            const messages = chatContainer.find('.message');

            if (messages.length >= 2) {
                const lastMessageHeight = $(messages[messages.length - 1]).outerHeight(true);
                const secondLastMessageHeight = $(messages[messages.length - 2]).outerHeight(true);
                const adjustedScrollHeight = chatContainer[0].scrollHeight - lastMessageHeight - secondLastMessageHeight - 15;
                chatContainer.animate({
                    scrollTop: adjustedScrollHeight
                }, 500);
            } else {
                chatContainer.animate({
                    scrollTop: 0
                }, 500);
            }
        }
        
        function submitSettings() {
            const message = $('#chat-input').val();
            if (message.trim() !== '') {
                $('.messages').append(`<div class="message user-message">${message}</div>`);
                $('#chat-input').val('');
                $('.messages').append(`<div class="message bot-message msg-loading">Loading...</div>`);
            }else{
                $('#chat-input').focus();
                return false;
            }
            scrollToLastMessage();
            const formData = new FormData();
            formData.append('practitionerId', "{{ session('PractitionerId') }}");
            formData.append('message', message);
            const settings = {
                url: "{{env('API_URL')}}chat",
                method: "POST",
                timeout: 0,
                headers: {
                    "Authorization": "Bearer " + "{{ session('accessToken') }}"
                },
                processData: false,
                contentType: false,
                data: formData
            };
            $.ajax(settings).done(response => {
                $('.msg-loading').remove();
                const responseMsg = isHTML(response.data.response) ? response.data.response : md.render(response.data.response);
                $('.messages').append(`<div class="message bot-message">${responseMsg}</div>`);
                scrollToLastMessage();
            }).fail((xhr, status, error) => {
                console.error('Error:', error);
                $('.msg-loading').remove();
                $('.messages').append(`<div class="message bot-message">Oops! There was a problem processing your request. Please wait a moment and try again.</div>`);
                scrollToLastMessage();
            });
        }

        const input = document.querySelector("#mobile");
        var iti = window.intlTelInput(input, {
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.19/js/utils.js",
            initialCountry: "auto",
            geoIpLookup: function(success, failure) {
                jQuery.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
                    var countryCode = (resp && resp.country) ? resp.country : "us";
                    success(countryCode);
                });
            },
            separateDialCode: true
        });

        jQuery(document).on('click', '#add-patient', function(){
            $('.menu__item').removeClass('menu__item--active');
            $(this).addClass('menu__item--active');
            jQuery('#addPatient').modal('show');
        });

        jQuery(document).on('click', '.save', function(e) {
            jQuery('#next').val('save');
            addPatient();
        });
        
        jQuery(document).on('click', '.save-create', function(e) {
            jQuery('#next').val('create-appointment');
            addPatient();
        });

        jQuery('.patient-add-modal-close').on('click', function() {
            $('.menu__item').removeClass('menu__item--active');
            var slug = window.location.href.split('/').filter(Boolean).pop();
            $('.'+slug).addClass('menu__item--active');
            $('#patientForm').trigger('reset');
        });
    
        // Form submit event
        function addPatient() {
            if (iti.isValidNumber()) {
                jQuery('#mobile').removeClass('invalid');
            } else {
                jQuery('#mobile').addClass('invalid');
                return;
            }
            const form = document.getElementById('patientForm');
            const inputs = form.querySelectorAll('input, select');
            let error = false;
            inputs.forEach(function(input) {
                if (!input.checkValidity()) {
                    input.classList.add('invalid');
                    error = true;
                } else {
                    input.classList.remove('invalid');
                }
            });
            if(error) return;

            const formData = new FormData();
            formData.append('practitioner', "{{session('PractitionerId')}}");
            formData.append('practitionerName', "{{session('PractitionerName')}}");
            formData.append('prefix', jQuery('#prefix').val());
            formData.append('suffix', jQuery('#prefix').val());
            formData.append('name', jQuery('#name').val());
            formData.append('surname', jQuery('#surname').val());
            formData.append('mobile', iti.getNumber());
            formData.append('email', jQuery('#email').val());
            formData.append('gender', jQuery('#gender').val());
            formData.append('birthDate', jQuery('#birthDate').val());
            formData.append('addressType', jQuery('#addressType').val());
            formData.append('address', jQuery('#address').val());
            formData.append('deceased', 'No');
        
            const settings = {
                url: "{{env('API_URL')}}{{session('currentEHR')}}/addpatient",
                method: "POST",
                timeout: 0,
                headers: {
                    "Authorization": "Bearer " + "{{ session('accessToken') }}"
                },
                processData: false,
                contentType: false,
                data: formData
            };
    
            jQuery('.patient-footer').html(`
                <div class="loader-container">
                    <div class="loader" id="loader"></div>
                </div>
            `);
        
            $.ajax(settings).done(response => {
                var patientData = response.data[0];
                jQuery('#patient').val(patientData.patientId);
                jQuery('#patientName').val(patientData.patientName);
                jQuery('.patient-footer').html(`
                    <button type="button" class="btn btn-outline-primary save">Save</button>
                    <button type="button" class="btn btn-outline-danger patient-add-modal-close" data-dismiss="modal">Close</button>
                `);
                $('.menu__item').removeClass('menu__item--active');
                var slug = window.location.href.split('/').filter(Boolean).pop();
                $('.'+slug).addClass('menu__item--active');
                jQuery('#addPatient').modal('hide');
                if(jQuery('#next').val() == 'create-appointment'){
                    getPatientsList();
                }
                $('#patientForm').trigger('reset');
                Swal.fire({
                    position: "top-end",
                    text: "Patient added successfully.",
                    showConfirmButton: false,
                    timer: 1000
                });
            }).fail((jqXHR, textStatus, errorThrown) => {
                Swal.fire({
                    position: "top-end",
                    title: "Something went wrong. Please try again later.",
                    showConfirmButton: false,
                    timer: 1000
                });
                jQuery('.patient-footer').html(`
                    <button type="button" class="btn btn-outline-primary save">Save</button>
                    <button type="button" class="btn btn-outline-danger patient-add-modal-close" data-dismiss="modal">Close</button>
                `);
                console.error("Error:", textStatus, errorThrown);
            });
        };
    });
</script>