<!DOCTYPE html>
<html>
<head>
    <title>Med-X | Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-icons/3.0.2/iconfont/material-icons.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="{{url('public/assets/css/style.css')}}">
</head>
<body>
    <div class="loading d-none">
      <div class='uil-ring-css' style='transform:scale(0.5);'>
        <div></div>
      </div>
    </div>
    <header>
        <nav class="menu">
            <a href="/" class="menu__item menu__item--active">
                <i class="material-icons">home</i>
            </a>
            <a href="#" class="menu__item">
                <i class="material-icons">help_outline</i>
            </a>
            <a href="#" class="menu__item">
                <i class="material-icons">settings</i>
            </a>
            <a href="https://auth.zapehr.com/logout" class="menu__item">
                <i class="material-icons">exit_to_app</i>
            </a>
        </nav>
    </header>
    <main class="container-fluid">
        <div class="row">
            <div class="col-sm-3">
                <div class="d-flex align-items-center">
                    <div class="col-sm-10 pl-0">
                        <img src="https://api.prod.med-x.ai/public/images/MedX-Logo.png" width="75%" alt="Med-X Logo">
                    </div>
                    <div class="col-sm-2 icons">
                        <i class="fas fa-calendar-plus primary-color" aria-label="Add Appointment"></i>
                    </div>
                </div>
                <div class="input-group mt-3">
                    <input type="text" class="form-control" placeholder="Search Patient" aria-label="Search Patient">
                    <div class="input-group-append">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <h3 class="font-weight-light mt-3 mb-0">Scheduled Visits</h3>
                <div class="user-list user-list-left"></div>
            </div>
            <div class="col-sm-6">
                <div class="center-box">
                    <div class="mt-5 pt-4">
                        <h2 class="primary-color">Hello, {{session('PractitionerName')}}</h2>
                        <h5 class="secondary-color">Select a scheduled visit to get started!</h5>
                        <div class="d-flex align-items-center mt-5">
                            <i class="material-icons-outlined glowing-icon" style="font-size:44px" aria-label="Info">wb_incandescent</i>
                            <p class="pl-2 mb-0">Historical medical records will be listed on the right-side in chronological order clearly showing the visits that have reports attached.</p>
                        </div>
                    </div>
                </div>
                <div class="center-box-selected d-none">
                    <div class="user-list mt-0">
                        <div class="user-item border-0 pb-0 pt-1 pl-0">
                            <h4 class="secondary-color patientName mb-0"></h4>
                            <small class="patientId"></small>
                        </div>
                    </div>
                    <h6 class="secondary-color appointmentId pt-4"></h6>
                    <div class="audio-text-box">
                        <audio id="audio" src=""></audio>
                    </div>
                    <div class="bottom-bar text-center">
                        
                        <div class="button-panel">
                            <i class="fas fa-microphone primary-color start-recording" aria-label="Audio Recording"></i>
                            <i class="fas fa-microphone primary-color play-recording d-none" aria-label="Audio Start"></i>
                            <i class="fas fa-pause primary-color pause-recording d-none" aria-label="Audio Pause"></i>
                            <i class="fas fa-stop text-danger stop-recording d-none" aria-label="Audio Stop"></i>
                            <i class="fas fa-cloud-upload-alt primary-color" aria-label="Reports Upload"></i>
                            <i class="fas fa-eraser primary-color erase" aria-label="Erase Audio Data"></i>
                            <i class="fas fa-check primary-color generate-transcription" aria-label="Submit for SOAP Summary"></i>
                        </div>
                        <p class="mb-2">MedX engine may display inaccurate information, please check the data before submitting it for further processing.</p>
                    </div>
                    
                </div>
            </div>
            <div class="col-sm-3">
                <div class="user-list mt-0">
                    <div class="user-item border-0 pb-0 pt-1">
                        <h4 class="secondary-color mb-0">{{session('PractitionerName')}}</h4>
                        <small>{{session('suffix')}}</small>
                    </div>
                </div>
                <div class="input-group mt-3">
                    <input type="text" class="form-control" placeholder="Search Patient History" aria-label="Search Patient History">
                    <div class="input-group-append">
                        <span class="input-group-text">
                            <i class="material-icons">search</i>
                        </span>
                    </div>
                </div>
                <div class="appointment-close">
                    <h3 class="font-weight-light mt-3 mb-0">Patient’s History</h3>
                    <p class="text-center mt-3">Historical records will be displayed in this section</p>
                </div>
                <div class="appointment-show mt-3 pr-1 d-none">
                    <div class="list-group panel">
                        <a href="#reports-list" id="reports" class="list-group-item-report" data-toggle="collapse">
                            <span class="d-flex justify-content-between align-items-center">
                                <h3 class="font-weight-light mb-0">Patient's Reports</h3>
                                <i class="fas fa-angle-down"></i>
                            </span>
                        </a>
                        <div class="d-grid pt-2 pl-2 pr-3 collapse" id="reports-list"></div>
                        <hr/>
                        <a href="#history-list" id="history" class="list-group-item-history" data-toggle="collapse">
                            <span class="d-flex justify-content-between align-items-center">
                                <h3 class="font-weight-light mb-0">Patient's History</h3>
                                <i class="fas fa-angle-up"></i>
                            </span>
                        </a>
                        <div class="d-grid pt-2 pl-2 pr-3 collapse show" id="history-list"></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal" id="appointmentDetailModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
            <div class="modal-dialog-xl modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-body appointment-details-modal">
                    </div>
                    <div class="modal-footer justify-content-center">
                        <button type="button" class="btn btn-outline-primary transacription">Transcription</button>
                        <button type="button" class="btn btn-outline-primary primary-bg-color soap-summary">SOAP Summary</button>
                        <button type="button" class="btn btn-outline-primary prescription">Prescription</button>
                        <button type="button" class="btn btn-outline-danger modal-close" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js" async></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" async></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/12.2.0/markdown-it.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script>
        $(document).ready(function() {
            const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
            const md = window.markdownit();
            function getAppointments(){
                const formData = new FormData();
                formData.append('practitioner', "{{ session('PractitionerId') }}");
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "https://api.dev.med-x.ai/api/v1/ehr-default/appointments",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('.user-list-left').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const userList = $('.user-list-left');
                    userList.empty();
                    const currentTime = new Date();
                    response.data.forEach(item => {
                        const itemTimeSlot = new Date(item.timeSlot);
                        const isSameDate = currentTime.toDateString() === itemTimeSlot.toDateString();
                        const appointmentTime = isSameDate 
                            ? itemTimeSlot.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) 
                            : itemTimeSlot.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
                        // const appointmentTime = new Date(item.timeSlot).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                        const appointmentId = item.appointmentId;
                        const patientId = item.patientURL;
                        const appointmentType = item.appointmentType;
                        const patientName = `${item.patientPrefix} ${item.patient}`;
                        
                        const userItem = `
                            <div class="user-item-left" data-appointmentId="${appointmentId}" data-patientId="${patientId}" data-patientName="${patientName}">
                                <h5>${patientName}</h5>
                                <small>${appointmentTime} | ${appointmentType}</small>
                            </div>
                        `;
                        
                        userList.append(userItem);
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.user-list-left').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            getAppointments();
            
            // Audio Recording
            let mediaRecorder;
            let audioChunks = [];
            let isPaused = false;
            let stream;

            function stopMediaStream() {
                if (stream) {
                    stream.getTracks().forEach(track => track.stop());
                }
            }
            
            async function initRecorder() {
                try {
                    stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    mediaRecorder = new MediaRecorder(stream);

                    mediaRecorder.ondataavailable = function(event) {
                        if (event.data.size > 0) {
                            audioChunks.push(event.data);
                        }
                    };

                    mediaRecorder.onstop = async function() {
                        if (stream) {
                            stream.getTracks().forEach(track => track.stop());
                        }
                        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');
                                const audioBlob = new Blob(audioChunks, { type: 'audio/mp4' });
                                audioChunks = [];
                                
                                const audioContext = new (window.AudioContext || window.webkitAudioContext)();
                                const arrayBuffer = await audioBlob.arrayBuffer();
                                audioContext.decodeAudioData(arrayBuffer, (buffer) => {
                                    const duration = buffer.duration;
                                    console.log("Audio Duration: ", duration);
                                    // Upload the audio file or perform further processing here
                                    const audioUrl = URL.createObjectURL(audioBlob);
                                    audioToText(audioBlob, audioUrl);
                                }, (error) => {
                                    jQuery('.loading').addClass('d-none');
                                    console.error('Error decoding audio data:', error);
                                });
                            }
                        })
                        // const audioUrl = URL.createObjectURL(audioBlob);
                        // // const audioElement = $('<audio>', { controls: true, src: audioUrl });
                        // // $('#audioPlaybackContainer').append(audioElement);
                        // audioToText(audioBlob, audioUrl);
                    };
                } catch (err) {
                    console.error('Failed to initialize recorder:', err);
                }
            }
            
            function audioToText(mp3Blob, audioUrl) {
                const form = new FormData();
                form.append("patientId", $('.user-item-left-selected').attr('data-patientId'));
                form.append("practitionerId", "{{ session('PractitionerId') }}");
                form.append("appointmentId", $('.user-item-left-selected').attr('data-appointmentId'));
                form.append("audio_file", mp3Blob, $('.user-item-left-selected').attr('data-appointmentId')+"T"+new Date().getTime()+'.mp3');

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

                $.ajax(settings).done(response => {
                    $('.audio-text-box').append(`
                        <div class="conversation d-flex">
                            <p class="text mb-0">${response.data.audiotext}</p>
                            <span class="player" data-url="${audioUrl}" data-classname="${new Date().getTime()}">
                                <i class="fas fa-play primary-color resume-${new Date().getTime()}"></i>
                                <i class="fas fa-pause d-none primary-color pause-${new Date().getTime()}"></i>
                                <span class="duration time-${new Date().getTime()} d-none">00:00</span>
                            </span>
                        </div>
                    `);
                    jQuery('.loading').addClass('d-none');
                }).fail((jqXHR, textStatus, errorThrown) => {
                    console.log('Error while converting audio to text.');
                    console.error("Error:", textStatus, errorThrown);
                    jQuery('.loading').addClass('d-none');
                });
            }
            
            $('.start-recording').on('click', async function() {
                await initRecorder();
                mediaRecorder.start();
                $('.start-recording').addClass('d-none');
                $('.pause-recording').removeClass('d-none');
                $('.stop-recording').removeClass('d-none');
            });
            
            $('.pause-recording').click(function() {
                if (mediaRecorder && !isPaused) {
                    mediaRecorder.pause();
                    isPaused = true;
                    $('.play-recording').removeClass('d-none');
                    $('.pause-recording').addClass('d-none');
                }
            });
            
            $('.play-recording').click(function() {
                if (mediaRecorder && isPaused) {
                    mediaRecorder.resume();
                    isPaused = false;
                    $('.play-recording').addClass('d-none');
                    $('.pause-recording').removeClass('d-none');
                }
            });

            $('.stop-recording').click(function() {
                if (mediaRecorder) {
                    mediaRecorder.stop();
                    $('.start-recording').removeClass('d-none');
                    $('.play-recording').addClass('d-none');
                    $('.pause-recording').addClass('d-none');
                    $('.stop-recording').addClass('d-none');
                }
            });
            
            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];
                audio.onloadedmetadata = function() {
                    if (isNaN(audio.duration)) {
                        console.error('Duration is not available.');
                        $('.time-'+className).text('00:00');
                    } else {
                        updateCurrentTime(className);
                    }
                };
            
                // 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');
                };
                
                $('.resume-'+className).addClass('d-none');
                $('.pause-'+className).removeClass('d-none');
                $('.time-'+className).removeClass('d-none');
                audio.play();
            });

            $(document).on('click', '.conversation .fa-pause', function(){
                var parentSpan = $(this).closest('.player');
                var className = parentSpan.attr('data-classname');
                $('.resume-'+className).removeClass('d-none');
                $('.pause-'+className).addClass('d-none');
                $('.time-'+className).addClass('d-none');
                audio.pause();
            });
            
            function getAllReports(patientId){
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('patientId', patientId);
                formData.append('timezone', timeZone);
        
                const settings = {
                    url: "https://api.dev.med-x.ai/api/v1/ehr-default/patient/reports",
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('#reports-list').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const reportList = $('#reports-list');
                    reportList.empty();
                    if(response.data.length > 0){
                        response.data.forEach(reports => {
                            reports.report.forEach(item => {
                                const reportTime = new Date(reports.date).toLocaleTimeString('en-US', {
                                    year: 'numeric',
                                    month: 'long',
                                    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">
                                    <h5 data-reportId="${item.reportId}" data-reportURL="${item.reportURL}" data-conclusion="${reports.conclusion}" class="report-details">${reportTime}</h5>
                                    <i class="fa fa-paperclip" aria-hidden="true"></i>
                                </div>`;
                                reportList.append(reportItem);
                            });
                        });
                    }else{
                        reportList.append('<p class="pt-2">Appointment history not available.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#reports-list').html('<p>Error loading appointments. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function getPatientHistory(patientId){
                const practitionerId = "{{ session('PractitionerId') }}";
                const formData = new FormData();
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/patient/history/${practitionerId}/${patientId}`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('#history-list').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.ajax(settings).done(response => {
                    const historyList = $('#history-list');
                    historyList.empty();
                    if(response.data.length > 0){
                        response.data.forEach(item => {
                            const historyItem = `<div class="d-flex align-items-baseline right-bottom-border justify-content-between">
                                <h5 data-appointmentId="${item.appointmentId}" class="appointment-details">${item.date}</h5>
                                <a href="javascript:void(0)" id="version" data-classname="${item.timeSlot}" data-appointmentId="${item.appointmentId}">
                                    <i class="fas fa-plus" aria-hidden="true" data-classname="${item.timeSlot}" data-appointmentId="${item.appointmentId}"></i>
                                </a>
                            </div>
                            <div class="d-grid version ${item.timeSlot}" style="display: none;"></div>`;
                            historyList.append(historyItem);
                        });
                        $('.appointment-details').hover(
                            function() { $(this).parent().addClass('appointment-right'); },
                            function() { $(this).parent().removeClass('appointment-right'); }
                        );
                    }else{
                        historyList.append('<p class="pt-2">Appointment history not available.</p>');
                    }
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('#history-list').html('<p>Error loading appointment history. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function getVersions(appointmentId, className){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('timezone', timeZone);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/appointment/history`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
        
                jQuery('.'+className).html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
        
                $.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: 'long',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                            hour12: true
                        });
                        var historyItem = `<div class="d-flex align-items-baseline appointment-version-details right-bottom-border justify-content-between" data-versionId="${item.versionId}" data-description="${item.description}" data-comment="${item.comment}" data-patientInstruction="${item.patientInstruction}" data-documentId="${item.documentId}">
                            <h5>${versionTime}</h5>`;
                        if(item.documentId != '' && item.documentId != null && item.documentId != undefined) {
                            historyItem += `<i class="fa-solid fa-music border-0" aria-hidden="true"></i>`;
                        }
                        historyItem += `</div>`;
                        historyList.append(historyItem);
                    });
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.'+className).html('<p>Error loading appointment versions. Please try again later.</p>');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function appointmentDetails(appointmentId){
                const formData = new FormData();
                formData.append('appointmentId', appointmentId);
                formData.append('timezone', timeZone);
                formData.append('date', '2024-05-17');
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/appointment/details`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.appointment-details-modal').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('#appointmentDetailModal').modal('show');
                $.ajax(settings).done(response => {
                    $('.soap-summary').addClass('primary-bg-color');
                    $('.transacription').removeClass('primary-bg-color');
                    $('.prescription').removeClass('primary-bg-color');
                    const transacription = response.data.description;
                    const soapSummaryData = response.data.comment;
                    const soapSummary = md.render(soapSummaryData);
                    const prescription = response.data.patientInstruction;
                    var html = '';
                    html += `<h6 class="appointment-id primary-color">Appointment ID: ${response.data.appointmentId}</h6>`;
                    html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                    html += `<div class="soap-summary-data"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                    html += `<div class="prescription-data d-none"><p>${prescription.length > 0 ? prescription : 'Prescription is not available.'}</p></div>`;
                    $('.appointment-details-modal').html(html);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.appointment-details-modal').html(`
                        <p>Error loading appointment versions. Please try again later.</p>
                    `);
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            function generateTranscription(appointmentId, patientId, transcription) {
                const formData = new FormData();
                formData.append('practitionerId', "{{ session('PractitionerId') }}");
                formData.append('appointmentId', $('.user-list-left .user-item-left-selected').attr('data-appointmentid'));
                formData.append('patientId', $('.user-list-left .user-item-left-selected').attr('data-patientid'));
                formData.append('transcription', transcription);
                formData.append('timezone', timeZone);
                console.log(formData);
                const settings = {
                    url: `https://api.dev.med-x.ai/api/v1/ehr-default/transcription`,
                    method: "POST",
                    timeout: 0,
                    headers: {
                        "Authorization": "Bearer " + "{{ session('accessToken') }}"
                    },
                    processData: false,
                    contentType: false,
                    data: formData
                };
                jQuery('.appointment-details-modal').html(`
                    <div class="loader-container">
                        <div class="loader" id="loader"></div>
                    </div>
                `);
                $('#appointmentDetailModal').modal('show');
                $.ajax(settings).done(response => {
                    $('.soap-summary').addClass('primary-bg-color');
                    $('.transacription').removeClass('primary-bg-color');
                    $('.prescription').removeClass('primary-bg-color');
                    const transacription = response.data.description;
                    const soapSummaryData = response.data.comment;
                    const soapSummary = md.render(soapSummaryData);
                    const prescription = response.data.patientInstruction;
                    var html = '';
                    html += `<h6 class="appointment-id primary-color">Appointment ID: ${response.data.appointmentId}</h6>`;
                    html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                    html += `<div class="soap-summary-data"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                    html += `<div class="prescription-data d-none"><p>${prescription.length > 0 ? prescription : 'Prescription is not available.'}</p></div>`;
                    $('.appointment-details-modal').html(html);
                }).fail((jqXHR, textStatus, errorThrown) => {
                    jQuery('.appointment-details-modal').html(`
                        <p>Error loading appointment versions. Please try again later.</p>
                    `);
                    $('#appointmentDetailModal').modal('hide');
                    console.error("Error:", textStatus, errorThrown);
                });
            }
            
            $(document).on('click', '.generate-transcription', function() {
                var transcription = '';
                $('.conversation .text').each(function() {
                    transcription += transcription.length > 0 ? '\n'+$(this).text() : $(this).text();
                });
                if(transcription == '' || transcription.length == 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Failed!',
                        text: 'Conversation data is required to generate SOAP Summary.',
                        confirmButtonColor: '#34B6B3',
                        customClass: {
                            title: 'my-custom-title',
                            content: 'my-custom-content'
                        }
                    });
                    return false;
                }
                const appointmentId = $('.user-list-left .user-item-left-selected').attr('data-appointmentid');
                const patientId = $('.user-list-left .user-item-left-selected').attr('data-patientid');
                generateTranscription(appointmentId, patientId, transcription);
            });
        
            $(document).on('click', '.user-item-left', function(){
                Swal.fire({
                    title: 'Consent',
                    text: "It is mandatory to obtain informed consent from the patient before recording their conversation.",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#34B6B3',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Ok',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $('.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();
                $('#version i').addClass('fa-plus').removeClass('fa-minus');
                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');
                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" src=""></audio>');
                        }
                    })
                }
            });
        
            $(document).on('click', '.appointment-version-details', function(){
                $('.appointment-version-details').removeClass('version-selected');
                $('.appointment-details').parent().removeClass('version-selected');
                $(this).addClass('version-selected');
                $('.soap-summary').addClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                const transacription = $(this).attr('data-description');
                const soapSummaryData = $(this).attr('data-comment');
                const soapSummary = md.render(soapSummaryData);
                const prescription = $(this).attr('data-patientInstruction');
                var html = '';
                html += `<div class="transcription-data d-none"><p>${transacription.length > 0 ? transacription : 'Transacription is not available.'}</p></div>`;
                html += `<div class="soap-summary-data"><p>${soapSummary.length > 0 ? soapSummary : 'SOAP Summary is not available.'}</p></div>`;
                html += `<div class="prescription-data d-none"><p>${prescription.length > 0 ? prescription : 'Prescription is not available.'}</p></div>`;
                $('.appointment-details-modal').html(html);
                $('#appointmentDetailModal').modal('show');
            });
            
            $(document).on('click', '.appointment-details', function(){
                $('.appointment-details').parent().removeClass('version-selected');
                $('.appointment-version-details').removeClass('version-selected');
                $(this).parent().addClass('version-selected');
                const appointmentId = $(this).attr('data-appointmentId');
                appointmentDetails(appointmentId);
            });
            
            $(document).on('click', '.modal-close', function() {
                $('.appointment-details').parent().removeClass('version-selected');
                $('.appointment-version-details').removeClass('version-selected');
                $('#appointmentDetailModal').modal('hide');
            });
            
            $(document).on('click', '.transacription', function(){
                $(this).addClass('primary-bg-color');
                $('.soap-summary').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                $('.transcription-data').removeClass('d-none');
                $('.soap-summary-data').addClass('d-none');
                $('.prescription-data').addClass('d-none');
            });
            
            $(document).on('click', '.soap-summary', function(){
                $(this).addClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.prescription').removeClass('primary-bg-color');
                $('.transcription-data').addClass('d-none');
                $('.soap-summary-data').removeClass('d-none');
                $('.prescription-data').addClass('d-none');
            });
            
            $(document).on('click', '.prescription', function(){
                $(this).addClass('primary-bg-color');
                $('.soap-summary').removeClass('primary-bg-color');
                $('.transacription').removeClass('primary-bg-color');
                $('.transcription-data').addClass('d-none');
                $('.soap-summary-data').addClass('d-none');
                $('.prescription-data').removeClass('d-none');
            });
        });
    </script>
</body>
</html>
