@extends('app')
@section('title', 'Med-X | Scribe')

@section('content')
    <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">
                        <a href="/dashboard">
                            <img src="{{env('AUTH_SERVER_URL')}}/public/images/MedX-Logo.png" width="75%" alt="Med-X Logo">
                        </a>
                    </div>
                    @if(session()->has('features') && in_array('APPOINTMENT', session()->get('features')))
                        <div class="col-sm-2 icons" id="add-appointment">
                            <i class="fas fa-calendar-plus primary-color" aria-label="Add Appointment"></i>
                        </div>
                    @endif
                </div>
                <div class="input-group mt-3">
                    <input type="text" class="form-control" id="searchPatient" value="MRN|203711" placeholder="Search Patient" aria-label="Search Patient">
                    <div class="input-group-append" id="searchPatientBtn">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <h3 class="font-weight-light mt-3 mb-0 left-title"></h3>
                <div class="user-list user-list-left"><p>Search patient to get scheduled appointment.</p></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>
                        <img src="{{env('APP_URL')}}/public/assets/img/recording.gif" class="d-none recording" />
                        <img src="{{env('APP_URL')}}/public/assets/img/pause.gif" class="d-none pause-recording-icon" />
                    </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="name-left border-0 pb-0 pt-1">
                        <h4 class="secondary-color mb-0">{{session('PractitionerName')}}</h4>
                        <small class="primary-color">{{session('suffix')}}</small>
                    </div>
                </div>
                <div class="input-group mt-3">
                    <input type="text" class="form-control" placeholder="Search Patient History" id="searchHistory" 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>
        <!-- Add Appointment Modal -->
        <div class="modal" id="addAppointment" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-md modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Schedule an Appointment</h5>
                    </div>
                    <div class="patient-loading"></div>
                    <form id="appointmentForm">
                        <input type="hidden" id="patient" />
                        <input type="hidden" id="patientName" />
                        <input type="hidden" id="slotDate" />
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="patientId" class="col-form-label">Patient</label>
                                        <select id="patientId" class="form-control" required>
                                            <option value="" disabled selected>Please Select</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label for="visit" class="col-form-label">Appointment Type</label>
                                        <select id="visit" class="form-control" required>
                                            <option value="">Please Select</option>
                                            <option value="FIRST VISIT">FIRST VISIT</option>
                                            <option value="FOLLOWUP">FOLLOWUP</option>
                                            <option value="EMERGENCY">EMERGENCY</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-sm-6">
                                    <div class="form-group">
                                        <label class="col-form-label">Appointment Date</label>
                                        <div id="appointmentDate"></div>
                                    </div>
                                </div>
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <label class="col-form-label">Appointment Time</label>
                                        <div id="time"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer justify-content-center appointment-footer">
                            <button type="submit" class="btn btn-outline-primary">Save</button>
                            <button type="button" class="btn btn-outline-danger appointment-add-modal-close" data-dismiss="modal">Close</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!-- Edit Modal -->
        <div class="modal" id="editModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-md modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title appointmentId">Update Content</h5>
                    </div>
                    <form id="editForm">
                        <input type="hidden" id="edit-appointmentId" />
                        <input type="hidden" id="update-url" value="soap-summary/edit" />
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-sm-12">
                                    <textarea class="form-gorup" id="content"></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer justify-content-center edit-footer">
                            <button type="submit" class="btn btn-outline-primary">Save</button>
                            <button type="button" class="btn btn-outline-danger edit-modal-close" data-dismiss="modal">Close</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!-- Help Modal -->
        <div class="modal" id="helpModal" 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-header">
                        <i class="material-icons" data-dismiss="modal">arrow_back</i>
                        <h5 class="modal-title">
                            Help Documentation
                        </h5>
                        <span class="web-version">V - 1.6</span>
                    </div>
                    <div class="modal-body help-body">
                    </div>
                </div>
            </div>
        </div>
        <!-- AI Content Generation Confirm Modal -->
        <div class="modal" id="notes" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog modal-md modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Generate Note</h5>
                    </div>
                    <div class="patient-loading"></div>
                    <form id="notesForm">
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-sm-12">
                                    <div class="form-group">
                                        <label for="generateType" class="col-form-label">Select Note</label>
                                        <select id="generateType" class="form-control" required>
                                            <option value="" disabled>Please Select</option>
                                            <option value="SOAPNOTE" selected>SOAP Summary</option>
                                            <option value="PROGRESSNOTE">Progress Notes</option>
                                            <option value="PROCEDURENOTE">Procedure Notes</option>
                                            <option value="DISCHARGENOTE">Discharge Summary</option>
                                            <option value="HISTORY-PHYSICAL">History & Physical</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div id="hisotry" class="row d-none">
                                <div class="col-md-6">
                                    <label for="hisotryData" class="col-form-label">Select SOAP from history</label>
                                    <div id="hisotryData"></div>
                                </div>
                                <div class="col-md-6">
                                    <label for="reportData" class="col-form-label">Select Report(s)</label>
                                    <div id="reportData"></div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer justify-content-center note-footer">
                            <button type="submit" class="btn btn-outline-primary">Save</button>
                            <button type="button" class="btn btn-outline-danger note-modal-close" data-dismiss="modal">Close</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="modal" id="noteDetailModal" 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 note-details-modal"></div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-danger modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </main>
