<!DOCTYPE html>
<html>
<head>
    <title>Med-X | Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-icons/3.0.2/iconfont/material-icons.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="{{asset('assets/css/style.css')}}">
    <style>
        .conversation:last-child {
            margin-bottom: 50px;
        }
        .transcription-data audio {
            width: 96%;
            bottom: 1%;
        }
        audio {
            width: 95%;
            height: 40px;
            position: absolute;
            bottom: 14%;
        }
        audio::-webkit-media-controls-panel {
            background-color: #34b6b340;
        }
        .report-details h5 {
            margin-bottom: 2px;
        }
        #reports-list .report-details {
            padding-top: 10px;
            padding-bottom: 10px;
        }
        .reportlist-data {
            padding: 0 10px
        }
        .reportlist-data ul {
            list-style-type: none;
            padding-inline-start: 0;
        }
        #report-file {
            border-bottom: 1px solid #0000004f;
            padding: 5px 0;
            cursor: pointer;
        }
        .reportFile-data {
            padding: 0px !important;
            text-align: center;
        }
        .report-summary-data {
            text-align: justify;
            padding: 5px 10px;
        }
        .upload-container {
            width: 70%;
            min-width: 70%;
            margin: auto;
            height: 25vh;
        }
        .upload-area {
            border: 2px dashed #34B6B3;
            border-radius: 5px;
            padding: 50px;
            text-align: center;
            background-color: transparent;
            position: relative;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .upload-area i {
            font-size: 50px;
            color: #34B6B3;
        }
        .upload-area p {
            font-size: 18px;
            color: #555;
            margin: 0;
            padding: 0;
        }
        .upload-area input {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }
        #reportFile {
            z-index: 99999;
        }
        .uploadList {
            padding: 0px 5px 5px !important;
        }
        .reportUploadList-data {
            height: calc(90vh - 29vh);
            overflow-y: scroll;
        }
    </style>
