<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("dbConfig.php");
session_start();
if (isset($_SESSION['username']) && isset($_SESSION['name'])) {
  $username = $_SESSION['username'];
  $name = $_SESSION['name'];
} else {
  echo '<META http-equiv="refresh" content="0;logout.php">';
  exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    if (isset($_POST['SlNo']) && isset($_POST['Amount'])) {
      $slNo = $_POST['SlNo'];
      $amount = $_POST['Amount'];

      $updateQuery = "UPDATE examination SET Amount = ? WHERE SlNo = ?";
      $stmt = $db->prepare($updateQuery);
      $stmt->bind_param("di", $amount, $slNo);

      if ($stmt->execute()) {
        echo "<script>alert('Amount updated successfully')</script>";
      } else {
        echo "Error updating amount: " . $stmt->error;
      }
      exit;
    } else {
      echo "Invalid request parameters";
      exit;
    }
  }
}

// Function to convert number to Indian currency format
function getIndianCurrency(float $number)
{
  $decimal = round($number - ($no = floor($number)), 2) * 100;
  $hundred = null;
  $digits_length = strlen($no);
  $i = 0;
  $str = array();
  $words = array(
    0 => '',
    1 => 'one',
    2 => 'two',
    3 => 'three',
    4 => 'four',
    5 => 'five',
    6 => 'six',
    7 => 'seven',
    8 => 'eight',
    9 => 'nine',
    10 => 'ten',
    11 => 'eleven',
    12 => 'twelve',
    13 => 'thirteen',
    14 => 'fourteen',
    15 => 'fifteen',
    16 => 'sixteen',
    17 => 'seventeen',
    18 => 'eighteen',
    19 => 'nineteen',
    20 => 'twenty',
    30 => 'thirty',
    40 => 'forty',
    50 => 'fifty',
    60 => 'sixty',
    70 => 'seventy',
    80 => 'eighty',
    90 => 'ninety'
  );
  $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');
  while ($i < $digits_length) {
    $divider = ($i == 2) ? 10 : 100;
    $number = floor($no % $divider);
    $no = floor($no / $divider);
    $i += $divider == 10 ? 1 : 2;
    if ($number) {
      $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
      $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
      $str[] = ($number < 21) ? $words[$number] . ' ' . $digits[$counter] . $plural . ' ' . $hundred : $words[floor($number / 10) * 10] . ' ' . $words[$number % 10] . ' ' . $digits[$counter] . $plural . ' ' . $hundred;
    } else $str[] = null;
  }
  $Rupees = implode('', array_reverse($str));
  $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
  return ($Rupees ? $Rupees . ' Rupees ' : '') . $paise;
}

// Retrieve data from the examination table
$patId = isset($_GET['PatId']) ? $_GET['PatId'] : null;
if (!$patId) {
  echo "Patient ID is required.";
  exit();
}

$patientQuery = "
    SELECT PatId AS PatientId, title, Name, Contact, Email, Dob, Age, Gender, BloodGroup, Address, Consultant, AdmitDate, AdmitTime, 'IPD' AS PatientType
    FROM patientdetails 
    WHERE PatId = ?
    UNION
    SELECT PatientId, NULL AS title, Name, Contact, Email, NULL AS Dob, Age, Gender, NULL AS BloodGroup, Address, Consultant, admitDate AS AdmitDate, NULL AS AdmitTime, 'OPD' AS PatientType
    FROM opdpatientregister 
    WHERE PatientId = ?
";

$stmt = $db->prepare($patientQuery);
$stmt->bind_param("ss", $patId, $patId);
$stmt->execute();
$patientResult = $stmt->get_result();

