<?php
include 'inc/header2.php';
//cek lv.user yang dibolehkan untuk akses halaman
Session::CheckSession();
// If no session variable exists, or unauthorized user_level, redirect the user:
  if (isset($_SESSION['id']))
  {
  // if a valid user session is found then the user level is checked, if the
  // user has level 3 access they will be granted access if not a access denied
  //message be displayed and the user will be redirected.
	 if ($_SESSION['roleid'] <= 3) {}

  else
  {
	header("Refresh: 1; url=403/index.php");
	exit(); // Quit the script.
  }  
  }
  // if no valid session is found then the user is not logged in and will
  // receive a access denied message and will be redirected to the login page.
  else if (!isset($_SESSION['user_id'])) {

  header("Refresh: 3; url=login.php");
  echo '<h3>Akses Ditolak!! - Anda tidak memiliki izin untuk mengakses halaman ini!</h3>';
  echo '<p>You will be redirected in 3 seconds</p>';
  include ('403/index.html');
  exit(); // Quit the script.
  }  
//end logika untuk lv user
 ?>

<?php
// Get the id parameter from the URL
if (isset($_GET['id'])) {
  $id_patient = preg_replace('/[^a-zA-Z0-9-]/', '', (int)$_GET['id']);
}
if (!$id_patient) {
    // Handle the case when the id parameter is not provided
    echo "Patient ID not provided.";
    exit();
}
 ?>
 <!-- Breadcurm-->
 <?php
