<?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 class="pdfbtndownload btn-group" role="group" aria-label="Patient Profile">
                              <a class="wawaiforcebtn btn btn-outline-success" type="button" id="btngenpdf"><i class="fa fa-file-pdf-o"></i>Generate PDF</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>
                      
                      </form>
                    </div>
                  </div>
                </div>
                <div class="col-xl-8">
                  <form class="card">
                    <div class="card-header">
                      <h4 class="card-title mb-0">Vitals <button class="btn btn-pill btn-primary btn-sm pull-right" type="button" id="get_data_vitals"><i data-feather="radio"></i> Get Data</button></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-vitals" style="display:none;">
                                <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;">
                                    <div class="loader-box loading-indicator" id="vitalsloading" style="display:none;">
                                      <div class="loader-7"></div>
                                    </div>
                                </tbody>
                            </table>
                        </div>
                        <div id="senderror-vitals" class="alert alert-danger dark alert-dismissible fade show" role="alert" style="display:none;"><i data-feather="alert-triangle"></i>
                          <p id="error-vitals"> </p>
                          <button class="btn-close" type="button" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    </div>
                    
                  </form>
                  
                </div>
                <div class="col-xl-12">
                  <div class="card">
                    <div class="card-header">
                      <h4 class="card-title mb-0">Audio <button class="btn btn-pill btn-primary btn-sm pull-right" type="button" id="get_data_audio"><i data-feather="radio"></i> Get Data</button></h4>
                    </div>
                    <div class="card-body">
                      <div class="loader-box loading-indicator" id="audioloading" style="display:none;">
                        <div class="loader-7"></div>
                      </div>
                      <div id="audiomed-results">
                      
                      </div>
                      <div id="senderror-audio" class="alert alert-danger dark alert-dismissible fade show" role="alert" style="display:none;"><i data-feather="alert-triangle"></i>
                          <p id="error-audio"> </p>
                          <button class="btn-close" type="button" data-bs-dismiss="alert" aria-label="Close"></button>
                      </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 <button class="btn btn-pill btn-primary btn-sm pull-right" type="button" id="get_data_picts"><i data-feather="radio"></i> Get Data</button></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 class="loader-box loading-indicator" id="pictsloading" style="display:none;">
                        <div class="loader-7"></div>
                      </div>
                      <div id="cammed-results">
                        
                      </div>
                      <div id="senderror-picts" class="alert alert-danger dark alert-dismissible fade show" role="alert" style="display:none;"><i data-feather="alert-triangle"></i>
                          <p id="error-picts"> </p>
                          <button class="btn-close" type="button" data-bs-dismiss="alert" aria-label="Close"></button>
                      </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 src="PatientDetails/dompdf/autoload.inc.php"></script>
     <script>
        document.getElementById('btngenpdf').addEventListener('click', function() {
            // Retrieve the recordId using the getParameterByName function
            var recordId = getParameterByName('id');

            // Ensure recordId is not empty
            if (recordId.trim() === "") {
                alert("Please enter a Record ID.");
                return;
            }

            // Send an Ajax request to get patient record data
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'http://localhost/mPanel/PatientDetails/genpdf.php?id=' + recordId, true);
            xhr.responseType = 'blob';
                                    // Set up the onreadystatechange event handler
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) { // Check if the request is complete
                    if (xhr.status == 200) { // Check if the request was successful
                        // Extract filename from the Content-Disposition header
                        var filename = getFilenameFromHeader(xhr.getResponseHeader('Content-Disposition'));

                        // Create a blob URL for the PDF data
                        var blob = new Blob([xhr.response], { type: 'application/pdf' });
                        var url = URL.createObjectURL(blob);

                        // Create a link element to trigger the download
                        var link = document.createElement('a');
                        link.href = url;
                        link.download = filename; // Set the filename dynamically

                        // Append the link to the document and trigger the click event
                        document.body.appendChild(link);
                        link.click();

                        // Remove the link from the document
                        document.body.removeChild(link);
                    } else {
                        console.log('Error: ' + xhr.status);
                    }
                }
            };

            // Send the request
            xhr.send();
        });

        // Function to extract filename from the Content-Disposition header
        function getFilenameFromHeader(header) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(header);
            if (matches != null && matches[1]) {
                return matches[1].replace(/['"]/g, '');
            }
            return 'output.pdf'; // Default filename if not found in the header
        }
        // Function to extract a parameter value from the URL
        function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }
    </script>