if (mysqli_num_rows($patientResult) != 0) {
  $patientData = mysqli_fetch_assoc($patientResult);
  $title = $patientData['title'] ?? 'N/A';
  $Pname = $patientData['Name'] ?? 'N/A';
  $contact1 = $patientData['Contact'] ?? 'N/A';
  $email = $patientData['Email'] ?? 'N/A';
  $dob = $patientData['Dob'] ?? 'N/A';
  $age = $patientData['Age'] ?? 'N/A';
  $gender = $patientData['Gender'] ?? 'N/A';
  $blood = $patientData['BloodGroup'] ?? 'N/A';
  $Address = $patientData['Address'] ?? 'N/A';
  $Consultant = $patientData['Consultant'] ?? 'N/A';
  $PatientType = $patientData['PatientType'];
  $AdmitDate = $patientData['AdmitDate'] ?? $patientData['admitDate'];
  $AdmitTime = $patientData['AdmitTime'] ?? ' ';
} else {
  echo "No patient found with the provided ID.";
  exit();
}

$billNo = $_GET['billNo'];
$examQuery = "SELECT * FROM examination WHERE BillNo='$billNo'";
$examResult = mysqli_query($db, $examQuery);
?>
<!DOCTYPE html>
<html>

<head>
  <title>

  </title>
  <meta charset="UTF-8">
  <link href="assets/img/favicon.png" rel="icon">
  <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css'>
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Raleway:300,400,500,700,800|Montserrat:300,400,700" rel="stylesheet">
  <link href='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>
  <link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css'>

  <!-- Vendor CSS Files -->
  <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="assets/vendor/ionicons/css/ionicons.min.css" rel="stylesheet">
  <link href="assets/vendor/animate.css/animate.min.css" rel="stylesheet">
  <link href="assets/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet">
  <link href="assets/vendor/venobox/venobox.css" rel="stylesheet">
  <link href="assets/vendor/owl.carousel/assets/owl.carousel.min.css" rel="stylesheet">
  <link href="assets/vendor/boxicons/css/boxicons.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <script src="jquery.dependent.fields.js"></script>
  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <script src="jquery.dependent.fields.js"></script>
  <style>
  @media print {
    .action-column, .edit-btn, .save-btn, .cancel-btn {
      display: none;
    }
  }
</style>
  <style>
    .finaltable {
      border-top: 1px solid black;
      border: 1px solid black;
    }

    .finaltable th {
      border-top: 1px solid black;
      border: 1px solid black;
    }

    .finaltable td {
      border-top: 1px solid black;
      border: 1px solid black;
    }

    .finaltable thead tr {
      border-bottom: 3px solid black;

    }

    @media print {
      #printPageButton {
        display: none;
      }
    }

    .spanfont {
      font-size: 20px;
    }
  </style>
</head>