$getUinfo = $users->getAnggotaInfoById($id_patient);
if ($getUinfo) {
?>
<?php 
$sesuaiid = $getUinfo->record_id;
?>
    <div class="page-body">
      
      <div class="container-fluid">
            <div class="page-title">
              <div class="row">
                <div class="col-6">
                 
                </div>
                <div class="col-6">
                  <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/mPanel" data-bs-original-title="" title="">                                       <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-home"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg></a></li>
                    <li class="breadcrumb-item"> Show Patient Data</li>
                    <li class="breadcrumb-item active"> <?php echo $getUinfo->patient_fname;?>&nbsp;<?php echo $getUinfo->patient_lname;?></li>
                    
                  </ol>
                </div>
              </div>
            </div>
          </div>
          <!-- isi page starts-->
           <div class="edit-profile">
              <div class="row">
                <div class="col-xl-4">
                  <div class="card">
                    <div class="card-header">
                      <h4 class="card-title mb-0">Patient Record Details</h4><small>Record ID <?php echo $getUinfo->record_id; ?></small>
                      <div class="card-options"><a class="card-options-collapse" href="#" data-bs-toggle="card-collapse" data-bs-original-title="" title=""><i class="fe fe-chevron-up"></i></a><a class="card-options-remove" href="#" data-bs-toggle="card-remove" data-bs-original-title="" title=""><i class="fe fe-x"></i></a></div>
                    </div>
                    <div class="card-body">
                      <form>
                        <div class="row mb-2">
                          <div class="profile-title">
                            <div class="media"><img class="img-70 rounded-circle" alt="" src="/assets/images/pod/favicon.png"><br>
                              <div class="media-body">
                                <h5 class="mb-1"><?php echo $getUinfo->patient_fname;?>&nbsp;<?php echo $getUinfo->patient_lname;?></h5>
                                <small><?php echo $getUinfo->record_date; ?></small>
                              </div>
                                    <a class="btn btn-pill btn-outline-success btn-xs"><?php echo $getUinfo->record_at; ?></a>
                            </div>
                          </div>
                          
                        </div>
                        <div class="mb-3">
                            <div class="ribbon-wrapper card">
                                <div class="card-body">
                                    <div class="ribbon ribbon-bookmark ribbon-success">Chief Complaint</div>
                                        <p><?php echo $getUinfo->record_notes; ?></p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card">
                            <div class="collapse show">
                                <div class="categories">
                                    <ul>
                                    <li>First Name :<span class="pull-right" style="font-weight: 300;"><?php echo $getUinfo->patient_fname; ?></span></li>
                                    <li>Last Name :<span class="pull-right" style="font-weight: 300;"><?php echo $getUinfo->patient_lname; ?></span></li>
                                    <li>Sex :<span class="pull-right" style="font-weight: 300;"><?php echo $getUinfo->patient_sex; ?></span></li>
                                    <li>Date Of Birth :<span class="pull-right" style="font-weight: 300;"><?php echo $getUinfo->patient_dob; ?></span></li>
                                    <li>Age Calculation :<span class="pull-right" style="font-weight: 300;"><?php $dob = $getUinfo->patient_dob; $birthdate = new DateTime($dob); $currentDate = new DateTime(); $interval = $currentDate->diff($birthdate);
                                    $dobyears = $interval->y; $dobmonths = $interval->m; $dobdays = $interval->d; echo "$dobyears years, $dobmonths months, $dobdays days";?></span></li>
                                    <li>Phone Number :<span class="pull-right" style="font-weight: 300;"><?php echo $getUinfo->patient_contact; ?></span></li>
                                    <li>Patient Care Specialist :<span class="pull-right" style="font-weight: 300;"><?php echo $getUinfo->record_by; ?></span></li>
                                    </ul>
                                </div>
                            </div>
                            
                              <?php if (isset($_GET['id']) == $sesuaiid) { ?>
                                <!-- <div class="btn-group" role="group" aria-label="Patient Profile">
                                  <a href="././edit-anggota.php?id=<?php //echo $getUinfo->record_id;?>" class="btn btn-outline-success" type="button">Change Data</a>
                                  <a href="././gantifoto.php?id=<?php //echo $getUinfo->record_id;?>" class="btn btn-outline-success" type="button">Change Patient Photo</a>
                                  <a href="././gantipwdanggota.php?id=<?php //echo $getUinfo->record_id;?>" class="btn btn-outline-success" type="button">Change Password</a>
                                </div> !-->
                              <?php  } ?>
<?php } ?>
                      </div>
                      <div class="btn-group" role="group" aria-label="Patient Profile">
                              <a href="././edit-anggota.php?id=<?php //echo $getUinfo->record_id;?>" class="btn btn-outline-success" type="button">Generate PDF</a>
                            </div>
                      </form>
                    </div>
                  </div>
                </div>
                <div class="col-xl-8">
                  <form class="card">
                    <div class="card-header">
                      <h4 class="card-title mb-0">Vitals</h4>
                      <div class="card-options"><a class="card-options-collapse" href="#" data-bs-toggle="card-collapse" data-bs-original-title="" title=""><i class="fe fe-chevron-up"></i></a><a class="card-options-remove" href="#" data-bs-toggle="card-remove" data-bs-original-title="" title=""><i class="fe fe-x"></i></a></div>
                    </div>
                    <div class="card-body">
                      <div class="row">
                        <div class="user-status table-responsive">
                            <table class="hover display" id="patient-details">
                                <thead>
                                    <tr>
                                        <th  class="text-center">BP</th>
                                        <th  class="text-center">Temp</th>
                                        <th  class="text-center">Resp</th>
                                        <th  class="text-center">HR</th>
                                        <th  class="text-center">Weight</th>
                                        <th  class="text-center">O2 SOT</th>
                                    </tr>
                                </thead>
                                <tbody style="text-align: center;">
                                    
                                </tbody>
                            </table>
                      </div>
                    </div>
                    
                  </form>
                  
                </div>
                <div class="col-xl-12">
                  <div class="card">
                    <div class="card-header">
                      <h4 class="card-title mb-0">Audio</h4>
                    </div>
                    <div class="card-body">
                      <div id="audiomed-results">
                      
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
              
            </div>
          <div class="edit-profile">
            <div class="row">
              <div class="col-sm-12">
                <div class="card">
                  <div class="card-header">
                    <h5>Camera</h5>
                    <div class="card-options"><a class="card-options-collapse" href="#" data-bs-toggle="card-collapse" data-bs-original-title="" title=""><i class="fe fe-chevron-up"></i></a><a class="card-options-remove" href="#" data-bs-toggle="card-remove" data-bs-original-title="" title=""><i class="fe fe-x"></i></a></div>
                  </div>
                  <div class="card-body">
                      <div id="cammed-results">
                        <div class="loader-box loading-indicator">
                          <div class="loader-7"></div>
                        </div>
                      </div>
                      <!-- Modal for full-screen image view -->
                      <div id="imageModal">
                        <span class="close-button" onclick="closeFullScreenImage()">&times;</span>
                        <img id="fullScreenImage" alt="Full-Screen Image">
                      </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          

      



      </div>
    </div>


  <?php
  include 'inc/footer2.php';
  ?>
<script>
    <?php $id_patient = preg_replace('/[^a-zA-Z0-9-]/', '', (int)$_GET['id']); ?>
    $(document).ready(function() {
        // Initialize DataTable
        var dataTableVitals = $('#patient-details').DataTable();

        // Create an EventSource to listen for updates from server_endpoint.php
        var eventSourceVitals = new EventSource('http://localhost/mPanel/live/live-patient-vitals.php?id=<?php echo $id_patient; ?>');

        // Event listener for updates
        eventSourceVitals.onmessage = function(eventVitals) {
            var patientInfo = JSON.parse(eventVitals.data);
            // Clear existing rows
            dataTableVitals.clear();

            // Add the updated patient information to the DataTable
            dataTableVitals.row.add([
                patientInfo.vbp,
                patientInfo.vtemp,
                patientInfo.vresp,
                patientInfo.vhr,
                patientInfo.vweight,
                patientInfo.vsot
                // Add additional columns as needed
            ]).draw(false);
        };

        // Event listener for errors (optional)
        eventSourceVitals.onerror = function(eventVitals) {
            console.error('EventSource failed:', eventVitals);
            eventSourceVitals.close();
        };

        // Close the EventSource when the page is closed or refreshed
        window.onbeforeunload = function() {
            eventSourceVitals.close();
        };
    });