<script>

  // 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';
    }

      //Vitals
      $(document).ready(function () {
            // DataTable instance
            var dataTable = null;

            // Handle button click using Ajax
            $('#get_data_vitals').click(function (e) {
                e.preventDefault(); // Prevent the default form submission behavior

                // Get the record ID from the current URL
                var recordId = getParameterByName('id');

                // Show loading indicator
                $('#vitalsloading').css("display", "block");

                $.ajax({
                    type: 'POST',
                    url: 'http://localhost/mPanel/PatientDetails/vitals.php?id=' + recordId, // Pass the record ID in the URL
                    data: { get_data: true },
                    success: function (response) {
                        // Parse the JSON response
                        var data = JSON.parse(response);

                        // Clear existing DataTable instance
                        if (dataTable !== null) {
                            dataTable.destroy();
                            dataTable = null;
                        }

                        // Initialize DataTables
                        dataTable = $('#patient-vitals').DataTable({
                            data: data,
                            columns: [
                                { data: 'vbp' },
                                { data: 'vtemp' },
                                { data: 'vresp' },
                                { data: 'vhr' },
                                { data: 'vweight' },
                                { data: 'vsot' }
                                // Add more columns as needed
                            ]
                        });

                        // Hide loading indicator 
                        $('#vitalsloading').css("display", "none");
                        $('#patient-vitals').css("display", "table");
                    },
                    error: function (error) {
                      $("#senderror-vitals").css("display", "block");
                        $('#error-vitals').text('Error: ' + error.responseText);
                        // Hide loading indicator in case of an error
                        $('#vitalsloading').css("display", "none");
                    }
                });
            });

            // Function to get URL parameter by name
            function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
                var results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            }
        });

        //Audio
        $(document).ready(function () {
            // Function to handle button click using Ajax
            $('#get_data_audio').click(function (e) {
                e.preventDefault(); // Prevent the default form submission behavior

                // Get the record ID from the current URL
                var recordId = getParameterByName('id');

                // Show loading indicator
                $('#audioloading').css("display", "block");

                $.ajax({
                    type: 'POST',
                    url: 'http://localhost/mPanel/PatientDetails/audio.php?id=' + recordId, // Pass the record ID in the URL
                    data: { get_data: true },
                    success: function (response) {
                        // Parse the JSON response
                        var data = JSON.parse(response);

                        // Clear existing content
                        $('#audiomed-results').empty();

                        // Display device_type, record_date, and record_by as <p> elements
                        for (var i = 0; i < data.length; i++) {
                            var audioElement = '<div><p class="exa1">' + '<audio controls src="' + data[i].files + '"></audio>' + '<small>' + data[i].device_type + '</small>' + '</p>' + '<p class="exa2">Record Date: ' + data[i].record_date + '</p>' + '<p class="exa3">Record By: ' + data[i].record_by + '</p></div>';
                            $('#audiomed-results').append(audioElement);
                        }

                        // Hide loading indicator
                        $('#audioloading').css("display", "none");
                    },
                    error: function (error) {
                        $("#senderror-audio").css("display", "block");
                        $('#error-audio').text('Error: ' + error.responseText);
                        // Hide loading indicator in case of an error
                        $('#audioloading').css("display", "none");
                    }
                });
            });

            // Function to get URL parameter by name
            function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
                var results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            }
        });

        //Picts
        $(document).ready(function () {
            // Function to handle button click using Ajax
            $('#get_data_picts').click(function (e) {
                e.preventDefault(); // Prevent the default form submission behavior

                // Get the record ID from the current URL
                var recordId = getParameterByName('id');

                // Show loading indicator
                $('#pictsloading').css("display", "block");

                $.ajax({
                    type: 'POST',
                    url: 'http://localhost/mPanel/PatientDetails/Picts.php?id=' + recordId, // Pass the record ID in the URL
                    data: { get_data: true },
                    success: function (response) {
                        // Parse the JSON response
                        var data = JSON.parse(response);

                        // Clear existing content
                        $('#cammed-results').empty();

                        // Display device_type, record_date, and record_by as <p> elements
                        for (var i = 0; i < data.length; i++) {
                            var pictsElement = '<div class="excamresult">' + '<img src="' + data[i].picts + '" onclick="toggleFullScreen(this)">' + '<p class="exf1">' + data[i].device_type + '</p>' + '<p class="exf2">Record Date: ' + data[i].record_date + '</p>' + '<p class="exf3">Record By: ' + data[i].record_at + '</p></div>';
                            $('#cammed-results').append(pictsElement);
                        }

                        // Hide loading indicator
                        $('#pictsloading').css("display", "none");
                    },
                    error: function (error) {
                        $("#senderror-picts").css("display", "block");
                        $('#error-picts').text('Error: ' + error.responseText);
                        // Hide loading indicator in case of an error
                        $('#pictsloading').css("display", "none");
                    }
                });
            });

            // Function to get URL parameter by name
            function getParameterByName(name) {
                name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
                var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
                var results = regex.exec(location.search);
                return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
            }
        });
  </script>