@endsection

@push('scripts')
    <script>
        $(document).ready(function() {
            const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            const md = window.markdownit();
            var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
            const currentDate = new Date();
            const options = { year: 'numeric', month: 'short', day: '2-digit' };
            const formattedDate = currentDate.toLocaleDateString('en-US', options);

            var easyMDE = new EasyMDE({
                element: document.getElementById('content'),
                autoDownloadFontAwesome: false,
                spellChecker: false,
            });
            
            function getBookedSlots(date) {
                const formData = new FormData();
                formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('date', date);
                formData.append('timezone', timeZone);
                jQuery('#slotDate').val(date);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/available/slots",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#time').html(`
                    <div class="loader-container mb-5">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    $('#time').empty();
                    if (response.success) {
                        var slotsHtml = '<div class="row col-12">';
                        const uniqueAppointments = [];
                        const startTimes = new Set();
                        response.data.forEach(appointment => {
                            const uniqueId = `timeSlot_${appointment.startTime}`;
                            slotsHtml += `<div class="mr-2 pr-1">
                                <input type="radio" name="timeSlot" id="${uniqueId}" value="${appointment.startTime}" data-appointmentId="${appointment.appointmentId}" required>
                                <label class="custom-radio ${uniqueId}" for="${uniqueId}">${appointment.startTimeText}</label>
                            </div>`;
                        });
                        slotsHtml += `</div>`;
                        $('#time').html(slotsHtml);
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $('#patientId').select2({
                placeholder: "Please Select",
                allowClear: false
            });
            $('#patientId').on('select2:select', function (e) {
                var data = e.params.data;
                jQuery('#patient').val(data.id);
                jQuery('#patientName').val(data.text);
            });
            var datePicker = $("#appointmentDate").dxDateBox({
                applyValueMode: 'useButtons',
                value: currentDate,
                max: new Date(currentDate.getFullYear() + 1, currentDate.getMonth(), currentDate.getDate()),
                min: currentDate,
                inputAttr: { 'aria-label': 'Appointment Date' },
                onValueChanged(data) {
                    var selectedDate = data.value;
                    var year = selectedDate.getFullYear();
                    var month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
                    var day = selectedDate.getDate().toString().padStart(2, '0');
                    getBookedSlots(`${year}-${month}-${day}`);
                },
                // opened: true,
                showClearButton: false,
                closeOnOutsideClick: false,
                focusStateEnabled: false
            }).dxDateBox("instance");

            jQuery('.dx-texteditor-input').attr('readonly', true);
            $("#appointmentDate").on("click", function() {
                datePicker.open();
            });

            $('.select2').on('select2:open', function () {
                $('.select2-container--open').css('z-index', 9999);
            });
            
            // Search Patient
            jQuery('#searchPatientBtn').on('click', function() {
                var search = jQuery('#searchPatient').val();
                if(search == ''){
                    Swal.fire({
                        icon: 'error',
                        text: 'Patient identification is required',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;    
                }
                const formData = new FormData();
                formData.append('identifier', search);
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/patients",
                    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 => {
                    jQuery('.left-title').text('Patient List');
                    const userList = $('.user-list-left');
                    userList.empty();
                    const currentTime = new Date();
                    response.data.forEach(item => {
                        console.log(item);
                        const userItem = `
                            <div class="user-item-left-patient" data-patientId="${item.patientId}" data-patientName="${item.patientName}">
                                <h5>${item.patientName}</h5>
                                <small>${item.patientId}</small>
                            </div>
                        `;
                        
                        userList.append(userItem);
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error searching patients. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            $(document).on('click', '.user-item-left-patient', function(){
                $('.user-item-left-patient').removeClass('user-item-left-patient-selected');
                $('.patientName').text($(this).attr('data-patientName'));
                $('.patientId').text('Patient ID: '+$(this).attr('data-patientId'));
                $(this).addClass('user-item-left-patient-selected');
                getAppointments($(this).attr('data-patientId'));
            });
            
            var appointmentsData = [];
            function displayAppointments(scheduledAppointments) {
                const userList = $('.user-list-left');
                userList.empty();
                const currentTime = new Date();
                scheduledAppointments.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' });
                    let timeDiff = itemTimeSlot - currentTime;
                    let dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)) + 1;
                    // 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-daydiff="${dayDiff}" data-appointmentId="${appointmentId}" data-patientId="${patientId}" data-patientName="${patientName}" data-encounterId="${item.encounterId}">
                            <h5>${patientName}</h5>
                            <small>${appointmentTime} | ${appointmentType}</small>
                        </div>
                    `;
                    
                    userList.append(userItem);
                });
            }
            
            function getAppointments(patient){
                const formData = new FormData();
                formData.append('patient', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('practitioner', "ewyZVtBwkC0w85m69VbpXwQ3");
                // remove above and uncomment below
                // formData.append('patient', patient);
                // formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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 => {
                    appointmentsData = response.data;
                    jQuery('.left-title').text('Scheduled Visits');
                    displayAppointments(response.data);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            // getAppointments();
            
            $(document).on('click', '.user-item-left', function(){
                $('.audio-text-box').html(`<audio id="audio" style="display:none" src="" controls controlsList="nodownload noplaybackrate"></audio><img src="{{env('APP_URL')}}/public/assets/img/recording.gif" class="d-none recording" /><img src="{{env('APP_URL')}}/public/assets/img/pause.gif" class="d-none pause-recording-icon" />`);
                $('.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'), $(this).attr('data-encounterId'));
            });
            
            // jQuery('#searchPatient').keyup(function() {
            //     var searchInput = jQuery(this).val().toLowerCase();
            //     var filteredAppointments = appointmentsData.filter(function(appointment) {
            //         return appointment.patient.toLowerCase().includes(searchInput);
            //     });
            //     if (filteredAppointments.length > 0) {
            //         displayAppointments(filteredAppointments)
            //     } else {
            //         jQuery('.user-list-left').html('<p>No patients found</p>');
            //     }
            // });
            
            // Audio Recording
            let recorder;
            let audioData = [];
            let isPaused = false;
            let timerIntervalId;
            AudioRecorder.preload("{{env('APP_URL').'/public/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) => {
                    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("encounterId", $('.user-item-left-selected').attr('data-encounterId'));
                // remove below 4 lines
                form.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                form.append('practitionerId', 'elpRiy0AYgjhdjAhTBJ3Aiw3');
                form.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                form.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                form.append("audio_file", mp3Blob, $('.user-item-left-selected').attr('data-appointmentId')+"T"+new Date().getTime()+'.mp3');

                const settings = {
                    "url": "{{env('API_URL')}}{{session('currentEHR')}}/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');
                });
            }
            
            $(document).on('click', '.start-recording', async function() {
                var appointmentid = $('.user-list-left .user-item-left-selected').attr('data-appointmentid');
                let cookieArr = document.cookie.split(";");
                let checked = false;
                for (let cookie of cookieArr) {
                    let [cookieName, cookieValue] = cookie.trim().split("=");
                    if (cookieName === appointmentid) {
                        checked = true;
                    }
                }
                if(checked === false){
                    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) {
                            var daydiff = $('.user-list-left .user-item-left-selected').attr('data-daydiff');
                            let expires = "";
                            let date = new Date();
                            date.setTime(date.getTime() + (daydiff * 24 * 60 * 60 * 1000));
                            expires = "; expires=" + date.toUTCString();
                            document.cookie = appointmentid + "=" + encodeURIComponent(appointmentid) + expires + "; path=/";
                            setupRecorder();
                            $('.start-recording').addClass('d-none');
                            $('.pause-recording').removeClass('d-none');
                            $('.stop-recording').removeClass('d-none');
                            jQuery('.recording').removeClass('d-none');
                            jQuery('.pause-recording-icon').addClass('d-none');
                            recorder.start();
                        }
                    });
                }else{
                    setupRecorder();
                    $('.start-recording').addClass('d-none');
                    $('.pause-recording').removeClass('d-none');
                    $('.stop-recording').removeClass('d-none');
                    jQuery('.recording').removeClass('d-none');
                    jQuery('.pause-recording-icon').addClass('d-none');
                    recorder.start();
                }
            });
        
            $(document).on('click', '.pause-recording', function() {
                if (recorder && !isPaused) {
                    recorder.pause();
                    isPaused = true;
                    jQuery('.recording').addClass('d-none');
                    jQuery('.pause-recording-icon').removeClass('d-none');
                    $('.play-recording').removeClass('d-none');
                    $('.pause-recording').addClass('d-none');

                }
            });
        
            $(document).on('click', '.play-recording', function() {
                if (recorder && isPaused) {
                    recorder.resume();
                    isPaused = false;
                    jQuery('.recording').removeClass('d-none');
                    $('.play-recording').addClass('d-none');
                    $('.pause-recording').removeClass('d-none');
                    jQuery('.pause-recording-icon').addClass('d-none');
                }
            });
        
            $(document).on('click', '.stop-recording', function() {
                clearInterval(timerIntervalId);
                $('.start-recording').removeClass('d-none');
                $('.play-recording').addClass('d-none');
                $('.pause-recording').addClass('d-none');
                $('.stop-recording').addClass('d-none');
                jQuery('.recording').addClass('d-none');
                jQuery('.pause-recording-icon').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, encounterId){
                const formData = new FormData();
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                formData.append('practitionerId', 'elpRiy0AYgjhdjAhTBJ3Aiw3');
                // remove above and uncomment below
                // formData.append('practitionerId', "{{ session('PractitionerId') }}");
                // formData.append('patientId', patientId);
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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){
                        jQuery('#reportData').html('');
                        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.fileName}" data-conclusion="${reports.conclusion}">
                                    <h5>${reportTime}</h5>
                                    <i class="fa fa-paperclip" aria-hidden="true"></i>
                                </div>`;
                                reportList.append(reportItem);
                                if(item.reportSummary != '' && cnt <= 10){
                                    jQuery('#reportData').append(`
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="reportHistory[]" value="${encodeURIComponent(reports.reportSummary)}" id="reportSummary-${reportTime}">
                                            <label class="form-check-label fw-500" for="reportSummary-${reportTime}">${reportTime}</label>
                                        </div>
                                    `);
                                    cnt++;
                                }
                            });
                        });
                    }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);
                });
            }
            
            var patientHistoryData = [];
            function displayHistoryList(historyData) {
                const historyList = $('#history-list');
                historyList.empty();
                if(historyData.length > 0){
                    var cnt = 1;
                    var noHistory = false;
                    jQuery('#hisotryData').html('');
                    historyData.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);
                        if(item.comment != '' && noHistory == false) {
                            const soapSummaryData = item.comment;
                            let [date, ...paragraphs] = soapSummaryData.split(":");
                            let summaryData = paragraphs.join(":").slice(4);
                            const soapSummary = isHTML(summaryData) ? summaryData : md.render(summaryData);
                            jQuery('.audio-text-box').append(`<div class="pl-3 pt-2"><h5 class="primary-color">${date}</h5>${soapSummary}</div>`);
                            noHistory = true;
                        }
                        if(item.comment != '' && cnt <= 10){
                            var checked = '';
                            var disabled = '';
                            if(cnt == 1 && formattedDate != item.date){
                                jQuery('#hisotryData').append(`
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" disabled checked id="soapSummary-${formattedDate}">
                                        <label class="form-check-label fw-500" for="soapSummary-${formattedDate}">${formattedDate}</label>
                                    </div>
                                `);
                            }
                            checked = formattedDate == item.date ? 'disabled' : '';
                            disabled = formattedDate == item.date ? 'disabled' : '';
                            jQuery('#hisotryData').append(`
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" ${checked} ${disabled} name="soapHistory[]" value="${encodeURIComponent(item.comment)}" id="soapSummary-${item.date}">
                                    <label class="form-check-label fw-500" for="soapSummary-${item.date}">${item.date}</label>
                                </div>
                            `);
                            cnt++;
                        }
                    });
                    if(!noHistory){
                        jQuery('.audio-text-box').append('<p class="pl-3 pt-2">Previous medical history is not available.</p>'); 
                    }
                    $('.appointment-details').hover(
                        function() { $(this).parent().addClass('appointment-right'); },
                        function() { $(this).parent().removeClass('appointment-right'); }
                    );
                }else{
                    jQuery('.audio-text-box').append('<p class="pl-3 pt-2">Previous medical history is not available.</p>');
                    historyList.append('<p class="pt-2">Appointment history not available.</p>');
                }
            }
            
            function getPatientHistory(patientId){
                const practitionerId = "{{ session('PractitionerId') }}";
                const formData = new FormData();
                formData.append('timezone', timeZone);
                var URL = `{{env('API_URL')}}{{session('currentEHR')}}/patient/history/${practitionerId}/${patientId}`;
                // remove below URL
                var URL = `{{env('API_URL')}}{{session('currentEHR')}}/patient/history/ewyZVtBwkC0w85m69VbpXwQ3/erXuFYUfucBZaryVksYEcMg3`;
                const settings = {
                    url: URL,
                    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 => {
                    patientHistoryData = response.data;
                    displayHistoryList(response.data);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#history-list').html('<p>Error loading appointment history. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            jQuery('#searchHistory').keyup(function() {
                var searchInput = jQuery(this).val().toLowerCase();
                var filteredHistory = patientHistoryData.filter(function(history) {
                    return history.date.toLowerCase().includes(searchInput);
                });
                displayHistoryList(filteredHistory);
            });
            
            function getVersions(appointmentId, className){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                // remove below 2 lines while live
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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);
                // remove below line while live
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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 = isHTML(soapSummaryData) ? soapSummaryData : md.render(soapSummaryData);
                    const prescription = isHTML(response.data.patientInstruction) ? response.data.patientInstruction : '<p>'+md.render(response.data.patientInstruction)+'</p>';
                    var html = '';
                    html += `<span class="app-title"><h6 class="appointment-id primary-color">Appointment ID: ${response.data.appointmentId}</h6><i class="material-icons" id="edit-btn" data-appointmentId="${response.data.appointmentId}" data-content="${response.data.comment}">edit</i></span>`;
                    html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                    html += `<div class="soap-summary-data" data-content="${response.data.comment}"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                    html += `<div class="prescription-data d-none" data-content="${response.data.patientInstruction}"><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(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('encounterId', $('.user-list-left .user-item-left-selected').attr('data-encounterid'));
                // remove below 4 lines
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('practitionerId', 'elpRiy0AYgjhdjAhTBJ3Aiw3');
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                formData.append('transcription', transcription);
                formData.append('timezone', timeZone);
                var generateType = jQuery('#generateType').val();
                var selectedText = $('#generateType option:selected').text();
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/transcription",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $('#notes').modal('hide');
                if(generateType == 'SOAPNOTE'){
                    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');
                }else{
                    jQuery('.note-details-modal').html(`
                        <p class="loading-p">Generating SOAP summary...</p>
                        <div class="loader-container">
                            <div class="loader" id="loader"></div>
                        </div>
                    `);
                    $('#noteDetailModal').modal('show');
                }
                $.ajax(settings).done(response => {
                    if(generateType == 'SOAPNOTE'){
                        const transacription = response.data.description;
                        const soapSummaryData = response.data.comment;
                        const soapSummary = md.render(soapSummaryData);
                        const prescription = response.data.patientInstruction;
                        var html = '';
                        html += `<span class="app-title"><h6 class="appointment-id primary-color">Appointment ID: ${response.data.appointmentId}</h6><i class="material-icons d-none" id="edit-btn" data-appointmentId="${response.data.appointmentId}" data-content="${encodeURIComponent(soapSummaryData)}">edit</i></span>`;
                        html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                        html += `<div class="soap-summary-data" data-content="${encodeURIComponent(soapSummaryData)}"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                        html += `<div class="prescription-data d-none" data-content="${encodeURIComponent(prescription)}"><p>${response.data.patientInstruction.length > 0 ? prescription : 'Prescription is not available.'}</p></div>`;
                        $('.generate-prescription').attr('soapNote', encodeURIComponent(response.data.comment));
                        $('.generate-prescription').attr('appointmentId', response.data.appointmentId);
                        $('.generate-prescription').removeClass('primary-bg-color').removeClass('d-none');
                        $('.appointment-details-modal').html(html);
                        $('#edit-btn').removeClass('d-none');
                        getPatientHistory($('.user-list-left .user-item-left-selected').attr('data-patientid'));
                    } else {
                        const soapSummaryData = response.data.comment;
                        jQuery('.note-details-modal').html(`
                            <p class="loading-p">Generating ${selectedText}...</p>
                            <div class="loader-container">
                                <div class="loader" id="loader"></div>
                            </div>
                        `);
                        generateNote(soapSummaryData);
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.appointment-details-modal').html(`
                        <p>Error loading appointment versions. Please try again later.</p>
                    `);
                    jQuery('.note-details-modal').html(`
                        <p>Error while generating note. Please try again later.</p>
                    `);
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }

            function generateNote(soapNote) {
                var generateType = jQuery('#generateType').val();
                var selectedText = $('#generateType option:selected').text();
                let soapHistory = $('input[name="soapHistory[]"]:checked')
                    .map(function() {
                        return decodeURIComponent($(this).val());
                    })
                    .get()
                    .filter(function(value) {
                        return !value.includes(formattedDate);
                    })
                    .join('\n\n');
                let reportHistory = $('input[name="reportHistory[]"]:checked')
                    .map(function() {
                        return decodeURIComponent($(this).val());
                    })
                    .get()
                    .join('\n\n');
                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('soapSummaries', formattedDate+':\n\n'+soapNote+'\n\n'+soapHistory);
                formData.append('reportSummaries', reportHistory);
                formData.append('noteType', generateType);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/generate/note",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $('#notesForm').trigger('reset');
                $.ajax(settings).done(response => {
                    const generatedNoteData = response.data.generatedNote;
                    const generatedNote = md.render(generatedNoteData);
                    const notAvail = selectedText+' is not available.';
                    var html = '';
                    html += `<span class="app-title"><h6 class="appointment-id primary-color">Appointment ID: ${$('.user-list-left .user-item-left-selected').attr('data-appointmentid')}</h6></span>`;
                    html += `<div class="transcription-data"><p>${generatedNote.length > 0 ? generatedNote : notAvail}</p></div>`;
                    $('.note-details-modal').html(html);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.note-details-modal').html(`
                        <p>Error while generating note. Please try again later.</p>
                    `);
                    $('#noteDetailModal').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;
                }
                generateTranscription(transcription);
                // $('#notes').modal('show');
            });

            $(document).on('change', '#generateType', function(){
                var selected = $(this).val();
                if(selected == 'DISCHARGENOTE' || selected == 'HISTORY-PHYSICAL') {
                    $('#hisotry').removeClass('d-none');
                } else {
                    $('input[name="soapHistory[]"]').prop('checked', false);
                    $('input[name="reportHistory[]"]').prop('checked', false);
                    $('#hisotry').addClass('d-none');
                }
            });
            
            jQuery('#notesForm').on('submit', function(e) {
                e.preventDefault();
                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;
                }
                generateTranscription(transcription);
            });
            
            jQuery('.note-modal-close').on('click', function() {
                $('#notesForm').trigger('reset');
            });

            $('.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><img src="{{env('APP_URL')}}/public/assets/img/recording.gif" class="d-none recording" /><img src="{{env('APP_URL')}}/public/assets/img/pause.gif" class="d-none pause-recording-icon" />`);
                        }
                    })
                }
            });
        
            $(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');
                $('#edit-btn').addClass('d-none');
                $('#edit-btn').attr('data-content', '');
                jQuery('#update-url').val('');
            });
            
            $(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();
                }
                $('#edit-btn').removeClass('d-none');
                /*var soapContent = jQuery('.soap-summary-data').html().replace(/<[^>]*>/g, '');
                soapContent = soapContent.replace(/\n/g, '\n');*/
                $('#edit-btn').attr('data-content', jQuery('.soap-summary-data').attr('data-content'));
                jQuery('#update-url').val('soap-summary/edit');
            });
            
            $(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();
                }
                $('#edit-btn').removeClass('d-none');
                /*var prescriptionContent = jQuery('.prescription-data').html().replace(/<[^>]*>/g, '');
                prescriptionContent = prescriptionContent.replace(/\n/g, '\n');*/
                $('#edit-btn').attr('data-content', jQuery('.prescription-data').attr('data-content'));
                jQuery('#update-url').val('update/prescription');
            });
            
            $(document).on('click', '#edit-btn', function(){
                jQuery('#edit-appointmentId').val(jQuery(this).attr('data-appointmentId'));
                jQuery('.appointmentId').text(jQuery(this).attr('data-appointmentId'));
                easyMDE.value(jQuery(this).attr('data-content'));
                setTimeout(function() {
                    easyMDE.codemirror.refresh();
                    easyMDE.codemirror.focus();
                }, 250);
                jQuery('#editModal').modal('show');
            });
            
            jQuery('#editForm').on('submit', function(e) {
                e.preventDefault();
                var appointmentId = jQuery('#edit-appointmentId').val();
                var url = jQuery('#update-url').val();
                var content = easyMDE.value().trim();
                if (appointmentId == '' || url == '') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Administartion level parameter missing. Please try after some time.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                if (content == '') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Content required to update.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                // remove below 3 lines
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                var clsName = '';
                if (url.indexOf('prescription') !== -1) {
                    formData.append('prescription', content);
                    clsName = '.prescription-data';
                } else {
                    formData.append('soapSummary', content);
                    clsName = '.soap-summary-data';
                }
                formData.append('timezone', timeZone);
            
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/"+url,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
    
                jQuery('.edit-footer').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
            
                $.ajax(settings).done(response => {
                    jQuery('.appointment-footer').html(`
                        <button type="submit" class="btn btn-outline-primary">Save</button>
                        <button type="button" class="btn btn-outline-danger edit-modal-close" data-dismiss="modal">Close</button>
                    `);
                    Swal.fire({
                        position: "top-end",
                        title: response.message,
                        showConfirmButton: false,
                        timer: 1500
                    });
                    var htmlContent = md.render(content);
                    jQuery(clsName).html(htmlContent);
                    jQuery(clsName).attr('data-content', content);
                    if(clsName == '.soap-summary-data'){
                        jQuery('.generate-prescription').attr('data-content', content);
                    }
                    jQuery('#editModal').modal('hide');
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Swal.fire({
                        position: "top-end",
                        title: "Something went wrong. Please try again later.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    jQuery('.edit-footer').html(`
                        <button type="submit" class="btn btn-outline-primary">Save</button>
                        <button type="button" class="btn btn-outline-danger edit-modal-close" data-dismiss="modal">Close</button>
                    `);
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            /*Document by URL*/
            function getDocument(url) {
                const formData = new FormData();
                formData.append('fileName', url);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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 reportURL = $(this).attr('data-reporturl');
                getReport(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(reportURL) {
                const formData = new FormData();
                formData.append('fileName', reportURL);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/appointment/document",
                    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.audio_file+'">');
                    } else {
                        $('.reportFile-data').html('<iframe style="height: 90vh; width: 100%;" src="data:application/'+response.data.contentType+';base64,'+response.data.audio_file+'"></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("patientId", $('.user-item-left-selected').attr('data-patientId'));
                formData.append("encounterId", $('.user-item-left-selected').attr('data-encounterId'));
                // remove below 3 lines
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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-reporturl="${item.fileName}">${item.fileName}</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);
                });
            }
            
            $(document).on('change', '#fileInput', 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') }}");
                // remove below 4 lines
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('practitionerId', 'elpRiy0AYgjhdjAhTBJ3Aiw3');
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                formData.append('timezone', timeZone);
                // AJAX request to upload file
                $.ajax({
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/reports/upload",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    mimeType: "multipart/form-data",
                    processData: false,
                    success: function (response) {
                        if (typeof response === "string") {
                            response = JSON.parse(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" class="mb-0" data-reporturl="${item.fileName}">${item.fileName}</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);
                // remove below 4 lines
                formData.append('patientId', 'erXuFYUfucBZaryVksYEcMg3');
                formData.append('practitionerId', 'elpRiy0AYgjhdjAhTBJ3Aiw3');
                formData.append('appointmentId', 'eu7HwI-X.DdSMR7sAxi9Szyfyye3Hs3HdQQtMEC.KT7U3');
                formData.append('encounterId', 'eoIRZgvu9RhrwOzDlZkRbSg3');
                formData.append('soapSummary', soapNote);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/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-data').attr('data-content', prescriptionHTML);
                    $('#edit-btn').attr('data-content', prescriptionHTML);
                    jQuery('#update-url').val('update/prescription');
                    $('.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 Prescription.',
                        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 getPatientsList() {
                const formData = new FormData();
                formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('identifier', "MRN|203711");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/patients",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#appointmentForm').addClass('d-none');
                jQuery('#addAppointment').modal('show');
                jQuery('.patient-loading').html(`
                    <div class="loader-container mb-5">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                var createPatient = jQuery('#patient').val();
                $.ajax(settings).done(response => {
                    jQuery('.patient-loading').html('');
                    jQuery('#appointmentForm').removeClass('d-none');
                    $('#patientId').empty();
                    $('#patientId').append(`<option value="" disabled selected>Please Select</option>`);
                    if(response.data.length > 0){
                        $.each(response.data, function(index, patient) {
                            var selected = patient.patientId == createPatient;
                            $('#patientId').append(
                                $('<option>', {
                                    value: patient.patientId,
                                    text: patient.patientName,
                                    selected: selected
                                })
                            );
                        });
                    }
                    $("#appointmentDate").dxDateBox("instance").open();
                    var year = currentDate.getFullYear();
                    var month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
                    var day = currentDate.getDate().toString().padStart(2, '0');
                    getBookedSlots(`${year}-${month}-${day}`);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            jQuery(document).on('click', '#add-appointment', function(){
                datePicker.option("value", new Date());
                // datePicker.option("opened", true);
                getPatientsList();
            });
            
            function formateTimeSlot(dateString) {
                var date = new Date(dateString);
                var year = date.getFullYear();
                var month = String(date.getMonth() + 1).padStart(2, '0');
                var day = String(date.getDate()).padStart(2, '0');
                var hours = String(date.getHours()).padStart(2, '0');
                var minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:00`;
            }
            
            jQuery('#appointmentForm').on('submit', function(e) {
                e.preventDefault();
                var patientId = jQuery('#patient').val();
                var patientName = jQuery('#patientName').val();
                var slotDate = jQuery('#slotDate').val();
                var slotTime = $('input[name="timeSlot"]:checked').val();
                var appointmentId = $('input[name="timeSlot"]:checked').attr('data-appointmentId');
                if (patientId == '' || patientName == '') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Please select patient.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                if (slotDate == '' || slotTime == '') {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Please select appointment date and time.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('practitioner', "{{session('PractitionerId')}}");
                formData.append('practitionerName', "{{session('PractitionerName')}}");
                formData.append('patient', patientId);
                formData.append('patientName', patientName);
                formData.append('timeSlot', formateTimeSlot(slotTime * 1000));
                formData.append('visit', jQuery('#visit').val());
                formData.append('timezone', timeZone);
                // remove below 2 lines
                formData.append('practitioner', "e3MBXCOmcoLKl7ayLD51AWA3");
                formData.append('practitionerName', "Family Medicine Physician, MD");
            
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/addappointment",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
    
                jQuery('.appointment-footer').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
            
                $.ajax(settings).done(response => {
                    jQuery('.appointment-footer').html(`
                        <button type="submit" class="btn btn-outline-primary">Save</button>
                        <button type="button" class="btn btn-outline-danger appointment-add-modal-close" data-dismiss="modal">Close</button>
                    `);
                    Swal.fire({
                        position: "top-end",
                        title: "Appointment scheduled successfully.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    window.location.reload();
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Swal.fire({
                        position: "top-end",
                        title: "Something went wrong. Please try again later.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    jQuery('.appointment-footer').html(`
                        <button type="submit" class="btn btn-outline-primary">Save</button>
                        <button type="button" class="btn btn-outline-danger appointment-add-modal-close" data-dismiss="modal">Close</button>
                    `);
                    console.error("Error:", textStatus, errorThrown);
                });
            });
            
            jQuery('.appointment-add-modal-close').on('click', function() {
                $('#appointmentForm').trigger('reset');
            });
            
            jQuery('.edit-modal-close').on('click', function() {
                $('#editForm').trigger('reset');
            });
            
            /* Help Code */
            jQuery(document).on('click', '#get-help', function(){
                const settings = {
                    url: "{{env('API_URL')}}help",
                    method: "GET",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false
                };
                jQuery('#helpModal').modal('show');
                jQuery('.help-body').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    var accordionHTML = '';
                    response.data.forEach(function(item, index) {
                        accordionHTML += `
                        <div class="card">
                            <div class="card-header" id="heading${index}">
                                <h5 class="mb-0">
                                    <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapse${index}" aria-expanded="${index === 0 ? 'true' : 'false'}" aria-controls="collapse${index}">
                                        ${item.question}
                                    </button>
                                </h5>
                            </div>
                            <div id="collapse${index}" class="collapse ${index === 0 ? 'show' : ''}" aria-labelledby="heading${index}" data-parent=".help-body">
                                <div class="card-body">
                                    ${item.answer}
                                </div>
                            </div>
                        </div>`;
                    });
                    jQuery('.help-body').html(accordionHTML);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.help-body').html('<p>Error loading help data. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            });
        });
    </script>
@endpush