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

?>
<!DOCTYPE html>
<html>

<head>
  <title>Generate Discharge Bill</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://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
  <script src='https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.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">

  <!-- 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="jquery.dependent.fields.js"></script>
  <!-- Template Main CSS File -->
  <link href="assets/css/style.css" rel="stylesheet">
  <style type="text/css">
    .nav-menu a {
      padding: 3px 3px;
    }

    .footer {
      position: fixed;
      left: 0;
      bottom: 0;
      width: 100%;
      background-color: #efe8e8;
      color: black;
      text-align: center;
      padding: 4px;
      font-size: 12px;
    }

    .footer a {
      font-weight: bold;
      color: #0c0c67;
    }

    .hide {
      display: none;
    }

    h4 {
      padding-top: 5px;
      padding-bottom: 0px;
      color: #1abfbf;
      font-weight: bold;
    }

    hr {
      background-color: #1abfbf;
    }

    span {
      color: red;
    }
  </style>
</head>

<body>
  <div style="text-align: center">
    <img src="assets/img/logo.png" width="100px" height="100px">
  </div>
  <header id="header">

    <div class="container">
      <nav id="nav-menu-container">
        <ul class="nav-menu">
          <li class="menu-active">
            <a class="nav-link" style="padding:2;font-size:14px" href="index.php">Home</a>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#">IPD Patients</a>
            <ul>
              <li><a href="AddPatient.php">IPD Patient Registration</a></li>
              <li><a href="AddAdvance.php">IPD add Advance</a></li>
              <li><a href="UpdateWard.php">Update Ward</a></li>
              <li><a href="IPDPatients.php">View IPD Patients</a></li>
            </ul>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#">OPD Patients</a>
            <ul>
              <li><a href="OPDRegistration.php">OPD Patient Registration</a></li>
              <li><a href="OPDPatients.php">View OPD Patients</a></li>
            </ul>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#">Staff</a>
            <ul>
              <li><a href="AddStaff.php">Add Staff</a></li>
              <li><a href="StaffList.php">Staff List</a></li>
            </ul>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#">Billing</a>
            <ul>
              <li><a href="billingId.php">Generate Consolidate Bill</a></li>
              <li><a href="InvestigationId.php">Generate Investigation Bill</a></li>
              <li><a href="FinaleBillId.php">Generate Discharge Bill</a></li>
              <li><a href="SearchBill.php">Search Bill</a></li>
            </ul>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#">Particular</a>
            <ul>
              <li><a href="AddParticulars..php">Add Particulars</a></li>
              <li><a href="ViewParticulars.php">View Particulars</a></li>
            </ul>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#">Report</a>
            <ul>
              <li><a href="UploadReport.php">Upload Patient Report</a></li>
              <li><a href="DailyTrans.php">Transactions</a></li>
              <li><a href="userTrans.php">User Transactions</a></li>
              <li><a href="ViewReport.php">View Patient Reports</a></li>
            </ul>
          </li>
          <li class="menu-has-children">
            <a class="nav-link" style="padding:2;font-size:14px" href="#" style="font-size:15px"><?php echo $name ?></a>
            <ul>
              <li><a href="logout.php">Logout</a></li>
              <li><a href="ResetPassword.php">Reset Password</a></li>
            </ul>
          </li>
        </ul>
      </nav><!-- #nav-menu-container -->
    </div>
  </header><!-- End Header -->
  <section>
    <div class="row">
      <div class="col-md-3"></div>
      <div class="col-md-6">
        <div class="shadow p-3 mb-5 bg-light rounded">
          <form method="POST" action="insuFinalBill.php" onsubmit="return validateForm()" name="checkForm">
            <h2 style="text-align: center;font-weight: bold;color:#fff;background-color: #279480;padding:10px;">Generate Discharge Bill</h2>
            <div class="row">
              <div class="form-group col">
                <label for="PatientId">Patient ID</label>
                <input class="form-control" type="text" name="FinalPatientId" id="PatientId" oninput="fetchPayableAmount()">
              </div>

              <p style="text-align:center;padding-top:5px">(or)</p>
              <div class="form-group col">
                <label for="contact">Phone Number</label>
                <input class="form-control" type="text" name="Finalcontact" id="con">
              </div>
            </div>
            <div class="form-group">
              <label for="TotalPayableAmount">Total Payable Amount</label>
              <input class="form-control" type="text" name="PayableAmount" id="TotalPayableAmount" readonly>
            </div>


            <div class="row" id="InsDetails">
              <div class="form-group col">
                <label for="InsuranceName">Insurance Name<span>*</span></label>
                <input class="form-control" type="text" name="InsuranceName" id="InsuranceName">
              </div>
              <div class="form-group col">
                <label for="InsuranceNo">Insurance No<span>*</span></label>
                <input class="form-control" type="text" name="InsuranceNo" id="InsuranceNo">
              </div>
            </div>

            <div class="row" id="InsDetails">
              <div class="form-group col">
                <label for="InsuranceAmt">Insurance Amount<span>*</span></label>
                <input class="form-control" type="text" name="InsuranceAmt" id="InsuranceAmt" oninput="calculateFinalPayable()">
              </div>
              <div class="form-group col">
                <label for="discount">Discount<span>*</span></label>
                <input class="form-control" type="text" name="discount" id="discount" oninput="calculateFinalPayable()">
              </div>
            </div>

            <div class="form-group">
              <label for="FinalPayableAmount">Final Payable Amount</label>
              <input class="form-control" type="text" name="FinalPayableAmount" id="FinalPayableAmount" readonly>
            </div>

            <div class="row">
              <div class="form-group col">
                <label for="disDate">Date<span>*</span></label>
                <input class="form-control" type="date" name="disDate" id="disDate" required>
              </div>
              <div class="form-group col">
                <label for="disTime">Time<span>*</span></label>
                <input class="form-control" type="time" name="disTime" id="disTime" required>
              </div>
            </div>

            <!-- Payment details section - will be shown/hidden based on final payable amount -->
            <div id="paymentDetailsSection" style="display:none;">
              <h4>Final Payment Details</h4>
              <hr>
              <div class="row">
                <div class="form-group col">
                  <label for="PaymentMode">Bill Type<span>*</span></label>
                  <select class="form-control" name="fbilltype" id="PaymentMode">
                    <option value="">Choose Option</option>
                    <option value="Cash">Cash</option>
                    <option value="Cash and UPI">Cash and UPI</option>
                    <option value="Card">Card</option>
                    <option value="UPI">UPI</option>
                    <option value="Cash and Card">Cash and Card</option>
                    <!-- <option value="Insurance">Insurance</option>-->
                    <option value="ABRK">ABARK</option>
                  </select>
                </div>
              </div>

              <div class="row" id="InsPaymentDetails" style="display:none;">
                <div class="form-group col">
                  <label for="InsurancePaymentName">Insurance Name<span>*</span></label>
                  <input class="form-control" type="text" name="InsurancePaymentName" id="InsurancePaymentName">
                </div>
                <div class="form-group col">
                  <label for="InsurancePaymentNo">Insurance No<span>*</span></label>
                  <input class="form-control" type="text" name="InsurancePaymentNo" id="InsurancePaymentNo">
                </div>
              </div>

              <div class="row" id="cardDetails" style="display:none;">
                <div class="form-group col">
                  <label for="bank">Bank Name<span>*</span></label>
                  <input class="form-control" type="text" name="bank">
                </div>
                <div class="form-group col">
                  <label for="cardno">Card No<span>*</span></label>
                  <input class="form-control" type="text" name="cardno" id="cardno">
                </div>
              </div>

              <div class="row" id="upiCashDetails" style="display:none;">
                <div class="form-group col">
                  <label for="upi">Upi Amount<span>*</span></label>
                  <input class="form-control" type="text" name="upi">
                </div>
                <div class="form-group col">
                  <label for="cash">Cash Amount<span>*</span></label>
                  <input class="form-control" type="text" name="cash" id="cash">
                </div>
              </div>

              <div id="cardCashDetails" style="display:none;">
                <div class="row">
                  <div class="form-group col">
                    <label for="bank-a">Bank Name<span>*</span></label>
                    <input class="form-control" type="text" name="bank-a">
                  </div>
                  <div class="form-group col">
                    <label for="cardno-a">Card No<span>*</span></label>
                    <input class="form-control" type="text" name="cardno-a">
                  </div>
                </div>
                <div class="row">
                  <div class="form-group col">
                    <label for="card-a">Card Amount<span>*</span></label>
                    <input class="form-control" type="text" name="card-a">
                  </div>
                  <div class="form-group col">
                    <label for="cash-a">Cash Amount<span>*</span></label>
                    <input class="form-control" type="text" name="cash-a" id="cash-a">
                  </div>
                </div>
              </div>

              <div class="row" id="upiDetails" style="display:none;">
                <div class="form-group col">
                  <label for="upiid">UPI Transaction ID<span>*</span></label>
                  <input class="form-control" type="text" name="upiid">
                </div>
              </div>
            </div>

            <button type="submit" class="btn btn-primary mt-3">Proceed</button>
          </form>
        </div>
      </div>
      <div class="col-md-3"></div>
    </div>
  </section>
  <div class="footer">
    &copy; Copyright 2024 All Rights Reserved <strong>Vidyaranya Hospital PVt LTD.</strong>. | Designed by <a href="http://www.vatsinsoft.in/">Vatsin Soft</a>
  </div>

  <script>
    // Calculate final payable amount based on total amount, insurance and discount
    function calculateFinalPayable() {
      var totalAmount = parseFloat(document.getElementById("TotalPayableAmount").value) || 0;
      var insuranceAmount = parseFloat(document.getElementById("InsuranceAmt").value) || 0;
      var discount = parseFloat(document.getElementById("discount").value) || 0;

      // Calculate final payable amount
      var finalPayable = totalAmount - insuranceAmount - discount;

      // If result is negative, set to 0
      finalPayable = Math.max(0, finalPayable);

      // Update the final payable amount field
      document.getElementById("FinalPayableAmount").value = finalPayable;

      // Show or hide the payment details section based on finalPayable amount
      var paymentDetailsSection = document.getElementById("paymentDetailsSection");
      if (finalPayable > 0) {
        paymentDetailsSection.style.display = "block";

        // Make payment mode required when section is visible
        document.getElementById("PaymentMode").setAttribute("required", "");
      } else {
        paymentDetailsSection.style.display = "none";

        // Remove required attribute when section is hidden
        document.getElementById("PaymentMode").removeAttribute("required");

        // Reset payment mode selection when hiding
        document.getElementById("PaymentMode").value = "";

        // Trigger change event to hide all payment method specific fields
        $("#PaymentMode").trigger("change");
      }
    }

    // Function to fetch payable amount from the server
    function fetchPayableAmount() {
      var patientId = document.getElementById("PatientId").value;

      if (patientId !== "") {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "getPayableAmount.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4 && xhr.status === 200) {
            if (xhr.responseText.trim() !== "") {
              document.getElementById("TotalPayableAmount").value = xhr.responseText.trim();
              calculateFinalPayable(); // Update final payable amount
            } else {
              document.getElementById("TotalPayableAmount").value = "No amount found";
              document.getElementById("FinalPayableAmount").value = "0.00";
              // Hide payment details section if no amount found
              document.getElementById("paymentDetailsSection").style.display = "none";
            }
          }
        };

        xhr.send("patientId=" + encodeURIComponent(patientId));
      } else {
        document.getElementById("TotalPayableAmount").value = "";
        document.getElementById("FinalPayableAmount").value = "";
        // Hide payment details section when patient ID is cleared
        document.getElementById("paymentDetailsSection").style.display = "none";
      }
    }

    // Form validation
    function validateForm() {
      var patientId = document.forms["checkForm"]["PatientId"].value;
      var contactNo = document.forms["checkForm"]["con"].value;
      var finalPayable = parseFloat(document.getElementById("FinalPayableAmount").value) || 0;

      // Check that either patient ID or phone number is entered
      if (patientId == "" && contactNo == "") {
        alert("Patient ID or Phone Number must be filled out");
        return false;
      }

      // If final payable amount is greater than 0, validate payment details
      if (finalPayable > 0) {
        var paymentMode = document.getElementById("PaymentMode").value;
        if (paymentMode == "") {
          alert("Please select a payment method");
          return false;
        }

        // Validate specific payment method fields based on selected payment mode
        if (paymentMode == "Insurance") {
          if (document.getElementById("InsurancePaymentName").value == "" ||
            document.getElementById("InsurancePaymentNo").value == "") {
            alert("Please fill in all insurance payment details");
            return false;
          }
        } else if (paymentMode == "Card") {
          if (document.querySelector('input[name="bank"]').value == "" ||
            document.querySelector('input[name="cardno"]').value == "") {
            alert("Please fill in all card details");
            return false;
          }
        } else if (paymentMode == "Cash and UPI") {
          if (document.querySelector('input[name="upi"]').value == "" ||
            document.querySelector('input[name="cash"]').value == "") {
            alert("Please fill in UPI and cash amounts");
            return false;
          }
        } else if (paymentMode == "Cash and Card") {
          if (document.querySelector('input[name="bank-a"]').value == "" ||
            document.querySelector('input[name="cardno-a"]').value == "" ||
            document.querySelector('input[name="card-a"]').value == "" ||
            document.querySelector('input[name="cash-a"]').value == "") {
            alert("Please fill in all card and cash details");
            return false;
          }
        } else if (paymentMode == "UPI") {
          if (document.querySelector('input[name="upiid"]').value == "") {
            alert("Please enter UPI transaction ID");
            return false;
          }
        }
      }

      return true;
    }

    // Initialize everything when document is ready
    $(document).ready(function() {
      // Set default values for insurance and discount
      $("#InsuranceAmt").val("0");
      $("#discount").val("0");

      // Handle payment mode changes
      $("#PaymentMode").change(function() {
        var paymentMode = $(this).val();

        // Hide all sections by default
        $('#InsPaymentDetails').hide();
        $('#cardDetails').hide();
        $('#upiCashDetails').hide();
        $('#upiDetails').hide();
        $('#cardCashDetails').hide();

        // Remove required attributes for all input fields
        $('#InsurancePaymentName, #InsurancePaymentNo').removeAttr('required');
        $('input[name="bank"], input[name="cardno"]').removeAttr('required');
        $('input[name="upi"], input[name="cash"]').removeAttr('required');
        $('input[name="upiid"]').removeAttr('required');
        $('input[name="card-a"], input[name="cash-a"], input[name="bank-a"], input[name="cardno-a"]').removeAttr('required');

        // Show relevant sections based on payment mode
        if (paymentMode == "Insurance") {
          $('#InsPaymentDetails').show();
          $('#InsurancePaymentName').attr('required', '');
          $('#InsurancePaymentNo').attr('required', '');
        } else if (paymentMode == "Card") {
          $('#cardDetails').show();
          $('input[name="bank"]').attr('required', '');
          $('input[name="cardno"]').attr('required', '');
        } else if (paymentMode == "Cash and UPI") {
          $('#upiCashDetails').show();
          $('input[name="upi"]').attr('required', '');
          $('input[name="cash"]').attr('required', '');
        } else if (paymentMode == "Cash and Card") {
          $('#cardCashDetails').show();
          $('input[name="card-a"], input[name="cash-a"], input[name="bank-a"], input[name="cardno-a"]').attr('required', '');
        } else if (paymentMode == "UPI") {
          $('#upiDetails').show();
          $('input[name="upiid"]').attr('required', '');
        }
      });

      // Set today's date as the default
      const today = new Date().toISOString().split('T')[0];
      document.getElementById('disDate').value = today;

      // Set current time as default
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      document.getElementById('disTime').value = `${hours}:${minutes}`;

      // Initial calculation to set correct visibility
      calculateFinalPayable();
    });
  </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>