<!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="{{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="#" 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" 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>
                <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>
    </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>
        $(document).ready(function() {
            function getAppointments(){
                const formData = new FormData();
                formData.append('practitioner', "{{ session('PractitionerId') }}");
        
                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() {
                        jQuery('.loading').removeClass('d-none');
                        if (stream) {
                            stream.getTracks().forEach(track => track.stop());
                        }
                        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', '.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();
            });
        
            $(document).on('click', '.user-item-left', function(){
                $('.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');
            });
        
            $(document).on('click', '.erase', function(){
                $('.audio-text-box').html('<audio id="audio" src=""></audio>');
            });
        });
    </script>
</body>
</html>