</head>
<body>
    <div class="loading d-none">
      <div class='uil-ring-css' style='transform:scale(0.5);'>
        <div></div>
      </div>
    </div>
    <header>
        <nav class="menu">
            <a href="/" class="menu__item menu__item--active">
                <i class="material-icons">home</i>
            </a>
            <a href="javascript:void(0)" class="menu__item">
                <i class="material-icons">help_outline</i>
            </a>
            <a href="javascript:void(0)" class="menu__item">
                <i class="material-icons">settings</i>
            </a>
            <a href="javascript:void(0)" id="logoutButton" class="menu__item">
                <i class="material-icons">exit_to_app</i>
            </a>
        </nav>
    </header>
    <main class="container-fluid">
        <div class="row">
            <div class="col-sm-3">
                <div class="d-flex align-items-center">
                    <div class="col-sm-10 pl-0">
                        <img src="https://api.prod.med-x.ai/public/images/MedX-Logo.png" width="75%" alt="Med-X Logo">
                    </div>
                    <div class="col-sm-2 icons">
                        <i class="fas fa-calendar-plus primary-color" aria-label="Add Appointment"></i>
                    </div>
                </div>
                <div class="input-group mt-3">
                    <input type="text" class="form-control" placeholder="Search Patient" aria-label="Search Patient">
                    <div class="input-group-append">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <h3 class="font-weight-light mt-3 mb-0">Scheduled Visits</h3>
                <div class="user-list user-list-left"></div>
            </div>
            <div class="col-sm-6">
                <div class="center-box">
                    <div class="mt-5 pt-4">
                        <h2 class="primary-color">Hello, {{session('PractitionerName')}}</h2>
                        <h5 class="secondary-color">Select a scheduled visit to get started!</h5>
                        <div class="d-flex align-items-center mt-5">
                            <i class="material-icons-outlined glowing-icon" style="font-size:44px" aria-label="Info">wb_incandescent</i>
                            <p class="pl-2 mb-0">Historical medical records will be listed on the right-side in chronological order clearly showing the visits that have reports attached.</p>
                        </div>
                    </div>
                </div>
                <div class="center-box-selected d-none">
                    <div class="user-list mt-0">
                        <div class="user-item border-0 pb-0 pt-1 pl-0">
                            <h4 class="secondary-color patientName mb-0"></h4>
                            <small class="patientId"></small>
                        </div>
                    </div>
                    <h6 class="secondary-color appointmentId pt-4"></h6>
                    <div class="audio-text-box" id="audio-text-box">
                        <audio id="audio" style="display:none" src="" controls controlsList="nodownload noplaybackrate"></audio>
                    </div>
                    <div class="bottom-bar text-center">
                        <div class="button-panel">
                            <i class="fas fa-microphone primary-color start-recording" aria-label="Audio Recording"></i>
                            <i class="fas fa-microphone primary-color play-recording d-none" aria-label="Audio Start"></i>
                            <i class="fas fa-pause primary-color pause-recording d-none" aria-label="Audio Pause"></i>
                            <i class="fas fa-stop text-danger stop-recording d-none" aria-label="Audio Stop"></i>
                            <i class="fas fa-cloud-upload-alt report-upload primary-color" aria-label="Reports Upload"></i>
                            <i class="fas fa-eraser primary-color erase" aria-label="Erase Audio Data"></i>
                            <i class="fas fa-check primary-color generate-transcription" aria-label="Submit for SOAP Summary"></i>
                        </div>
                        <p class="mb-2">MedX engine may display inaccurate information, please check the data before submitting it for further processing.</p>
                    </div>
                    
                </div>
            </div>
            <div class="col-sm-3">
                <div class="user-list mt-0">
                    <div class="user-item border-0 pb-0 pt-1">
                        <h4 class="secondary-color mb-0">{{session('PractitionerName')}}</h4>
                        <small>{{session('suffix')}}</small>
                    </div>
                </div>
                <div class="input-group mt-3">
                    <input type="text" class="form-control" placeholder="Search Patient History" aria-label="Search Patient History">
                    <div class="input-group-append">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <div class="appointment-close">
                    <h3 class="font-weight-light mt-3 mb-0">Patient’s History</h3>
                    <p class="text-center mt-3">Historical records will be displayed in this section</p>
                </div>
                <div class="appointment-show mt-3 pr-1 d-none">
                    <div class="list-group panel">
                        <a href="#reports-list" id="reports" class="list-group-item-report" data-toggle="collapse">
                            <span class="d-flex justify-content-between align-items-center">
                                <h3 class="font-weight-light mb-0">Patient's Reports</h3>
                                <i class="fas fa-angle-down"></i>
                            </span>
                        </a>
                        <div class="d-grid pt-2 pl-2 pr-3 collapse" id="reports-list"></div>
                        <hr/>
                        <a href="#history-list" id="history" class="list-group-item-history" data-toggle="collapse">
                            <span class="d-flex justify-content-between align-items-center">
                                <h3 class="font-weight-light mb-0">Patient's History</h3>
                                <i class="fas fa-angle-up"></i>
                            </span>
                        </a>
                        <div class="d-grid pt-2 pl-2 pr-3 collapse show" id="history-list"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal" id="appointmentDetailModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-body appointment-details-modal">
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-primary transacription">Transcription</button>
                        <button type="button" class="btn btn-outline-primary primary-bg-color soap-summary">SOAP Summary</button>
                        <button type="button" class="btn btn-outline-primary generate-prescription d-none">Generate Prescription</button>
                        <button type="button" class="btn btn-outline-primary prescription">Prescription</button>
                        <button type="button" class="btn btn-outline-danger modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- Report Modal -->
        <div class="modal" id="reportModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-body report-modal">
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-primary reports">Reports</button>
                        <button type="button" class="btn btn-outline-primary primary-bg-color report-summary">Report Summary</button>
                        <button type="button" class="btn btn-outline-danger modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- ReportFile Modal -->
        <div class="modal" id="reportFile" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-body reportFile-data">
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-danger report-modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- ReportFile Upload And List Modal -->
        <div class="modal" id="reportUpload" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-body">
                        <div class="upload-container">
                            <div class="upload-area" id="uploadArea">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p>File supported .png, .jpeg & .pdf (maximum 32MB allowed)</p>
                                <input type="file" id="fileInput" name="files" >
                            </div>
                        </div>
                        <div class="reportUploadList-data"></div>
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-danger report-upload-modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <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://cdnjs.cloudflare.com/ajax/libs/markdown-it/12.2.0/markdown-it.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script src="{{asset('assets/js/audiorecorder.js')}}"></script>
    
    <script>
        $(document).ready(function() {
            const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            const md = window.markdownit();
            var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
            function getAppointments(){
                const formData = new FormData();
                formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "https://api.dev.med-x.ai/api/v1/ehr-default/appointments",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('.user-list-left').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const userList = $('.user-list-left');
                    userList.empty();
                    const currentTime = new Date();
                    response.data.forEach(item => {
                        const itemTimeSlot = new Date(item.timeSlot);
                        const isSameDate = currentTime.toDateString() === itemTimeSlot.toDateString();
                        const appointmentTime = isSameDate 
                            ? itemTimeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) 
                            : itemTimeSlot.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
                        // const appointmentTime = new Date(item.timeSlot).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                        const appointmentId = item.appointmentId;
                        const patientId = item.patientURL;
                        const appointmentType = item.appointmentType;
                        const patientName = `${item.patientPrefix} ${item.patient}`;
                        
                        const userItem = `
                            <div class="user-item-left" data-appointmentId="${appointmentId}" data-patientId="${patientId}" data-patientName="${patientName}">
                                <h5>${patientName}</h5>
                                <small>${appointmentTime} | ${appointmentType}</small>
                            </div>
                        `;
                        
                        userList.append(userItem);
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            getAppointments();
            
            // Audio Recording
            let recorder;
            let audioData = [];
            let isPaused = false;
            let timerIntervalId;
            AudioRecorder.preload("{{asset('assets/js/mp3worker.js')}}");
            
            function setupRecorder() {
                audioData = [];
                recorder = new AudioRecorder({
                    recordingGain : 1,
                    encoderBitRate : 128,
                    streaming : true,
                    streamBufferSize : 50000,   
                    constraints : {
                        channelCount : 1,
                        autoGainControl : 1,
                        echoCancellation : 1,
                        noiseSuppression : 1
                    },
                });
        
                recorder.ondataavailable = (data) => {
                    console.log("data", data.length);
                    audioData.push(data);
                };
        
                recorder.onstart = () => {
                    timerIntervalId = setInterval(() => {
                        console.log((recorder.time / 1000.0).toFixed(2) + "s");
                    }, 100);
                };
        
                recorder.onstop = () => {
                    Swal.fire({
                        title: 'Confirm',
                        text: "Would you like to keep this recording, or discard it?",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#34B6B3',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Keep',
                        cancelButtonText: 'Discard'
                    }).then(async (result) => {
                        if (result.isConfirmed) {
                            jQuery('.loading').removeClass('d-none');
                            // Combine all the mp3 data chunks from the audioData array into a Blob
                            let mp3Blob = new Blob(audioData, {type : "audio/mpeg"});
                            let mp3BlobUrl = URL.createObjectURL(mp3Blob);
                            audioToText(mp3Blob, mp3BlobUrl);
                        }
                    });
                };
        
                recorder.onerror = (error) => {
                    console.log(error);
                    $('.start-recording').removeClass('d-none');
                    $('.play-recording').addClass('d-none');
                    $('.pause-recording').addClass('d-none');
                    $('.stop-recording').addClass('d-none');
                };
            }
            
            function audioToText(mp3Blob, audioUrl) {
                const form = new FormData();
                form.append("patientId", $('.user-item-left-selected').attr('data-patientId'));
                form.append("practitionerId", "{{ session('PractitionerId') }}");
                form.append("appointmentId", $('.user-item-left-selected').attr('data-appointmentId'));
                form.append("audio_file", mp3Blob, $('.user-item-left-selected').attr('data-appointmentId')+"T"+new Date().getTime()+'.mp3');

                const settings = {
                    "url": "https://api.dev.med-x.ai/api/v1/ehr-default/audio-text",
                    "method": "POST",
                    "timeout": 0,
                    "headers": {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    "processData": false,
                    "mimeType": "multipart/form-data",
                    "contentType": false,
                    "dataType": "json",
                    "data": form
                };

                $.ajax(settings).done(response => {
                    $('.audio-text-box').append(`
                        <div class="conversation d-flex">
                            <p class="text mb-0">${response.data.audiotext}</p>
                            <span class="player" data-url="${audioUrl}" data-classname="${new Date().getTime()}">
                                <i class="fas fa-play primary-color resume-${new Date().getTime()}"></i>
                                <i class="fas fa-pause d-none primary-color pause-${new Date().getTime()}"></i>
                                <span class="duration time-${new Date().getTime()} d-none">00:00</span>
                            </span>
                        </div>
                    `);
                    jQuery('.loading').addClass('d-none');
                }).fail((jqXHR, textStatus, errorThrown) => {
                    console.log('Error while converting audio to text.');
                    console.error("Error:", textStatus, errorThrown);
                    jQuery('.loading').addClass('d-none');
                });
            }
            
            $('.start-recording').on('click', async function() {
                setupRecorder();
                $('.start-recording').addClass('d-none');
                $('.pause-recording').removeClass('d-none');
                $('.stop-recording').removeClass('d-none');
                recorder.start();
            });
        
            $('.pause-recording').click(function() {
                if (recorder && !isPaused) {
                    recorder.pause();
                    isPaused = true;
                    $('.play-recording').removeClass('d-none');
                    $('.pause-recording').addClass('d-none');
                }
            });
        
            $('.play-recording').click(function() {
                if (recorder && isPaused) {
                    recorder.resume();
                    isPaused = false;
                    $('.play-recording').addClass('d-none');
                    $('.pause-recording').removeClass('d-none');
                }
            });
        
            $('.stop-recording').click(function() {
                clearInterval(timerIntervalId);
                $('.start-recording').removeClass('d-none');
                $('.play-recording').addClass('d-none');
                $('.pause-recording').addClass('d-none');
                $('.stop-recording').addClass('d-none');
                recorder.stop();
            });
            
            let audio;
            function formatTime(seconds) {
                const minutes = Math.floor(seconds / 60);
                const secs = Math.floor(seconds % 60);
                return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            }
            
            function updateCurrentTime(className) {
                const currentTime = audio.currentTime;
                $('.time-'+className).text(formatTime(currentTime));
            }

            $(document).on('click', '.fa-play', function(){
                $('.fa-play').removeClass('d-none');
                $('.fa-pause').addClass('d-none');
                $('.duration').addClass('d-none');
                $('.duration').text('00:00');
                var parentSpan = $(this).closest('.player');
                var audioUrl = parentSpan.attr('data-url');
                var className = parentSpan.attr('data-classname');
                
                if($('#audio').attr('src') == '' || $('#audio').attr('src') != audioUrl){
                    $('#audio').attr('src', audioUrl);
                }
                audio = $('#audio')[0];
                // Update current time during playback
                audio.ontimeupdate = function() {
                    if (!isNaN(audio.duration)) {
                        updateCurrentTime(className);
                    } else {
                        console.warn('Duration still not available.');
                    }
                };
                
                audio.onended = function() {
                    $('.resume-' + className).removeClass('d-none');
                    $('.pause-' + className).addClass('d-none');
                    $('.time-' + className).addClass('d-none');
                    $('.time-' + className).text('00:00');
                };
                
                audio.onpause = function() {
                    $('.resume-' + className).removeClass('d-none');
                    $('.pause-' + className).addClass('d-none');
                };
                
                audio.onplay = function() {
                    $('.resume-' + className).addClass('d-none');
                    $('.pause-' + className).removeClass('d-none');
                };
                
                $('#audio').show();
                $('.resume-'+className).addClass('d-none');
                $('.pause-'+className).removeClass('d-none');
                $('.time-'+className).removeClass('d-none');
                audio.play();
            });

            $(document).on('click', '.conversation .fa-pause', function(){
                var parentSpan = $(this).closest('.player');
                var className = parentSpan.attr('data-classname');
                $('.resume-'+className).removeClass('d-none');
                $('.pause-'+className).addClass('d-none');
                // $('.time-'+className).addClass('d-none');
                audio.pause();
            });
            
            function getAllReports(patientId){
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', patientId);
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "https://api.dev.med-x.ai/api/v1/ehr-default/patient/reports",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('#reports-list').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const reportList = $('#reports-list');
                    reportList.empty();
                    if(response.data.length > 0){
                        response.data.forEach(reports => {
                            reports.report.forEach(item => {
                                const reportTime = new Date(reports.date).toLocaleTimeString('en-US', {
                                    year: 'numeric',
                                    month: 'short',
                                    day: 'numeric',
                                    hour: '2-digit',
                                    minute: '2-digit',
                                    hour12: true
                                });
                                const reportItem = `<div class="d-flex align-items-baseline right-bottom-border justify-content-between report-details" data-reportName="${item.title}" data-reportId="${item.reportId}" data-reportURL="${item.reportURL}" data-conclusion="${reports.conclusion}">
                                    <h5>${reportTime}</h5>
                                    <i class="fa fa-paperclip" aria-hidden="true"></i>
                                </div>`;
                                reportList.append(reportItem);
                            });
                        });
                    }else{
                        reportList.append('<p class="pt-2">Appointment history not available.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#reports-list').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function getPatientHistory(patientId){
                const practitionerId = "{{ session('PractitionerId') }}";
                const formData = new FormData();
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/patient/history/${practitionerId}/${patientId}`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('#history-list').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const historyList = $('#history-list');
                    historyList.empty();
                    if(response.data.length > 0){
                        response.data.forEach(item => {
                            const historyItem = `<div class="d-flex align-items-baseline right-bottom-border justify-content-between">
                                <h5 data-appointmentId="${item.appointmentId}" class="appointment-details">${item.date}</h5>
                                <a href="javascript:void(0)" id="version" data-classname="${item.timeSlot}" data-appointmentId="${item.appointmentId}">
                                    <i class="fas fa-plus" aria-hidden="true" data-classname="${item.timeSlot}" data-appointmentId="${item.appointmentId}"></i>
                                </a>
                            </div>
                            <div class="d-grid version ${item.timeSlot}" style="display: none;"></div>`;
                            historyList.append(historyItem);
                        });
                        $('.appointment-details').hover(
                            function() { $(this).parent().addClass('appointment-right'); },
                            function() { $(this).parent().removeClass('appointment-right'); }
                        );
                    }else{
                        historyList.append('<p class="pt-2">Appointment history not available.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#history-list').html('<p>Error loading appointment history. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function getVersions(appointmentId, className){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/appointment/history`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('.'+className).html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('.generate-prescription').addClass('d-none');
                $('.prescription').removeClass('d-none');

                $.ajax(settings).done(response => {
                    const historyList = $('.'+className);
                    historyList.empty();
                    response.data.forEach(item => {
                        const versionTime = new Date(item.date).toLocaleTimeString('en-US', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                            hour12: true
                        });
                        var historyItem = `<div class="d-flex align-items-baseline appointment-version-details right-bottom-border justify-content-between" data-versionId="${item.versionId}" data-description="${item.description}" data-comment="${item.comment}" data-patientInstruction="${item.patientInstruction}" data-documentId="${item.documentId}">
                            <h5>${versionTime}</h5>`;
                        if(item.documentId != '' && item.documentId != null && item.documentId != undefined) {
                            historyItem += `<i class="fa-solid fa-music border-0" aria-hidden="true"></i>`;
                        }
                        historyItem += `</div>`;
                        historyList.append(historyItem);
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.'+className).html('<p>Error loading appointment versions. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function appointmentDetails(appointmentId){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('timezone', timeZone);
                formData.append('date', '2024-05-17');
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/appointment/details`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.appointment-details-modal').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('.generate-prescription').addClass('d-none');
                $('.prescription').addClass('d-none');
                $('#appointmentDetailModal').modal('show');
                $.ajax(settings).done(response => {
                    $('.soap-summary').addClass('primary-bg-color');
                    $('.transacription').removeClass('primary-bg-color');
                    $('.prescription').removeClass('primary-bg-color');
                    const transacription = response.data.description;
                    const soapSummaryData = response.data.comment;
                    const soapSummary = md.render(soapSummaryData);
                    const prescription = isHTML(response.data.patientInstruction) ? response.data.patientInstruction : '<p>'+md.render(response.data.patientInstruction)+'</p>';
                    var html = '';
                    html += `<h6 class="appointment-id primary-color">Appointment ID: ${response.data.appointmentId}</h6>`;
                    html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                    html += `<div class="soap-summary-data"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                    html += `<div class="prescription-data d-none"><p>${prescription.length > 0 ? prescription : 'Prescription is not available.'}</p></div>`;
                    if(response.data.patientInstruction.length == 0) {
                        $('.generate-prescription').attr('soapNote', response.data.comment);
                        $('.generate-prescription').attr('appointmentId', response.data.appointmentId);
                        $('.generate-prescription').removeClass('d-none');
                        $('.prescription').addClass('d-none');
                    }else{
                        $('.prescription').removeClass('d-none');
                    }
                    $('.appointment-details-modal').html(html);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.appointment-details-modal').html(`
                        <p>Error loading appointment versions. Please try again later.</p>
                    `);
                    $('.prescription').removeClass('d-none');
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function generateTranscription(appointmentId, patientId, transcription) {
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('appointmentId', $('.user-list-left .user-item-left-selected').attr('data-appointmentid'));
                formData.append('patientId', $('.user-list-left .user-item-left-selected').attr('data-patientid'));
                formData.append('transcription', transcription);
                formData.append('timezone', timeZone);
                console.log(formData);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/transcription`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.appointment-details-modal').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('.soap-summary').addClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color').addClass('d-none');
                $('.generate-prescription').removeClass('primary-bg-color').addClass('d-none');
                $('#appointmentDetailModal').modal('show');
                $.ajax(settings).done(response => {
                    const transacription = response.data.description;
                    const soapSummaryData = response.data.comment;
                    const soapSummary = md.render(soapSummaryData);
                    const prescription = response.data.patientInstruction;
                    var html = '';
                    html += `<h6 class="appointment-id primary-color">Appointment ID: ${response.data.appointmentId}</h6>`;
                    html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                    html += `<div class="soap-summary-data"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                    html += `<div class="prescription-data d-none"><p>${response.data.patientInstruction.length > 0 ? prescription : 'Prescription is not available.'}</p></div>`;
                    $('.generate-prescription').attr('soapNote', response.data.comment);
                    $('.generate-prescription').attr('appointmentId', response.data.appointmentId);
                    $('.generate-prescription').removeClass('primary-bg-color').removeClass('d-none');
                    $('.appointment-details-modal').html(html);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.appointment-details-modal').html(`
                        <p>Error loading appointment versions. Please try again later.</p>
                    `);
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $(document).on('click', '.generate-transcription', function() {
                var transcription = '';
                $('.conversation .text').each(function() {
                    transcription += transcription.length > 0 ? '\n'+$(this).text() : $(this).text();
                });
                if(transcription == '' || transcription.length == 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Conversation data is required to generate SOAP Summary.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                const appointmentId = $('.user-list-left .user-item-left-selected').attr('data-appointmentid');
                const patientId = $('.user-list-left .user-item-left-selected').attr('data-patientid');
                generateTranscription(appointmentId, patientId, transcription);
            });
        
            $(document).on('click', '.user-item-left', function(){
                Swal.fire({
                    title: 'Consent',
                    text: "It is mandatory to obtain informed consent from the patient before recording their conversation.",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#34B6B3',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Ok',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('.audio-text-box').html('<audio id="audio" style="display:none" src="" controls controlsList="nodownload noplaybackrate"></audio>');
                        $('.user-item-left').removeClass('user-item-left-selected');
                        $('.patientName').text($(this).attr('data-patientName'));
                        $('.patientId').text('Patient ID: '+$(this).attr('data-patientId'));
                        $('.appointmentId').text('Appointment ID: '+$(this).attr('data-appointmentId'));
                        $(this).addClass('user-item-left-selected');
                        $('.center-box').addClass('d-none');
                        $('.center-box-selected').removeClass('d-none');
                        $('.appointment-close').addClass('d-none');
                        $('.appointment-show').removeClass('d-none');
                        getPatientHistory($(this).attr('data-patientId'));
                        getAllReports($(this).attr('data-patientId'));
                    }
                })
            });
        
            $('.collapse').on('show.bs.collapse', function() {
                $('.collapse.show').not(this).collapse('hide');
                $(this).prev('a').find('.fas').removeClass('fa-angle-down').addClass('fa-angle-up');
            }).on('hide.bs.collapse', function() {
                $(this).prev('a').find('.fas').removeClass('fa-angle-up').addClass('fa-angle-down');
            });
            
            $(document).on('click', '#version, #version i', function(event) {
                event.stopPropagation();
                $('.version').hide();
                const className = $(this).attr('data-classname');
                const appointmentId = $(this).attr('data-appointmentId');
                var iconPlusElement = $(this).is('i.fas.fa-plus') ? $(this) : $(this).find('i.fas.fa-plus');
                var iconMinusElement = $(this).is('i.fas.fa-minus') ? $(this) : $(this).find('i.fas.fa-minus');
                $('#version i').addClass('fa-plus').removeClass('fa-minus');
                if (iconPlusElement.length > 0) {
                    iconPlusElement.removeClass('fa-plus').addClass('fa-minus');
                    $('.'+className).show();
                    getVersions(appointmentId, className);
                } else if (iconMinusElement.length > 0) {
                    iconMinusElement.addClass('fa-plus').removeClass('fa-minus');
                } else {
                    console.log('icon is not available');
                }
            });
        
            $(document).on('click', '.erase', function(){
                var transcription = '';
                $('.conversation .text').each(function() {
                    transcription += transcription.length > 0 ? '\n'+$(this).text() : $(this).text();
                });
                if(transcription != '' || transcription.length != 0) {
                    Swal.fire({
                        title: 'Clear',
                        text: "Are you sure you wish to clear the conversation data?",
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#34B6B3',
                        cancelButtonColor: '#d33',
                        confirmButtonText: 'Yes',
                        cancelButtonText: 'No'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $('.audio-text-box').html('<audio id="audio" style="display:none" src="" controls controlsList="nodownload noplaybackrate"></audio>');
                        }
                    })
                }
            });
        
            $(document).on('click', '.appointment-version-details', function(){
                $('.appointment-version-details').removeClass('version-selected');
                $('.appointment-details').parent().removeClass('version-selected');
                $(this).addClass('version-selected');
                $('.soap-summary').addClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                const transacription = $(this).attr('data-description');
                const soapSummaryData = $(this).attr('data-comment');
                const soapSummary = md.render(soapSummaryData);
                const prescriptionHTML = $(this).attr('data-patientInstruction');
                const prescription = isHTML(prescriptionHTML) ? prescriptionHTML : '<p>'+md.render(prescriptionHTML)+'</p>';
                const documentId = $(this).attr('data-documentid');
                const classTime = new Date().getTime();
                var html = '';
                html += `<div class="transcription-data d-none">
                            <p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p>`;
                if(documentId != ''){
                    html += `<audio id="modal-audio" src="" controls controlsList="nodownload noplaybackrate"></audio>`;
                }
                html += `</div><div class="soap-summary-data"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                html += `<div class="prescription-data d-none"></div>`;
                $('.appointment-details-modal').html(html);
                $('.prescription-data').html(prescription.length > 0 ? prescription : 'Prescription is not available.');
                $('#appointmentDetailModal').modal('show');
                if(documentId != ''){
                    getDocument(documentId, classTime);
                }
            });
            
            $(document).on('click', '.appointment-details', function(){
                $('.appointment-details').parent().removeClass('version-selected');
                $('.appointment-version-details').removeClass('version-selected');
                $(this).parent().addClass('version-selected');
                const appointmentId = $(this).attr('data-appointmentId');
                appointmentDetails(appointmentId);
            });
            
            $(document).on('click', '.modal-close', function() {
                $('.appointment-details').parent().removeClass('version-selected');
                $('.appointment-version-details').removeClass('version-selected');
                $('.soap-summary').addClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                $('.appointment-details-modal').html('');
                $('#appointmentDetailModal').modal('hide');
                $('.report-details').removeClass('report-selected');
                $('.reports').removeClass('primary-bg-color');
                $('.report-summary').addClass('primary-bg-color');
                $('.report-modal').html('');
                $('#reportModal').modal('hide');
            });
            
            $(document).on('click', '.transacription', function(){
                $(this).addClass('primary-bg-color');
                $('.soap-summary').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                $('.transcription-data').removeClass('d-none');
                $('.soap-summary-data').addClass('d-none');
                $('.prescription-data').addClass('d-none');
            });
            
            $(document).on('click', '.soap-summary', function(){
                $(this).addClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                $('.transcription-data').addClass('d-none');
                $('.soap-summary-data').removeClass('d-none');
                $('.prescription-data').addClass('d-none');
                var audioElement = $('#modal-audio')[0];
                if (audioElement && typeof audioElement.pause === 'function' && !audioElement.paused) {
                    audioElement.pause();
                }
            });
            
            $(document).on('click', '.prescription', function(){
                $(this).addClass('primary-bg-color');
                $('.soap-summary').removeClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.transcription-data').addClass('d-none');
                $('.soap-summary-data').addClass('d-none');
                $('.prescription-data').removeClass('d-none');
                var audioElement = $('#modal-audio')[0];
                if (audioElement && typeof audioElement.pause === 'function' && !audioElement.paused) {
                    audioElement.pause();
                }
            });
            
            /*Document by URL*/
            function getDocument(url) {
                const formData = new FormData();
                formData.append('documentId', url);
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/appointment/document`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    $('#modal-audio').attr('src', 'data:audio/mp3;base64,'+response.data.audio_file);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    $('#modal-audio').attr('src', '');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            /* Report Details */
            $(document).on('click', '.report-details', function(){
                $('.report-details').removeClass('report-selected');
                $(this).addClass('report-selected');
                $('.report-summary').addClass('primary-bg-color');
                $('.reports').removeClass('primary-bg-color');
                const reportName = $(this).attr('data-reportName');
                const reportId = $(this).attr('data-reportid');
                const reportURL = $(this).attr('data-reporturl');
                const conclusionData = $(this).attr('data-conclusion');
                const conclusion = isHTML(conclusionData) ? conclusionData : '<p>'+md.render(conclusionData)+'</p>';
                var html = '';
                html += `<div class="reportlist-data d-none">
                            <ul>
                                <li id="report-file" data-reportid="${reportId}" data-reporturl="${reportURL}">${reportName.length > 0 ? reportName : 'Reports are not available.'}</li>
                            </ul>
                        </div>`;
                html += `<div class="report-summary-data"></div>`;
                $('.report-modal').html(html);
                $('.report-summary-data').html(conclusion);
                $('#reportModal').modal('show');
            });
            
            $(document).on('click', '.reports', function(){
                $(this).addClass('primary-bg-color');
                $('.report-summary').removeClass('primary-bg-color');
                $('.reportlist-data').removeClass('d-none');
                $('.report-summary-data').addClass('d-none');
            });

            $(document).on('click', '.report-summary', function(){
                $(this).addClass('primary-bg-color');
                $('.reports').removeClass('primary-bg-color');
                $('.reportlist-data').addClass('d-none');
                $('.report-summary-data').removeClass('d-none');
            });

            $(document).on('click', '#report-file', function(){
                const reportId = $(this).attr('data-reportid');
                const reportURL = $(this).attr('data-reporturl');
                getReport(reportId, reportURL);
                $('.reports').removeClass('primary-bg-color');
                $('.reportlist-data').addClass('d-none');
                $('.report-summary-data').removeClass('d-none');
            });
            
            $(document).on('click', '.report-modal-close', function(){
                $('.reports').addClass('primary-bg-color');
                $('.reportFile-data').html('');
                $('.reportlist-data').removeClass('d-none');
                $('.report-summary-data').addClass('d-none');
                jQuery('#reportFile').modal('hide');
            });
            
            /*Report by URL*/
            function getReport(reportId, reportURL) {
                const formData = new FormData();
                formData.append('reportId', reportId);
                formData.append('reportURL', reportURL);
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/report/details`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#reportFile').modal('show');
                jQuery('.reportFile-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    if(response.data.contentType.includes('image')){
                        $('.reportFile-data').html('<img style="height: 90vh; width: 100%;" src="data:'+response.data.contentType+';base64,'+response.data.data+'">');
                    } else {
                        $('.reportFile-data').html('<iframe style="height: 90vh; width: 100%;" src="data:'+response.data.contentType+';base64,'+response.data.data+'"></iframe>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    $('.reportFile-data').html('');
                    jQuery('#reportFile').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $(document).on('click', '.report-upload', function(){
                $('.reportUploadList-data').html('');
                jQuery('#reportUpload').modal('show');
                getAppointmentReports();
            });
            
            function getAppointmentReports(){
                const formData = new FormData();
                formData.append("appointmentId", $('.user-item-left-selected').attr('data-appointmentId'));
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "https://api.dev.med-x.ai/api/v1/ehr-default/reports",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('.reportUploadList-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const reportList = $('.reportUploadList-data');
                    reportList.empty();
                    if(response.data.length > 0){
                        response.data.forEach(item => {
                            const reportItem = `<div class="right-bottom-border uploadList">
                                <h5 id="report-file" class="mb-0" data-reportid="${item.reportId}" data-reporturl="${item.reportURL}">${item.title}</h5>
                            </div>`;
                            reportList.append(reportItem);
                        });
                    }else{
                        reportList.append('<p class="pt-2">Reports for appointment are not available.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.reportUploadList-data').html('<p>Error loading reports. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $('#fileInput').on('change', function () {
                var files = $('#fileInput')[0].files;
                var maxSize = 32 * 1024 * 1024; // 32MB for images and PDFs
                var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
                var valid = true;
                var formData = new FormData();
                const reportList = $('.reportUploadList-data');
                if (files.length === 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'File Validation Failed!',
                        text: 'Please select a file to upload.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return;
                }
                $.each(files, function (index, file) {
                    if ($.inArray(file.type, allowedTypes) === -1) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Type',
                            text: 'Invalid file type: ' + file.name + '. Allowed file type are .jpeg, .png or .pdf.',
                            confirmButtonColor: '#34B6B3',
                            customClass: {
                                title: 'my-custom-title',
                                content: 'my-custom-content'
                            }
                        });
                        valid = false;
                        return false;
                    }
        
                    // Validate file size
                    if (file.size > maxSize) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Size',
                            text: 'Please select allowed file size. File size must be less than 32MB for file: ' + file.name,
                            confirmButtonColor: '#34B6B3',
                            customClass: {
                                title: 'my-custom-title',
                                content: 'my-custom-content'
                            }
                        });
                        valid = false;
                        return false;
                    }
        
                    formData.append('reports[]', file);
                });
                if (!valid) {
                    return;
                }
                reportList.empty();
                reportList.append(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                formData.append("appointmentId", $('.user-item-left-selected').attr('data-appointmentId'));
                formData.append("patientId", $('.user-item-left-selected').attr('data-patientId'));
                formData.append("practitionerId", "{{ session('PractitionerId') }}");
                formData.append('timezone', timeZone);
                // AJAX request to upload file
                $.ajax({
                    url: 'https://api.dev.med-x.ai/api/v1/ehr-default/reports/upload',
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    mimeType: "multipart/form-data",
                    processData: false,
                    success: function (response) {
                        reportList.empty();
                        if (response.success && response.data.length > 0) {
                            response.data.forEach(item => {
                                const reportItem = `<div class="right-bottom-border uploadList">
                                    <h5 id="report-file" data-reportid="${item.reportId}" data-reporturl="${item.reportURL}">${item.title}</h5>
                                </div>`;
                                reportList.append(reportItem);
                            });
                        }else{
                            reportList.append('<p class="pt-2">Reports for appointment are not available.</p>');
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        getAppointmentReports();
                        console.log(jqXHR, errorThrown);
                        console.log('File upload failed. Please try again.');
                    }
                });
            });
            
            /* Prescription Generation */
            function generatePrescription(appointmentId, soapNote) {
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', $('.user-list-left .user-item-left-selected').attr('data-patientid'));
                formData.append('appointmentId', appointmentId);
                formData.append('soapSummary', soapNote);
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/generate/prescription`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.prescription-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    const prescriptionHTML = response.data.patientInstruction;
                    const prescription = isHTML(prescriptionHTML) ? prescriptionHTML : '<p>'+md.render(prescriptionHTML)+'</p>';
                    $('.prescription-data').html(prescriptionHTML.length > 0 ? prescription : 'Prescription is not available.');
                    $('.prescription').addClass('primary-bg-color').removeClass('d-none');
                    $('.generate-prescription').removeClass('primary-bg-color').addClass('d-none');
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.prescription-data').html(errorThrown);
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $(document).on('click', '.generate-prescription', function(){
                const soapNote = $(this).attr('soapNote');
                if(soapNote == '' || soapNote.length < 10) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'SOAP summary is required to Preacription.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                const appointmentId = $(this).attr('appointmentId');
                $('.version').hide();
                $('.version').html('');
                $('#version i').removeClass('fa-minus').addClass('fa-plus');
                $('.transcription-data').addClass('d-none');
                $('.soap-summary-data').addClass('d-none');
                $('.prescription-data').removeClass('d-none');
                $('.transacription').removeClass('primary-bg-color');
                $('.soap-summary').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                $(this).addClass('primary-bg-color');
                generatePrescription(appointmentId, soapNote);
            });
        });
        
        function logout() {
            // Create an invisible iframe
            var iframe = document.createElement('iframe');
            iframe.style.display = 'none';
            iframe.name = 'logoutIframe';
            document.body.appendChild(iframe);

            // Create a form and set its target to the iframe
            var form = document.createElement('form');
            form.method = 'GET';
            form.action = 'https://auth.zapehr.com/logout';
            form.target = 'logoutIframe'; // Submit the form to the iframe
            form.style.display = 'none';
            document.body.appendChild(form);
            form.submit();
        
            // Optionally, monitor for iframe's load event
            iframe.onload = function() {
                document.body.removeChild(iframe);
                window.location.href = 'https://medx-web.hveer.com/logout';
            };
        }
        
        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;
        
        // document.getElementById('logoutButton').addEventListener('click', function() {
        //     var form = document.createElement('form');
        //     form.method = 'GET';
        //     form.action = 'https://auth.zapehr.com/logout';
        //     form.style.display = 'none';
        //     document.body.appendChild(form);
        //     form.submit();
        
        //     // Optionally, monitor for response completion and redirect afterward
        //     setTimeout(function() {
        //         console.log('working');
        //         // Redirect to login page after a delay (assuming logout completed)
        //         window.location.href = 'https://medx-web.hveer.com'; // Replace with your login page URL
        //     }, 2000); // Adjust the timeout as needed
        // });
    </script>
</body>
</html>