</script>

<script>
   <?php $record_id = preg_replace('/[^a-zA-Z0-9-]/', '', (int)$_GET['id']); ?>
    var displayedData = []; // To keep track of displayed data
    // Create an EventSource to listen for updates from server_endpoint.php
    var eventSource = new EventSource('http://localhost/mPanel/live/live-patient-camera.php?id=<?php echo $record_id; ?>');

     // Event listener for updates
    eventSource.onmessage = function(event) {
        var filesData = JSON.parse(event.data);

        // Filter out already displayed data
        var newFilesData = filesData.filter(function(fileInfo) {
            return !displayedData.some(function(displayedFile) {
                return displayedFile.device_type === fileInfo.device_type &&
                       displayedFile.record_date === fileInfo.record_date &&
                       displayedFile.record_at === fileInfo.record_at &&
                       displayedFile.picts === fileInfo.picts;
                // Add additional fields for comparison as needed
            });
        });
         // Display the loading indicator
        document.querySelector('.loading-indicator').style.display = 'none';
        
        // Create a new Image object to preload images
        var preloadedImages = new Image();
        // Event listener for image loading
        preloadedImages.onload = function() {
            // Remove the loading indicator
            document.querySelector('.loading-indicator').style.display = 'none';
            // Preload images before appending to the DOM
        newFilesData.forEach(function(fileInfo) {
            preloadedImages.src = fileInfo.picts;
        });

        // Display the updated patient files information
        var htmlContent = '';
        newFilesData.forEach(function(fileInfo) {
            htmlContent += '<div class="excamresults">' + '<div class="excamresult">' + 
                           '<img src="' + fileInfo.picts + '" onclick="toggleFullScreen(this)"><br>' +
                           '<p class="exf1">Device Type: ' + fileInfo.device_type + '</p>' +
                           '<p class="exf2">Record Date: ' + fileInfo.record_date + '</p>' +
                           '<p class="exf3">Captured By: ' + fileInfo.record_at + '</p>' +
                           '</div></div>';
            // Add additional fields as needed
        });
        htmlContent += '';

        // Append new data to the existing content
        document.getElementById('cammed-results').innerHTML = htmlContent;

         // Update displayedData with the new data
        displayedData = filesData;
        // Show the patient-files content
            document.getElementById('cammed-results').style.display = 'flex';
        };
        // Set the src attribute to trigger the onload event
            preloadedImages.src = newFilesData[0].picts; // Use the first image as an example
    };

    // Event listener for errors (optional)
    eventSource.onerror = function(event) {
        console.error('EventSource failed:', event);
        eventSource.close();
    };

    // Close the EventSource when the page is closed or refreshed
    window.onbeforeunload = function() {
        eventSource.close();
    };
    // Function to toggle full-screen mode for an image
    function toggleFullScreen(img) {
        var modal = document.getElementById('imageModal');
        var fullScreenImg = document.getElementById('fullScreenImage');

        // Set the image source in the modal
        fullScreenImg.src = img.src;

        // Toggle the display of the modal
        modal.style.display = (modal.style.display === 'none' || modal.style.display === '') ? 'flex' : 'none';
    }
    // Function to close full-screen image
    function closeFullScreenImage() {
        // Hide the modal
        document.getElementById('imageModal').style.display = 'none';
    }
    
</script>


<script>
    <?php $record_id = preg_replace('/[^a-zA-Z0-9-]/', '', (int)$_GET['id']); ?>
 const dataContainerAudio = document.getElementById('audiomed-results');
        // Function to initialize the SSE connection
        function initializeSSE() {
           
            var eventSourceAudio = new EventSource('http://localhost/mPanel/live/live-patient-audio.php?id=<?php echo $record_id; ?>');

            eventSourceAudio.onmessage = (event) => {
                const recordsAudio = JSON.parse(event.data);
                displayRecords(recordsAudio);
            };

            eventSourceAudio.onerror = (error) => {
                console.error('eventSourceAudio failed:', error);
                eventSourceAudio.close();
            };
        }
       

         // Function to display records in the container
        function displayRecords(recordsAudio) {
            dataContainerAudio.innerHTML = ''; // Clear previous recordsAudio

            recordsAudio.forEach(record => {
                const recordDiv = document.createElement('div');
                recordDiv.innerHTML = `
                    <p class="exa1"><audio controls src="${record.files}"></audio><br><small>${record.device_type} Sound</small></p><br>
                <p class="exa2">Record Date: ${record.record_date}</p>
                <p class="exa3">Record By: ${record.record_by}</p>
                <hr>
            `;

                dataContainerAudio.appendChild(recordDiv);
            });
        }

        // Initialize SSE connection on page load
        initializeSSE();
</script>