@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" placeholder="Search Patient" aria-label="Search Patient">
                    <div class="input-group-append">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <h3 class="font-weight-light mt-3 mb-0">Scheduled Visits</h3>
                <div class="clicked"></div>
                <div class="user-list user-list-left"></div>
            </div>
            <div class="col-sm-6">
                <div class="center-box">
                    <div class="mt-5 pt-4">
                        <h2 class="primary-color">Hello, {{session('PractitionerName')}}</h2>
                        <h5 class="secondary-color">Select a scheduled visit to get started!</h5>
                        <div class="d-flex align-items-center mt-5">
                            <i class="material-icons-outlined glowing-icon" style="font-size:44px" aria-label="Info">wb_incandescent</i>
                            <p class="pl-2 mb-0">Historical medical records will be listed on the right-side in chronological order clearly showing the visits that have reports attached.</p>
                        </div>
                    </div>
                </div>
                <div class="center-box-selected d-none">
                    <div class="user-list mt-0">
                        <div class="user-item border-0 pb-0 pt-1 pl-0">
                            <h4 class="secondary-color patientName mb-0"></h4>
                            <small class="patientId"></small>
                        </div>
                    </div>
                    <h6 class="secondary-color appointmentId pt-4"></h6>
                    <div class="audio-text-box" id="audio-text-box">
                        <audio id="audio" style="display:none" src="" controls controlsList="nodownload noplaybackrate"></audio>
                        <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">
                        <span class="app-title">
                            <h6 class="appointment-id d-none primary-color">Appointment ID: <span class="model-appointmentid"></span></h6>
                            <div class="header-btn">
                                <i class="material-icons-outlined d-none mr-3" id="download-btn">download</i>
                                <i class="material-icons edit-icon d-none mr-3" id="edit-btn" data-appointmentid="" data-content="">edit</i>
                                <i class="material-icons-outlined modal-close" id="close-btn" data-dismiss="modal">close</i>
                            </div>
                        </span>
                        <div class="data-tab loader-div"></div>
                        <div class="data-tab transcription-data d-none"></div>
                        <div class="data-tab soap-summary-data d-none" data-content=""></div>
                        <div class="data-tab prescription-data d-none" data-content=""></div>
                        <div class="data-tab additionalnote_1-data d-none" data-content=""></div>
                        <div class="data-tab PROCEDURENOTE-data d-none" data-content=""></div>
                        <div class="data-tab INVENTORYNOTES-data d-none" data-content=""></div>
                        <div class="data-tab PROGRESSNOTE-data d-none" data-content=""></div>
                        <div class="data-tab DISCHARGENOTE-data d-none" data-content=""></div>
                        <div class="data-tab HISTORYPHYSICAL-data d-none" data-content=""></div>
                        <div class="data-tab PERIODONTALCHARTINGNOTES-data d-none" data-content=""></div>
                    </div>
                    <div class="modal-footer justify-content-center">
                        <div class="extra-btn pb-2 d-none">
                            <button type="button" id="saveandsendtoehr" class="btn btn-outline-primary mr-3" data-display="transcription">Save and Send to EHR</button>
                            <button type="button" id="saveInventory" class="btn btn-outline-primary d-none">Save Inventory</button>
                        </div>
                        <button type="button" class="btn btn-outline-primary primary-bg-color active-button d-none transcription" data-display="transcription">Transcription</button>
                        <button type="button" class="btn btn-outline-primary d-none active-button soap-summary" data-display="soap-summary">SOAP Summary</button>
                        @if(session()->has('additionalnote'))
                            @foreach(session()->get('additionalnote') as $value => $title)
                                <button type="button" class="btn btn-outline-primary d-none active-button {{$value}}" data-display="{{$value}}">{{$title}}</button>
                            @endforeach
                        @endif
                        <button type="button" class="btn btn-outline-primary d-none active-button PROCEDURENOTE" data-display="PROCEDURENOTE">Procedure Notes</button>
                        <button type="button" class="btn btn-outline-primary d-none active-button INVENTORYNOTES" data-display="INVENTORYNOTES">Inventory Notes</button>
                        <button type="button" class="btn btn-outline-primary d-none active-button PROGRESSNOTE" data-display="PROGRESSNOTE">Progress Notes</button>
                        <button type="button" class="btn btn-outline-primary d-none active-button DISCHARGENOTE" data-display="DISCHARGENOTE">Discharge Summary</button>
                        <button type="button" class="btn btn-outline-primary d-none active-button HISTORYPHYSICAL" data-display="HISTORYPHYSICAL">History & Physical</button>
                        <button type="button" class="btn btn-outline-primary d-none active-button PERIODONTALCHARTINGNOTES" data-display="PERIODONTALCHARTINGNOTES">Periodontal Charting Notes</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">
                        <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 and Send to EHR</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>
                    <span class="d-none" id="pdfnotetype"></span>
                    <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 selected>Please Select</option>
                                            @if(session()->has('additionalnote'))
                                                @foreach(session()->get('additionalnote') as $value => $title)
                                                    <option value="{{$value}}">{{$title}}</option>
                                                @endforeach
                                            @endif
                                            <option value="PROCEDURENOTE">Procedure Notes</option>
                                            <option value="INVENTORYNOTES">Inventory Notes</option>
                                            <option value="SOAPNOTE">SOAP Summary</option>
                                            <option value="PROGRESSNOTE">Progress Notes</option>
                                            <option value="DISCHARGENOTE">Discharge Summary</option>
                                            <option value="HISTORY-PHYSICAL">History & Physical</option>
                                            <option value="PERIODONTALCHARTINGNOTES">Periodontal Charting Notes</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">Generate</button>
                            <button type="button" class="btn btn-outline-danger note-modal-close" data-dismiss="modal">Close</button>
                        </div>
                    </form>
                </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 generateFullDaySlots(excludedSlots, date) {
                var slotsHtml = '<div class="row col-12">';
                var startOfDay = new Date(date);
                startOfDay.setHours(0, 0, 0, 0);
                var endOfDay = new Date(date);
                endOfDay.setHours(23, 30, 0, 0);
            
                var now = new Date();
                var currentSlotStart = new Date(date);
                currentSlotStart.setHours(now.getHours(), Math.floor(now.getMinutes() / 30) * 30, 0, 0); // Round down to the nearest 30 minutes

                for (var time = startOfDay.getTime(); time <= endOfDay.getTime(); time += 30 * 60 * 1000) {
                    var startTime = new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                    var endTime = new Date(time + 30 * 60 * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                    // Exclude past slots except the current slot
                    var isExcluded = ($.inArray(time, excludedSlots) !== -1 || time < now.getTime()) && time !== currentSlotStart.getTime();
                    if (isExcluded) {
                        slotsHtml += `<div class="mr-10">
                            <input type="radio" name="timeSlot" id="${startTime}" value="${startTime}" disabled>
                            <label class="custom-radio disabled ${startTime.replace(/[: ]/g, "-")}" for="${startTime}">${startTime} - ${endTime}</label>
                        </div>`;
                    } else {
                        slotsHtml += `<div class="mr-10">
                            <input type="radio" name="timeSlot" id="${startTime}" value="${startTime}" required>
                            <label class="custom-radio ${startTime.replace(/[: ]/g, "-")}" for="${startTime}">${startTime} - ${endTime}</label>
                        </div>`;
                    }
                }
                slotsHtml += `</div>`;
                return slotsHtml;
            }
            
            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')}}/booked/slots",
                    method: "POST",
                    timeout: 0,
                    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 excludedSlots = response.data.map(function(slot) {return slot.startTime;});
                        $('#time').html(generateFullDaySlots(excludedSlots, date));
                        // var targetOffset = $(".08-00-AM").offset().top;
                        // var containerOffset = $("#time").offset().top;
                        // $("#time").animate({
                        //     scrollTop: targetOffset - containerOffset
                        // }, 1000);
                    }
                }).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);
            });
            
            var appointmentsData = [];
            function displayAppointments(scheduledAppointments) {
                const userList = $('.user-list-left');
                userList.empty();
                const currentTime = new Date();
                if(scheduledAppointments.length > 0) {
                    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 appointmentDate = itemTimeSlot.toLocaleDateString("en-US", {month: "2-digit", day: "2-digit", year: "numeric"});
                        // const appointmentTime = new Date(item.timeSlot).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                        const appointmentId = item.appointmentId;
                        const encounterId = item.encounterId;
                        const patientId = item.patientURL;
                        const careStackPatientId = item.careStackPatientId;
                        const appointmentType = item.appointmentType;
                        const patientName = `${item.patientPrefix} ${item.patient}`;
                        
                        const userItem = `
                            <div class="user-item-left" data-daydiff="${dayDiff}" data-appointmentId="${appointmentId}" data-encounterId="${encounterId}" data-patientId="${patientId}" data-careStackPatientId="${careStackPatientId}" data-appointmentDate="${appointmentDate}" data-patientName="${patientName}">
                                <h5>${patientName}</h5>
                                <small>${appointmentTime} | ${appointmentType}</small>
                            </div>
                        `;
                        userList.append(userItem);
                    });
                } else {
                    userList.append('<p>You don\'t have any scheduled appointments.</p>');
                }
            }
            
            function getAppointments(){
                const formData = new FormData();
                formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/appointments",
                    method: "POST",
                    timeout: 0,
                    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;
                    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();
            
            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("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,
                    "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) {
                            jQuery('.old-soap').remove();
                            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();
                             if($('.user-list-left .user-item-left-selected').attr('data-encounterid') == "" || $('.user-list-left .user-item-left-selected').attr('data-encounterid') == "null"){
                                $.ajax({
                                    url: "{{env('API_URL')}}{{session('currentEHR')}}/encounter/create",
                                    type: 'POST',
                                    data: {
                                        _token: '{{ csrf_token() }}',
                                        appointmentId: $('.user-list-left .user-item-left-selected').attr('data-appointmentid'),
                                        patientId: $('.user-list-left .user-item-left-selected').attr('data-patientId'),
                                        practitionerId: "{{ session('PractitionerId') }}",
                                        customer: "{{ session('customer') }}"
                                    },
                                    success: function (response) {
                                        $('.user-list-left .user-item-left-selected').attr('data-encounterid', response.data.encounterId);
                                    },
                                    error: function (xhr) {
                                        Swal.fire({
                                            position: "top-end",
                                            text: xhr.responseText.message,
                                            showConfirmButton: false,
                                            timer: 1000
                                        });
                                    }
                                });
                            }
                        }
                    });
                }else{
                    jQuery('.old-soap').remove();
                    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){
                const formData = new FormData();
                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,
                    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){
                        var cnt = 1;
                        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.reportURL}" 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{
                        jQuery('#reportData').html('Reports has not been uploaded yet.');
                        reportList.append('<p class="pt-2">Reports has not been uploaded yet.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#reports-list').html('<p>Error loading reports. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            var patientHistoryData = [];
            function displayHistoryList(historyData, old) {
                const historyList = $('#history-list');
                historyList.empty();
                if(historyData.length > 0){
                    var cnt = 1;
                    var noHistory = false;
                    jQuery('#hisotryData').html('');
                    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>
                    `);
                    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 && old) {
                            const soapSummaryData = item.comment;
                            let [date, ...paragraphs] = soapSummaryData.split(":");
                            let summaryData = paragraphs.join(":");
                            const soapSummary = isHTML(summaryData) ? summaryData : md.render(summaryData);
                            jQuery('.audio-text-box').append(`<div class="pl-3 pt-2 old-soap"><h5 class="primary-color">${date}</h5>${soapSummary}</div>`);
                            noHistory = true;
                        }
                        if(item.comment != '' && cnt < 10 && formattedDate != item.date){
                            var checked = formattedDate == item.date ? 'checked' : '';
                            var 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 && old){
                        jQuery('.audio-text-box').append('<p class="old-soap pl-3 pt-2">Patient history not found.</p>'); 
                    }
                    $('.appointment-details').hover(
                        function() { $(this).parent().addClass('appointment-right'); },
                        function() { $(this).parent().removeClass('appointment-right'); }
                    );
                }else{
                    jQuery('.audio-text-box').append('<p class="old-soap pl-3 pt-2">Patient history not found.</p>');
                    historyList.append('<p class="pt-2">Appointment history not available.</p>');
                }
            }
            
            function getPatientHistory(patientId, old = true){
                const practitionerId = "{{ session('PractitionerId') }}";
                const formData = new FormData();
                formData.append('timezone', timeZone);
                const settings = {
                    url: `{{env('API_URL')}}{{session('currentEHR')}}/patient/history/${practitionerId}/${patientId}`,
                    method: "POST",
                    timeout: 0,
                    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, old);
                    $('.clicked').css('height', '0');
                }).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);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/appointment/history",
                    method: "POST",
                    timeout: 0,
                    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-appointmentId="${appointmentId}" 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);
                });
            }
            
            var inventoryData = [];
            function appointmentModel(response, clsName = 'transcription') {
                const transacription = response.data.description;
                const appointmentId = response.data.appointmentId;
                $('.model-appointmentid').text(appointmentId);
                $('.edit-icon').attr('data-appointmentid', appointmentId);
                jQuery('.transcription-data').html(transacription.length > 0 ? "</p>"+transacription+"</p>" : '<p>Transcription not available.</p>');
                $('.transcription').removeClass('d-none')
                if(response.data.contentType != undefined && response.data.contentType != "" && response.data.audio_file != undefined && response.data.audio_file != ""){
                    jQuery('.transcription-data').append(`<audio id="modal-audio" src="${'data:audio/mp3;base64,'+response.data.audio_file}" controls controlsList="nodownload noplaybackrate"></audio>`);
                }
                if(response.data.comment != undefined && response.data.comment != ""){
                    const soapSummaryData = response.data.comment;
                    const soapSummary = isHTML(soapSummaryData) ? soapSummaryData : md.render(soapSummaryData);
                    jQuery('.soap-summary-data').attr('data-content', encodeURIComponent(response.data.comment));
                    jQuery('.soap-summary-data').html(soapSummary.length > 0 ? soapSummary : '<p>soap summary not available.</p>');
                    jQuery('.soap-summary-data').addClass('d-none');
                    jQuery('.soap-summary').removeClass('d-none');
                }
                if(response.data.patientInstruction != undefined && response.data.patientInstruction != ""){
                    const prescription = isHTML(response.data.patientInstruction) ? response.data.patientInstruction : md.render(response.data.patientInstruction);
                    jQuery('.patientInstruction-data').attr('data-content', encodeURIComponent(response.data.patientInstruction));
                    jQuery('.patientInstruction-data').html(prescription.length > 0 ? prescription : '<p>prescription not available.</p>');
                    jQuery('.patientInstruction-data').addClass('d-none');
                    jQuery('.prescription').removeClass('d-none');
                }
                if(response.data.additionalnote_1 != undefined && response.data.additionalnote_1 != ""){
                    const additionalnote_1 = isHTML(response.data.additionalnote_1) ? response.data.additionalnote_1 : md.render(response.data.additionalnote_1);
                    jQuery('.additionalnote_1-data').attr('data-content', encodeURIComponent(response.data.additionalnote_1));
                    jQuery('.additionalnote_1-data').html(additionalnote_1.length > 0 ? additionalnote_1 : '<p>additional note not available.</p>');
                    jQuery('.additionalnote_1-data').addClass('d-none');
                    jQuery('.additionalnote_1').removeClass('d-none');
                }
                if(response.data.PROCEDURENOTE != undefined && response.data.PROCEDURENOTE != ""){
                    const PROCEDURENOTE = isHTML(response.data.PROCEDURENOTE) ? response.data.PROCEDURENOTE : md.render(response.data.PROCEDURENOTE);
                    jQuery('.PROCEDURENOTE-data').attr('data-content', encodeURIComponent(response.data.PROCEDURENOTE));
                    jQuery('.PROCEDURENOTE-data').html(PROCEDURENOTE.length > 0 ? PROCEDURENOTE : '<p>procedure note not available.</p>');
                    jQuery('.PROCEDURENOTE-data').addClass('d-none');
                    jQuery('.PROCEDURENOTE').removeClass('d-none');
                }
                if(response.data.INVENTORYNOTES != undefined && response.data.INVENTORYNOTES != ""){
                    const INVENTORYNOTES = isHTML(response.data.INVENTORYNOTES) ? response.data.INVENTORYNOTES : md.render(response.data.INVENTORYNOTES);
                    jQuery('.INVENTORYNOTES-data').attr('data-content', encodeURIComponent(response.data.INVENTORYNOTES));
                    jQuery('.INVENTORYNOTES-data').html(INVENTORYNOTES.length > 0 ? INVENTORYNOTES : '<p>inventory note not available.</p>');
                    var cleanedJson = response.data.INVENTORYNOTES.replace(/^```json/, '').replace(/```$/, '').trim();
                    if (isValidJSON(cleanedJson)) {
                        var parsedNote = JSON.parse(cleanedJson);
                        inventoryData = parsedNote.inventory;
                    }
                    jQuery('.INVENTORYNOTES-data').addClass('d-none');
                    jQuery('.INVENTORYNOTES').removeClass('d-none');
                }
                if(response.data.PROGRESSNOTE != undefined && response.data.PROGRESSNOTE != ""){
                    const PROGRESSNOTE = isHTML(response.data.PROGRESSNOTE) ? response.data.PROGRESSNOTE : md.render(response.data.PROGRESSNOTE);
                    jQuery('.PROGRESSNOTE-data').attr('data-content', encodeURIComponent(response.data.PROGRESSNOTE));
                    jQuery('.PROGRESSNOTE-data').html(PROGRESSNOTE.length > 0 ? PROGRESSNOTE : '<p>progress note not available.</p>');
                    jQuery('.PROGRESSNOTE-data').addClass('d-none');
                    jQuery('.PROGRESSNOTE').removeClass('d-none');
                }
                if(response.data.DISCHARGENOTE != undefined && response.data.DISCHARGENOTE != ""){
                    const DISCHARGENOTE = isHTML(response.data.DISCHARGENOTE) ? response.data.DISCHARGENOTE : md.render(response.data.DISCHARGENOTE);
                    jQuery('.DISCHARGENOTE-data').attr('data-content', encodeURIComponent(response.data.DISCHARGENOTE));
                    jQuery('.DISCHARGENOTE-data').html(DISCHARGENOTE.length > 0 ? DISCHARGENOTE : '<p>discharge note not available.</p>');
                    jQuery('.DISCHARGENOTE-data').addClass('d-none');
                    jQuery('.DISCHARGENOTE').removeClass('d-none');
                }
                if(response.data.HISTORYPHYSICAL != undefined && response.data.HISTORYPHYSICAL != ""){
                    const HISTORYPHYSICAL = isHTML(response.data.HISTORYPHYSICAL) ? response.data.HISTORYPHYSICAL : md.render(response.data.HISTORYPHYSICAL);
                    jQuery('.HISTORYPHYSICAL-data').attr('data-content', encodeURIComponent(response.data.HISTORYPHYSICAL));
                    jQuery('.HISTORYPHYSICAL-data').html(HISTORYPHYSICAL.length > 0 ? HISTORYPHYSICAL : '<p>history & physical note not available.</p>');
                    jQuery('.HISTORYPHYSICAL-data').addClass('d-none');
                    jQuery('.HISTORYPHYSICAL').removeClass('d-none');
                }
                if(response.data.PERIODONTALCHARTINGNOTES != undefined && response.data.PERIODONTALCHARTINGNOTES != ""){
                    const PERIODONTALCHARTINGNOTES = isHTML(response.data.PERIODONTALCHARTINGNOTES) ? response.data.PERIODONTALCHARTINGNOTES : md.render(response.data.PERIODONTALCHARTINGNOTES);
                    jQuery('.PERIODONTALCHARTINGNOTES-data').attr('data-content', encodeURIComponent(response.data.PERIODONTALCHARTINGNOTES));
                    jQuery('.PERIODONTALCHARTINGNOTES-data').html(PERIODONTALCHARTINGNOTES.length > 0 ? PERIODONTALCHARTINGNOTES : '<p>periodontal charting note not available.</p>');
                    jQuery('.PERIODONTALCHARTINGNOTES-data').addClass('d-none');
                    jQuery('.PERIODONTALCHARTINGNOTES').removeClass('d-none');
                }
                $('.loader-div').addClass('d-none').html('');
                $('.appointment-id').removeClass('d-none');
                $('#download-btn').removeClass('d-none');
                $('.'+clsName).removeClass('d-none').trigger('click');
                // if(response.data.patientInstruction.length == 0) {
                //     $('.generate-prescription').attr('soapNote', encodeURIComponent(response.data.comment));
                //     $('.generate-prescription').attr('appointmentId', response.data.appointmentId);
                //     $('.generate-prescription').removeClass('d-none');
                //     $('.prescription').addClass('d-none');
                // }else{
                //     $('.prescription').removeClass('d-none');
                // }
            }
            
            function appointmentDetails(appointmentId){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('timezone', timeZone);
                formData.append('date', '2024-05-17');
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/appointment/details",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $('.active-button').removeClass('primary-bg-color');
                $('.data-tab').html('').addClass('d-none');
                $('.loader-div').removeClass('d-none');
                jQuery('.loader-div').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('#appointmentDetailModal').modal('show');
                $.ajax(settings).done(response => {
                    appointmentModel(response);
                    return false;
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Swal.fire({
                        position: "top-end",
                        text: "Error loading appointment versions. Please try again later.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    // $('.prescription').removeClass('d-none');
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            const notesValue = ["SOAPNOTE","DISCHARGENOTE","HISTORY-PHYSICAL"];
            function generateTranscription(transcription) {
                jQuery('#saveInventory').addClass('d-none');
                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'));
                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,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $('#notes').modal('hide');
                $('.active-button').removeClass('primary-bg-color');
                $('.data-tab').html('').addClass('d-none');
                $('.loader-div').removeClass('d-none');
                jQuery('.loader-div').html(`
                    <p class="loading-p">Generating SOAP summary...</p>
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('#appointmentDetailModal').modal('show');
                if(notesValue.includes(generateType)){
                    $.ajax(settings).done(response => {
                        if(generateType == 'SOAPNOTE'){
                            appointmentModel(response, 'soap-summary');
                            getPatientHistory($('.user-list-left .user-item-left-selected').attr('data-patientid'), false);
                            return false;
                        } else {
                            let soapSummaryData = '';
                            if(notesValue.includes(generateType)){
                                soapSummaryData = response.data.comment;
                                jQuery('.loader-div').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) => {
                        Swal.fire({
                            position: "top-end",
                            text: "Error while generating summary. Please try again later.",
                            showConfirmButton: false,
                            timer: 1000
                        });
                        $('#appointmentDetailModal').modal('hide');
                        console.error("Error:", textStatus, errorThrown);
                    });
                } else {
                    jQuery('.loader-div').html(`
                        <p class="loading-p">Generating ${selectedText}...</p>
                        <div class="loader-container">
                            <div class="loader" id="loader"></div>
                        </div>
                    `);
                    generateNote(transcription);
                }
            }

            function isValidJSON(str) {
                try {
                    JSON.parse(str);
                    return true;
                } catch (e) {
                    return false;
                }
            }

            function generateNote(soapNote = '') {
                jQuery('#saveInventory').addClass('d-none');
                var generateType = jQuery('#generateType').val();
                jQuery('#pdfnotetype').text(generateType);
                var selectedText = $('#generateType option:selected').text();
                let soapHistory = '';
                let reportHistory = '';
                if(notesValue.includes(generateType)){
                    soapHistory = $('input[name="soapHistory[]"]:checked')
                        .map(function() {
                            return decodeURIComponent($(this).val());
                        })
                        .get()
                        .filter(function(value) {
                            return !value.includes(formattedDate);
                        })
                        .join('\n\n');
                    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'));
                if(notesValue.includes(generateType)){
                    formData.append('soapSummaries', formattedDate+':\n\n'+soapNote+'\n\n'+soapHistory);
                    formData.append('reportSummaries', reportHistory);
                }else{
                    formData.append('soapSummaries', soapNote);
                }
                formData.append('noteType', generateType);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/generate/note",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $('#notesForm').trigger('reset');
                $('#hisotry').addClass('d-none');
                $.ajax(settings).done(response => {
                    appointmentModel(response, generateType.replace(/-/g, ""));
                    getPatientHistory($('.user-list-left .user-item-left-selected').attr('data-patientid'), false);
                    return false;
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Swal.fire({
                        position: "top-end",
                        text: "Error while generating note. Please try again later.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $(document).on('click', '.generate-transcription', function() {
                var transcription = '';
                $('.conversation .text').each(function() {
                    transcription += transcription.length > 0 ? '\n'+$(this).text() : $(this).text();
                });
                if(transcription == '' || transcription.length == 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Conversation data is required to generate SOAP Summary.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                $('#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');
                $('#hisotry').addClass('d-none');
            });
        
            $(document).on('click', '.user-item-left', function(){
                $('.clicked').css('height', '100%');
                $('.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'));
            });
        
            $('.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" />`);
                        }
                    })
                }
            });
            
            function appointmentVersionDetails(appointmentId, versionId){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('versionId', versionId);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/appointment/version",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $('.active-button').removeClass('primary-bg-color');
                $('.transcription').addClass('primary-bg-color');
                $('.data-tab').html('').addClass('d-none');
                $('.transcription-data').removeClass('d-none');
                jQuery('.transcription-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('#appointmentDetailModal').modal('show');
                $.ajax(settings).done(response => {
                    appointmentModel(response);
                    return false;
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Swal.fire({
                        position: "top-end",
                        text: "Error loading appointment versions. Please try again later.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    // $('.prescription').removeClass('d-none');
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }

            $(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', '.appointment-version-details', function(){
                $('.appointment-version-details').removeClass('version-selected');
                $('.appointment-details').parent().removeClass('version-selected');
                $(this).addClass('version-selected');
                var appointmentId = $(this).attr('data-appointmentid');
                var versionId = $(this).attr('data-versionid');
                appointmentVersionDetails(appointmentId, versionId);
            });
            
            $(document).on('click', '.modal-close', function() {
                jQuery('.appointment-details').parent().removeClass('version-selected');
                jQuery('.appointment-version-details').removeClass('version-selected');
                jQuery('.active-button').removeClass('primary-bg-color').addClass('d-none');
                $('.appointment-id').addClass('d-none');
                $('#download-btn').addClass('d-none');
                $('#edit-btn').addClass('d-none');
                $('.extra-btn').addClass('d-none');
                $('#saveInventory').addClass('d-none');
                jQuery('.data-tab').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', '.active-button', function(){
                const contentDiv = $(this).attr('data-display');
                $('.active-button').removeClass('primary-bg-color');
                $(this).addClass('primary-bg-color');
                $('.data-tab').addClass('d-none');
                $('.'+contentDiv+'-data').removeClass('d-none');
                $('#edit-btn').addClass('d-none').attr('data-content', '');
                $('.extra-btn, #saveInventory, #edit-btn').addClass('d-none');
                var audioElement = $('#modal-audio')[0];
                if (audioElement && typeof audioElement.pause === 'function' && !audioElement.paused) {
                    audioElement.pause();
                }
                var detailPopup = true;
                if ($("#history-list").find(".version-selected").length > 0) {
                    detailPopup = false;
                }
                if(detailPopup){
                    if(contentDiv == 'INVENTORYNOTES'){
                        $('#saveInventory').removeClass('d-none');
                    }
                    if(contentDiv != 'transcription'){
                        $('.extra-btn').removeClass('d-none');
                        $('#edit-btn').removeClass('d-none');
                        $('#edit-btn').attr('data-content', jQuery('.'+contentDiv+'-data').attr('data-content'));
                    }
                }
            });
            
            $(document).on('click', '#edit-btn', function(){
                jQuery('.appointmentId').text(jQuery(this).attr('data-appointmentId'));
                easyMDE.value(decodeURIComponent(jQuery(this).attr('data-content')));
                setTimeout(function() {
                    easyMDE.codemirror.refresh(); // Ensure the editor is fully rendered
                    easyMDE.codemirror.focus();   // Optionally focus the editor
                }, 250);
                jQuery('#editModal').modal('show');
            });
            
            function saveAndSendToEHR(content){
                const appointmentId = $('.user-item-left-selected').attr('data-appointmentId');
                const patientId = $('.user-item-left-selected').attr('data-careStackPatientId');
                const appointmentDate = $('.user-item-left-selected').attr('data-appointmentDate');
                const drName = "{{session('PractitionerName')}}";
                var clsName = jQuery("#appointmentDetailModal .primary-bg-color").attr('data-display');
                // Update content to respective area
                var htmlContent = md.render(content);
                jQuery('.'+clsName+'-data').html(htmlContent);
                jQuery('.'+clsName+'-data').attr('data-content', encodeURIComponent(content));
                $('#edit-btn').attr('data-content', encodeURIComponent(content));
                Swal.fire({
                    title: "Confirm",
                    text: "If a follow up date is scheduled ?",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#34B6B3",
                    cancelButtonColor: "#d33",
                    confirmButtonText: "Proceed",
                    cancelButtonText: "Cancel"
                }).then((result) => {
                    if (result.isConfirmed) {
                        jQuery('.loading').removeClass('d-none');
                        // Prepare for API call
                        const formData = new FormData();
                        formData.append('appointmentId', appointmentId);
                        formData.append('patientId', patientId);
                        formData.append('appointmentDate', appointmentDate);
                        formData.append('drName', drName);
                        formData.append('timezone', timeZone);
                        var url = '';
                        var fieldName = '';
                        if (clsName === 'soap-summary') {
                            url = 'soap-summary/edit';
                            fieldName = 'soapSummary';
                        } else if (clsName === 'prescription') {
                            url = 'update/prescription';
                            fieldName = 'prescription';
                        } else {
                            url = 'update/note';
                            fieldName = 'note';
                            formData.append('noteType', clsName);
                        }
                        formData.append(fieldName, content);
                        console.log(appointmentId, patientId, appointmentDate, drName, clsName, fieldName, url);
                        if (appointmentId == '' || appointmentDate == '' || drName == '' || clsName == '' || fieldName == '' || url == '') {
                            Swal.fire({
                                icon: 'error',
                                title: 'Validation Failed!',
                                text: 'Administartion level parameter missing. Please do refresh and try after some time.',
                                confirmButtonColor: '#34B6B3',
                                customClass: {
                                    title: 'my-custom-title',
                                    content: 'my-custom-content'
                                }
                            });
                            jQuery('.loading').addClass('d-none');
                            return false;
                        }
                        const settings = {
                            url: "{{env('API_URL')}}{{session('currentEHR')}}/"+url,
                            method: "POST",
                            timeout: 0,
                            processData: false,
                            contentType: false,
                            data: formData
                        };
                        $.ajax(settings).done(response => {
                            jQuery('.loading').addClass('d-none');
                            Swal.fire({
                                position: "top-end",
                                text: response.message,
                                showConfirmButton: false,
                                timer: 1500
                            });
                            /*var htmlContent = md.render(content);
                            jQuery('.'+clsName+'-data').html(htmlContent);
                            jQuery('.'+clsName+'-data').attr('data-content', encodeURIComponent(content));
                            if(clsName == '.soap-summary-data'){
                                jQuery('.generate-prescription').attr('data-content', encodeURIComponent(content));
                                jQuery('.generate-prescription').attr('soapNote', encodeURIComponent(content));
                            }
                            $('#edit-btn').attr('data-content', encodeURIComponent(content));*/
                        }).fail((jqXHR, textStatus, errorThrown) => {
                            jQuery('.loading').addClass('d-none');
                            Swal.fire({
                                position: "top-end",
                                text: "Something went wrong. Please try again later.",
                                showConfirmButton: false,
                                timer: 1000
                            });
                            console.error("Error:", textStatus, errorThrown);
                        });
                    }
                });
            }
            
            jQuery(document).on('click', '#saveandsendtoehr', function(e) {
                var clsName = jQuery("#appointmentDetailModal .primary-bg-color").attr('data-display');
                var contentData = jQuery('.'+clsName+'-data').attr('data-content');
                var content = decodeURIComponent(contentData).trim();
                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;
                }
                saveAndSendToEHR(content);
            });
            
            jQuery('#editForm').on('submit', function(e) {
                e.preventDefault();
                var content = easyMDE.value().trim();
                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;
                }
                jQuery('#editModal').modal('hide');
                saveAndSendToEHR(content);
            });
            
            /*Document by URL*/
            function getDocument(url) {
                const formData = new FormData();
                formData.append('documentId', url);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/appointment/document",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    $('#modal-audio').attr('src', 'data:audio/mp3;base64,'+response.data.audio_file);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    $('#modal-audio').attr('src', '');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            /* Report Details */
            $(document).on('click', '.report-details', function(){
                $('.report-details').removeClass('report-selected');
                $(this).addClass('report-selected');
                $('.report-summary').addClass('primary-bg-color');
                $('.reports').removeClass('primary-bg-color');
                const reportName = $(this).attr('data-reportName');
                const reportId = $(this).attr('data-reportid');
                const reportURL = $(this).attr('data-reporturl');
                const conclusionData = $(this).attr('data-conclusion');
                const conclusion = isHTML(conclusionData) ? conclusionData : '<p>'+md.render(conclusionData)+'</p>';
                var html = '';
                html += `<div class="reportlist-data d-none">
                            <ul>
                                <li id="report-file" data-reportid="${reportId}" data-reporturl="${reportURL}">${reportName.length > 0 ? reportName : 'Reports are not available.'}</li>
                            </ul>
                        </div>`;
                html += `<div class="report-summary-data"></div>`;
                $('.report-modal').html(html);
                $('.report-summary-data').html(conclusion);
                $('#reportModal').modal('show');
            });
            
            $(document).on('click', '.reports', function(){
                $(this).addClass('primary-bg-color');
                $('.report-summary').removeClass('primary-bg-color');
                $('.reportlist-data').removeClass('d-none');
                $('.report-summary-data').addClass('d-none');
            });

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

            $(document).on('click', '#report-file', function(){
                const reportId = $(this).attr('data-reportid');
                const reportURL = $(this).attr('data-reporturl');
                getReport(reportId, reportURL);
                $('.reports').removeClass('primary-bg-color');
                $('.reportlist-data').addClass('d-none');
                $('.report-summary-data').removeClass('d-none');
            });
            
            $(document).on('click', '.report-modal-close', function(){
                $('.reports').addClass('primary-bg-color');
                $('.reportFile-data').html('');
                $('.reportlist-data').removeClass('d-none');
                $('.report-summary-data').addClass('d-none');
                jQuery('#reportFile').modal('hide');
            });
            
            /*Report by URL*/
            function getReport(reportId, reportURL) {
                const formData = new FormData();
                formData.append('reportId', reportId);
                formData.append('reportURL', reportURL);
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/report/details",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('#reportFile').modal('show');
                jQuery('.reportFile-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $.ajax(settings).done(response => {
                    if(response.data.contentType.includes('image')){
                        $('.reportFile-data').html('<img style="height: 90vh; width: 100%;" src="data:'+response.data.contentType+';base64,'+response.data.data+'">');
                    } else {
                        $('.reportFile-data').html('<iframe style="height: 90vh; width: 100%;" src="data:application/'+response.data.contentType+';base64,'+response.data.data+'"></iframe>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    $('.reportFile-data').html('');
                    jQuery('#reportFile').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $(document).on('click', '.report-upload', function(){
                $('.reportUploadList-data').html('');
                jQuery('#reportUpload').modal('show');
                getAppointmentReports();
            });
            
            function getAppointmentReports(){
                const formData = new FormData();
                formData.append("appointmentId", $('.user-item-left-selected').attr('data-appointmentId'));
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/reports",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('.reportUploadList-data').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const reportList = $('.reportUploadList-data');
                    reportList.empty();
                    if(response.data.length > 0){
                        response.data.forEach(item => {
                            const reportItem = `<div class="right-bottom-border uploadList">
                                <h5 id="report-file" class="mb-0" data-reportid="${item.reportId}" data-reporturl="${item.reportURL}">${item.title}</h5>
                            </div>`;
                            reportList.append(reportItem);
                        });
                    }else{
                        reportList.append('<p class="pt-2">Reports for appointment are not available.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.reportUploadList-data').html('<p>Error loading reports. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $('#fileInput').on('change', function () {
                var files = $('#fileInput')[0].files;
                var maxSize = 32 * 1024 * 1024; // 32MB for images and PDFs
                var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
                var valid = true;
                var formData = new FormData();
                const reportList = $('.reportUploadList-data');
                if (files.length === 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'File Validation Failed!',
                        text: 'Please select a file to upload.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return;
                }
                $.each(files, function (index, file) {
                    if ($.inArray(file.type, allowedTypes) === -1) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Type',
                            text: 'Invalid file type: ' + file.name + '. Allowed file type are .jpeg, .png or .pdf.',
                            confirmButtonColor: '#34B6B3',
                            customClass: {
                                title: 'my-custom-title',
                                content: 'my-custom-content'
                            }
                        });
                        valid = false;
                        return false;
                    }
        
                    // Validate file size
                    if (file.size > maxSize) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Invalid File Size',
                            text: 'Please select allowed file size. File size must be less than 32MB for file: ' + file.name,
                            confirmButtonColor: '#34B6B3',
                            customClass: {
                                title: 'my-custom-title',
                                content: 'my-custom-content'
                            }
                        });
                        valid = false;
                        return false;
                    }
        
                    formData.append('reports[]', file);
                });
                if (!valid) {
                    return;
                }
                reportList.empty();
                reportList.append(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                formData.append("appointmentId", $('.user-item-left-selected').attr('data-appointmentId'));
                formData.append("patientId", $('.user-item-left-selected').attr('data-patientId'));
                formData.append("practitionerId", "{{ session('PractitionerId') }}");
                formData.append('timezone', timeZone);
                // AJAX request to upload file
                $.ajax({
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/reports/upload",
                    timeout: 0,
                    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" data-reportid="${item.reportId}" data-reporturl="${item.reportURL}">${item.title}</h5>
                                </div>`;
                                reportList.append(reportItem);
                            });
                        }else{
                            reportList.append('<p class="pt-2">Reports for appointment are not available.</p>');
                        }
                        getAllReports($('.user-item-left-selected').attr('data-patientId'));
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        getAppointmentReports();
                        console.log(jqXHR, errorThrown);
                        console.log('File upload failed. Please try again.');
                    }
                });
            });
            
            /* Prescription Generation */
            function generatePrescription(appointmentId, soapNote) {
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', $('.user-list-left .user-item-left-selected').attr('data-patientid'));
                formData.append('appointmentId', appointmentId);
                formData.append('soapSummary', decodeURIComponent(soapNote));
                formData.append('timezone', timeZone);
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/generate/prescription",
                    method: "POST",
                    timeout: 0,
                    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', encodeURIComponent(prescriptionHTML));
                    $('#edit-btn').attr('data-content', encodeURIComponent(prescriptionHTML));
                    $('.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');
                $('.transcription').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('timezone', timeZone);
        
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/patients",
                    method: "POST",
                    timeout: 0,
                    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(){
                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();
                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('practitioner', "{{session('PractitionerId')}}");
                formData.append('practitionerName', "{{session('PractitionerName')}}");
                formData.append('patient', patientId);
                formData.append('patientName', patientName);
                formData.append('timeSlot', formateTimeSlot(slotDate+' '+slotTime));
                formData.append('visit', jQuery('#visit').val());
                formData.append('timezone', timeZone);
            
                const settings = {
                    url: "{{env('API_URL')}}{{session('currentEHR')}}/addappointment",
                    method: "POST",
                    timeout: 0,
                    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",
                        text: "Appointment scheduled successfully.",
                        showConfirmButton: false,
                        timer: 1000
                    });
                    window.location.reload();
                }).fail((jqXHR, textStatus, errorThrown) => {
                    Swal.fire({
                        position: "top-end",
                        text: "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,
                    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);
                });
            });

            function downloadPDF(html, filename){
                const content = `<style>pre{overflow-x: auto;white-space: pre-wrap;word-wrap: break-word;}</style>${html}`;
                const fileName = filename.toLowerCase();
                $.ajax({
                    url: "{{env('APP_URL')}}/download-pdf",
                    type: 'POST',
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    data: { 
                        content: content,
                        notetype: filename,
                        appointmentId: $('.user-item-left-selected').attr('data-appointmentId'),
                        inventoryData: inventoryData
                    },
                    xhrFields: {
                        responseType: 'blob'
                    },
                    success: function (response) {
                        const blob = new Blob([response], { type: 'application/pdf' });
                        const url = window.URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = fileName+'.pdf';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        window.URL.revokeObjectURL(url);
                        Swal.fire({
                            position: "top-end",
                            text: 'PDF download successfully.',
                            showConfirmButton: false,
                            timer: 2000
                        });
                    },
                    error: function (xhr) {
                        Swal.fire({
                            position: "top-end",
                            text: xhr.responseText.message,
                            showConfirmButton: false,
                            timer: 2000
                        });
                    }
                });
            }

            $(document).on('click', '#download-btn', function() {
                var html = jQuery(".data-tab").not(".d-none").first().html();
                var filename = jQuery("#appointmentDetailModal .primary-bg-color").text().trim();
                // var className = $('.appointment-details-modal > div:not(.d-none)').attr('class');
                downloadPDF(html, filename);
            });

            $(document).on('click', '#saveInventory', function() {
                const formData = new FormData();
                formData.append('appointmentId', $('.user-item-left-selected').attr('data-appointmentId'));
                formData.append('inventoryData', inventoryData);
                const settings = {
                    url: "{{env('API_URL')}}inventory",
                    method: "POST",
                    timeout: 0,
                    processData: false,
                    contentType: false,
                    data: formData
                };
                $.ajax(settings).done(response => {
                    Swal.fire({
                        position: "top-end",
                        text: 'Inventory stored successfully.',
                        showConfirmButton: false,
                        timer: 2000
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    console.error("Error:", textStatus, errorThrown);
                });
            });
        });
    </script>
@endpush