<body>

  <section>

    <div class="row" id="printPageButton" style="margin:5%">
      <button type="button" class="btn btn-primary" onclick="window.print()">Print</button> &nbsp;&nbsp;&nbsp;
      <a href="index.php"><button type="button" class="btn btn-primary">Home</button></a>
    </div>

    <div style="margin:5%">
      <div class="row">
        <div class="col-md-6 col-sm-6">
          <img src="assets/img/logo.png">
          <span class="spanfont"><b>Vidhyaranya Hospital PVT LTD.</b></span>
        </div>

        <div class="col-md-6 col-sm-6">
          <table>
            <tr>
              <td valign="top">Address</td>
              <td>:2876, 4th Cross, NS Road, Chamundipuram, Mysuru, Karnataka 570004</td>
            </tr>
            <tr>
              <td valign="top">Website</td>
              <td>:www.vidhyaranya</td>
            </tr>
            <tr>
              <td valign="top">Contact</td>
              <td>:+91-821 233 1655</td>
            </tr>
            <tr>
              <td>Unit</td>
              <td>:Mysore</td>
            </tr>

          </table>
        </div>
      </div>


      <div class="row text-center mt-3">
        <div class="col-md-12">
          <label style="font-size:15pt"><b>IN PATIENT BILL</b></label>
        </div>
      </div>
      <hr>


      <div class="row d-flex justify-content-between">
        <div class="col-md-6 col-sm-6 row1 text-left">
          <hr />
          <table>
            <tr>
              <td valign="top">Patient Id</td>
              <td valign="top">: <?php echo $patId; ?></td>
            </tr>
            <tr>
              <td valign="top">Name</td>
              <td valign="top">: <?php echo $title . ' ' . $Pname; ?></td>
            </tr>
            <tr>
              <td valign="top">Contact</td>
              <td valign="top">: <?php echo $contact1; ?></td>
            </tr>
            <?php if ($email != "") { ?>
              <tr>
                <td valign="top">Email Id</td>
                <td valign="top">: <?php echo $email; ?></td>
              </tr>
            <?php } ?>
            <tr>
              <td valign="top">Address: </td>
              <td valign="top"> : <?php echo $Address; ?></td>
            </tr>
          </table>
        </div>
        <div class="col-md-6 col-sm-6 row2">
          <table>
            <hr />
            <tr>
              <td valign="top">Gender/Age/Blood Group</td>
              <td valign="top">: <?php echo $gender . "/ " . $age . " / " . $blood; ?></td>
            </tr>
            <tr>
              <td valign="top">Consultant</td>
              <td valign="top">: <?php echo $Consultant; ?></td>
            </tr>
            <tr>
              <td valign="top">Patient Type</td>
              <td valign="top">: <?php echo $PatientType; ?></td>
            </tr>
            <tr>
              <td valign="top"><?php if ($PatientType === 'IPD') {
                                  echo "Admit Date/Time";
                                } else {
                                  echo "Admit Date";
                                } ?></td>
              <td valign="top">: <?php
                                  if ($PatientType === 'IPD') {
                                    echo $AdmitDate . ", " . $AdmitTime;
                                  } else {
                                    echo $AdmitDate;
                                  }
                                  ?></td>
            </tr>
          </table>
        </div>
      </div>

      <br /><br />
      <table class="table table-hover finaltable">
        <thead>
          <th scope="col">Sl No.</th>
          <th scope="col">Particulars</th>
          <th scope="col">Consultant</th>
          <th scope="col">Department</th>
          <th scope="col">Amount</th>
          <th scope="col"  class="action-column">Action</th>
        </thead>
        <tbody>
          <?php
          $i = 1;
          $totalAmount = 0;
          while ($row = mysqli_fetch_assoc($examResult)) {
            $slNo = $row['SlNo'];
            $particulars = $row['Particulars'];
            $consultant = $row['consultant'];
            $dateTime = $row['created_at'];
            $department = $row['optionlab'];
            $amount = $row['Amount'];
            $totalAmount += $amount;
            echo "<tr id='row-$slNo''><td>$i</td>";
            echo "<td>$particulars</td>";
            echo "<td>$consultant</td>";
            echo "<td>$department</td>";
            echo "<td><span class='amount-text'>$amount</span>
                      <input type='text' class='amount-input' value='$amount' style='display:none;'>
                  </td>";
            echo "<td class='action-column'>
                    <button class='edit-btn' onclick='editAmount($slNo)'>Edit</button>
                    <button class='save-btn' onclick='saveAmount($slNo)' style='display:none;'>Save</button>
                    <button class='cancel-btn' onclick='cancelEdit($slNo)' style='display:none;'>Cancel</button>
                  </td></tr>";
            $i++;
          }
          ?>
          <tr>
            <td colspan="4" style="text-align:right;"><strong>Total Amount</strong></td>
            <td><strong><?php echo $totalAmount; ?></strong></td>
          </tr>
        </tbody>
      </table>

      <br>
      <div>
        <h6 style="font-weight:bold"><?php echo getIndianCurrency($totalAmount) . " only/-"; ?></h6>
      </div>
      <div class="row mt-5">
        <div class="col-md-3">
        </div>
        <div class="col-md-6"></div>
        <div class="col-md-3">
          Authorized Signatory</h6>
          <br><br>
          <h6>Prepared by <?php echo $name ?></h6>
        </div>
      </div>


    </div>
  </section>
  <script>
  
    function editAmount(slNo) {
      // Attempt to select and modify each element, with console logging for troubleshooting
      let amountText = document.querySelector(`#row-${slNo} .amount-text`);
      let amountInput = document.querySelector(`#row-${slNo} .amount-input`);
      let editBtn = document.querySelector(`#row-${slNo} .edit-btn`);
      let saveBtn = document.querySelector(`#row-${slNo} .save-btn`);
      let cancelBtn = document.querySelector(`#row-${slNo} .cancel-btn`);

      if (amountText) {
        amountText.style.display = 'none';
      } else {
        console.log(`Element #row-${slNo} .amount-text not found`);
      }

      if (amountInput) {
        amountInput.style.display = 'inline-block';
      } else {
        console.log(`Element #row-${slNo} .amount-input not found`);
      }

      if (editBtn) {
        editBtn.style.display = 'none';
      } else {
        console.log(`Element #row-${slNo} .edit-btn not found`);
      }

      if (saveBtn) {
        saveBtn.style.display = 'inline-block';
      } else {
        console.log(`Element #row-${slNo} .save-btn not found`);
      }

      if (cancelBtn) {
        cancelBtn.style.display = 'inline-block';
      } else {
        console.log(`Element #row-${slNo} .cancel-btn not found`);
      }
    }


    function cancelEdit(slNo) {
      const input = document.querySelector(`#row-${slNo} .amount-input`);
      const amountText = document.querySelector(`#row-${slNo} .amount-text`).innerText;
      input.value = amountText;

      document.querySelector(`#row-${slNo} .amount-text`).style.display = 'inline-block';
      input.style.display = 'none';
      document.querySelector(`#row-${slNo} .edit-btn`).style.display = 'inline-block';
      document.querySelector(`#row-${slNo} .save-btn`).style.display = 'none';
      document.querySelector(`#row-${slNo} .cancel-btn`).style.display = 'none';
    }

    function saveAmount(slNo) {
      const newAmount = document.querySelector(`#row-${slNo} .amount-input`).value;

      // AJAX to save the updated amount
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "", true);
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); // Add this to distinguish AJAX request
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            try {
              const response = xhr.responseText;
              console.log(response); // Log the server response for debugging

              // Update the amount text and reset button visibility
              document.querySelector(`#row-${slNo} .amount-text`).innerText = newAmount;
              document.querySelector(`#row-${slNo} .amount-text`).style.display = 'inline-block';
              document.querySelector(`#row-${slNo} .amount-input`).style.display = 'none';
              document.querySelector(`#row-${slNo} .edit-btn`).style.display = 'inline-block';
              document.querySelector(`#row-${slNo} .save-btn`).style.display = 'none';
              document.querySelector(`#row-${slNo} .cancel-btn`).style.display = 'none';

              // Show alert and reload the page
              alert("Amount updated successfully!");
              location.reload(); // Reload the page
            } catch (error) {
              console.error("Error processing response:", error);
              alert("An error occurred while updating the amount.");
            }
          } else {
            console.error("HTTP Error:", xhr.status);
            alert("Failed to update amount. Please try again.");
          }
        }
      };
      xhr.send("SlNo=" + slNo + "&Amount=" + newAmount);
    }
  </script>

  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js'></script>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
  <script src="assets/vendor/jquery/jquery.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/jquery.easing/jquery.easing.min.js"></script>
  <script src="assets/vendor/php-email-form/validate.js"></script>
  <script src="assets/vendor/wow/wow.min.js"></script>
  <script src="assets/vendor/venobox/venobox.min.js"></script>
  <script src="assets/vendor/owl.carousel/owl.carousel.min.js"></script>
  <script src="assets/vendor/jquery-sticky/jquery.sticky.js"></script>
  <script src="assets/vendor/superfish/superfish.min.js"></script>
  <script src="assets/vendor/hoverIntent/hoverIntent.js"></script>
  <script src="assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
  <script src="assets/js/main.js"></script>
</body>

</html>