<?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">';
}


if (isset($_POST['disDate'])) {
  $disDate = $_POST['disDate'];
  $disTime = $_POST['disTime'];
  $patientId = $_POST['FinalPatientId'];
  $contact = $_POST['Finalcontact'];
  $paymentmode = $_POST['paymentmode'];
  $insuranceAmt = $_POST['insuranceAmt'];
  $InsuranceName = $_POST['InsuranceName'];
  $InsuranceNo = $_POST['InsuranceNo'];
  $bank = $_POST['bank'] ?? '';
  $cardno = $_POST['cardno'] ?? '';
  $bank_a = $_POST['bank-a'] ?? '';
  $cardno_a = $_POST['cardno-a'] ?? '';
  $cash_a = $_POST['cash-a'] ?? '';
  $card_a = $_POST['card-a'] ?? '';
  $upi = $_POST['upi'];
  $cash = $_POST['cash'];
  $upiid = $_POST['upiid'];

  $query = mysqli_query($db, "SELECT * FROM patientdetails WHERE PatId='$patientId' OR Contact='$contact'");
  if (mysqli_num_rows($query) == 0) {
    echo "<script>alert('Incorrect Patient ID or Contact Number!')</script>";
    $url = "/Billing/FinaleBillId.php";
    echo "<meta http-equiv=\"refresh\" content=\"0;url=$url\" />";
  } else {




    while ($row = $query->fetch_assoc()) {
      $patid = $row['PatId'];
      $title = $row['title'];
      $Pname = $row['Name'];
      $contact1 = $row['Contact'];
      $email = $row['Email'];
      $dob = $row['Dob'];
      $age = $row['Age'];
      $gender = $row['Gender'];
      $blood = $row['BloodGroup'];
      $Address = $row['Address'];
      $Consultant = $row['Consultant'];
      $PatientType = $row['PatientType'];
      $CaseType = $row['CaseType'];
      $AdmitDate = $row['AdmitDate'];
      $AdmitTime = $row['AdmitTime'];
      $discount = $row['DiscountAmount'];
    }

    $advanceAmount = 0; // Initialize total advance amount
    $advances = []; // Array to store each record's details

    // Fetch advances
    // $advanceQuery = "SELECT SlNo, BillNo, PatId, Amount, AdvanceDate, advanceTime, PaymentMode, InsuranceName, InsuranceNo, bank, cardno, upi, cash, upiid, PreparedBy FROM advance WHERE PatId='$patid'";
    // $advanceResult = mysqli_query($db, $advanceQuery);

    // // Loop through results to sum up amounts and store each row
    // while ($row = $advanceResult->fetch_assoc()) {
    //   $advanceAmount += $row['Amount']; // Sum up the advance amounts
    //   $advances[] = $row; // Store each row in the array
    // }

    // Fetch other details if necessary (e.g., from the 'bill' table)
    // $res1 = mysqli_query($db, "SELECT * FROM bill WHERE PatientId='$patid'");
    // if (mysqli_num_rows($res1) != 0) {
    //   while ($row = $res1->fetch_assoc()) {
    //     $BillNo[] = $row['BillNo'];
    //   }
    // }
    
    
     $advanceQuery = "SELECT SlNo, BillNo, PatId, Amount, AdvanceDate, advanceTime, PaymentMode, InsuranceName, InsuranceNo, bank, cardno, upi, cash, upiid, PreparedBy FROM advance WHERE PatId='$patid' AND is_deleted=1";
$advanceResult = mysqli_query($db, $advanceQuery);

// Loop through results to sum up amounts and store each row
while ($row = $advanceResult->fetch_assoc()) {
    $advanceAmount += $row['Amount']; // Sum up the advance amounts
    $advances[] = $row; // Store each row in the array
}


    // Fetch other details if necessary (e.g., from the 'bill' table)
  $res1 = mysqli_query($db, "SELECT `BillId`, `BillNo`, `PatientId`, `PatientType`, `TotAmount`, `PaymentMode`, `BDate`, `BTime`, `PayableAmount`, `InsuranceName`, `InsuranceNo`, `bank`, `cardno`, `upi`, `cash`, `PreparedBy`, `upiid`, `cashamount`, `cardamount`, `is_deleted` FROM `bill` WHERE `PatientId`='$patid' AND is_deleted=1");

if (mysqli_num_rows($res1) != 0) {
    while ($row = $res1->fetch_assoc()) {
        $BillNo[] = $row['BillNo'];
    }
}

    // Fetch examination total
    // $examinationTotal = 0;
    // $examinationQuery = "SELECT SUM(Amount) AS TotalExaminationAmount 
    //                      FROM examination 
    //                      WHERE PatId='$patid'";
    // $examinationResult = mysqli_query($db, $examinationQuery);
    // if ($examinationResult->num_rows > 0) {
    //     $row = $examinationResult->fetch_assoc();
    //     $examinationTotal = $row['TotalExaminationAmount'] ?? 0;
    // }
    // $advanceAmount=0;
    // $advance=mysqli_query($db,"SELECT * FROM advance WHERE PatId='$patid'");
    // while($row=$advance->fetch_assoc()){
    //     $advanceAmount+=$row['Amount'];
    // }
    // $res1=mysqli_query($db,"SELECT * FROM bill where PatientId='$patid'");
    // if(mysqli_num_rows($res1)!=0){
    //   while($row=$res1->fetch_assoc()){
    //     $BillNo[]=$row['BillNo'];
    //   }
    // }

?>
    <!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 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;
        }
      </style>

    </head>

    <body>
      <section>
        <div class="row">
          <div class="col-md-1"></div>
          <div class="col-md-10">


            <div class="shadow p-3 mb-5 bg-light rounded">
              <div class="row">
                <div class="col-md-3">
                  <img src="assets/img/logo.png">
                </div>
                <div class="col-md-3"></div>
                <div class="col-md-6">
                  <table>
                    <tr>
                      <td valign="top">Address</td>
                      <td>:2876, 4th Cross, NS Road, Chamundipuram, Mysuru, Karnataka 570004</td>
                    </tr>
                  
                    <tr>
                      <td valign="top">Contact</td>
                      <td>:+91-821 233 1655, +91-821 233 0555, +91 9035933963</td>
                    </tr>
                    <tr>
                      <td>Unit</td>
                      <td>:Mysore</td>
                    </tr>

                  </table>
                </div>
              </div>
              <hr>
              <div class="row">
                <div class="col-md-6">
                  <table>
                    <tr>
                      <td valign="top"><b>Patient Id</b></td>
                      <td valign="top">:<b> <?php echo $patid; ?></b></td>
                    </tr>
                    <tr>
                      <td valign="top"><b>N<b>ame</b></td>
                      <td valign="top">: <b><?php echo $title . ' ' . $Pname; ?></b></td>
                    </tr>
                    <tr>
                      <td valign="top"><b>Contact No.</b></td>
                      <td valign="top">: <b><?php echo $contact1; ?></b></td>
                    </tr>
                    <?php if ($email != "") { ?>
                      <tr>
                        <td valign="top"><b>Email Id</b></td>
                        <td valign="top">: <?php echo $email; ?></td>
                      </tr>
                    <?php } ?>
                    <tr>
                      <td valign="top"><b>Address</b></td>
                      <td valign="top">: <?php echo $Address; ?></td>
                    </tr>

                  </table>
                </div>
                <div class="col-md-6">
                  <table>
                    <tr>
                      <td valign="top"><b>Gender/Age/Blood Group</b></td>
                      <td valign="top">: <?php echo $gender . " / " . $age . "  / "  . $blood; ?></td>

                    </tr>

                    <tr>
                      <td valign="top"><b>Consultant</b></td>
                      <td valign="top">: <b><?php echo $Consultant; ?></b></td>
                    </tr>
                    <tr>
                      <td valign="top"><b>Patient Type/Case Type</b></td>
                      <td valign="top">: <?php echo $PatientType . "/ " . $CaseType; ?></td>
                    </tr>
                    <tr>
                      <td valign="top"><b>Admit Date/Time</b></td>
                      <td valign="top">: <?php echo $AdmitDate . ", " . date('H:i A', strtotime($AdmitTime)); ?></td>
                    </tr>
                    <tr>
                      <td valign="top"><b>Discharge Status</b></td>
                      <td valign="top">:
                        <div class="form-check form-check-inline">
                          <input class="form-check-input" type="checkbox" name="is_died" id="is_died" value="1" <?php echo (isset($_POST['is_died']) && $_POST['is_died']) == 1 ? 'checked' : ''; ?>>
                          <label class="form-check-label" for="is_died">Patient <span class="text-danger">Expired</span></label>
                        </div>
                      </td>
                    </tr>
                    <tr>
                      <td valign="top"><b>Payment Mode/Discharge Date-Time</b></td>
                      <td valign="top">: <?php echo $paymentmode . " " . $disDate . ", " . date('H:i A', strtotime($disTime)); ?></td>
                    </tr>
                    <?php if ($paymentmode == "Insurance") {
                      echo "<tr><td><b>Insurance Name / Number</b></td>";
                      echo "<td>:$InsuranceName, $InsuranceNo</td></tr>";
                    }
                    if ($billtype == "Card") {
                      echo "<tr><td>Bank Name / Card Number</td>";
                      echo "<td>:$bank, $cardno</td></tr>";
                    }
                    if ($billtype == "Cash and UPI") {
                      echo "<tr><td>Cash Amount / UPI Amount</td>";
                      echo "<td>:$cash, $upi</td></tr>";
                    }
                    if ($billtype == "Cash and Card") {
                      echo "<tr><td>Card Amount / Cash Amount</td>";
                      echo "<td>:$card_a, $cash_a</td></tr>";
                    }
                    ?>
                  </table>
                </div>
              </div>
              <br>


              <table class="table table-hover">
                <thead>
                  <th scope="col">Sl No.</th>
                  <th scope="col">Particulars</th>
                  <th scope="col">Consultant</th>
                  <th scope="col">Quantity</th>
                  <th scope="col">Price</th>
                  <th scope="col">Amount</th>
                </thead>
                <tbody>
                  <?php
                  $j = 1;
                  $total = 0;
                  for ($bcount = 0; $bcount < (sizeof($BillNo)); $bcount++) {
                    $fetch = mysqli_query($db, "SELECT * FROM billparticulars where BillNo='$BillNo[$bcount]' AND BillNo RLIKE '^[VH/CB]' AND  is_deleted=1 ORDER BY particulars");
                    while ($row = $fetch->fetch_assoc()) {

                      echo "<tr><td>" . $j . "</td>";
                      echo "<td>" . $row['Particulars'] . "</td>";
                      echo "<td>" . $row['consultant'] . "</td>";
                      echo "<td>" . $row['Quantity'] . "</td>";
                      echo "<td>" . $row['UnitPrice'] . "</td>";
                      $amount = $row['Amount'];
                      echo "<td>" . $row['Amount'] . "</td>";
                      echo "</tr>";
                      $total += $amount;
                      $j++;
                    }
                  }
                  if ($advanceAmount != 0) {
                    $payable = $total - ($advanceAmount + $discount);
                  } else {
                    $payable = $total - $discount;
                  }
                  ?>

                  <tr>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td>Sub Total</td>
                    <td><?php echo $total; ?></td>
                  </tr>
                </tbody>
              </table>

              <div class="row">
                <div class="col-md-6">
                  <!-- HTML Table to display advances -->
                  <table class="table table-bordered patientamt">
                    <thead>
                      <tr>
                        <th>Bill Number</th>
                        <th>Advance Amount</th>
                        <th>Advance Date</th>
                        <!--<th>Time</th> <!-- New Time Column -->
                      </tr>
                    </thead>
                    <tbody>
                      <?php
                      // Check if there are any advances
                      if (empty($advances)) {
                        echo "<tr><td colspan='4'>No advance records found.</td></tr>";
                      } else {
                        // Display each record with BillNo, Amount, AdvanceDate, and Time
                        foreach ($advances as $advance) {
                          echo "<tr>";
                          echo "<td>" . htmlspecialchars($advance['BillNo']) . "</td>"; // Display BillNo
                          echo "<td>" . htmlspecialchars($advance['Amount']) . "</td>"; // Display Amount
                          echo "<td>" . htmlspecialchars($advance['AdvanceDate'] . ' ' . date('H:i A', strtotime($advance['advanceTime']))) . "</td>"; // Display AdvanceDate
                          // echo "<td>" . htmlspecialchars($advance['advanceTime']) . "</td>"; // Display Time
                          echo "</tr>";
                        }

                        // Display the total advance amount in a separate row
                        echo "<tr>";
                        echo "<td><strong>Total Amount</strong></td>";
                        echo "<td colspan='3'><strong>" . htmlspecialchars($advanceAmount) . "</strong></td>";
                        echo "</tr>";
                      }
                      ?>
                    </tbody>
                  </table>

                </div>
                <div class="col-md-6">
                  <?php
                  // $total = $examinationTotal + $subtotal; 
                  // if ($advanceAmount != 0) {
                  //     $payable = $total - ($advanceAmount + $discount); // Deduct advance and discount
                  // } else {
                  //     $payable = $total - $discount; // Deduct only discount
                  // }
                  ?>

                  <table class="table table-bordered">
                    <!--   <tr>-->
                    <!--    <td>Total Examination Amount</td>-->
                    <!--    <td><?php echo number_format($examinationTotal); ?></td>-->
                    <!--</tr>-->

                    <tr>
                      <td><b>Total Bill Amount</b></td>
                      <td><b><?php echo number_format($total); ?></b></td>
                    </tr>
                    <tr>
                    <tr>
                      <td>Advance Amount</td>
                      <td><?php echo number_format($advanceAmount); ?></td>
                    </tr>
                    <?php

                    // If negative, display the refund message and the absolute value
                    if ($payable < 0) {
                      $payableMessage = "Refund to Patient " . number_format(abs($payable));
                    } else {
                      $payableMessage = number_format($payable);
                    }
                    ?>
                    <tr>
                      <td><b>Patient Payable Amount</b></td>
                      <td><b><?php echo $payableMessage; ?></b></td>
                    </tr>
                  </table>


                </div>
              </div>
              <br><br><br><br>
              <div class="row">
                <div class="col-md-1"></div>
                <div class="col-md-7">



                </div>
                <div class="col-md-4">
                  <h6>Authorized Signatory</h6>
                  <br>
                  <h6>Prepared by <? echo $name ?></h6>

                </div>
              </div>
              <br><br><br><br>

            </div>
            <div class="col-md-1"></div>

          </div>
        </div>

        <form action="store.php" method="POST">
          <input type="hidden" name="FPatientId" value="<?php echo $patid; ?>">
          <input type="hidden" name="AdmitDate" value="<?php echo $AdmitDate; ?>">
          <input type="hidden" name="AdmitTime" value="<?php echo $AdmitTime; ?>">
          <input type="hidden" name="DischargeDate" value="<?php echo $disDate; ?>">
          <input type="hidden" name="DischargeTime" value="<?php echo $disTime; ?>">
          <input type="hidden" name="DiscountAmount" value="<?php echo $discount; ?>">
          <input type="hidden" name="FAdvanceAmount" value="<?php echo $advanceAmount; ?>">
          <input type="hidden" name="insuranceAmt" value="<?php echo $insuranceAmt; ?>">
          <input type="hidden" name="paymentmode" value="<?php echo $paymentmode; ?>">
          <input type="hidden" name="is_died" value="0">
          <input type="hidden" name="TotalAmount" value="<?php echo $total; ?>">
          <input type="hidden" name="PayableAmount" value="<?php echo $payable; ?>">
          <input type="hidden" name="preparedby" value="<?php echo $name; ?>">
          <input type="hidden" name="InsuranceName" value="<?php echo $InsuranceName; ?>">
          <input type="hidden" name="InsuranceNo" value="<?php echo $InsuranceNo; ?>">

          <input type="hidden" name="bank" value="<?php echo $bank; ?>">
          <input type="hidden" name="cardno" value="<?php echo $cardno; ?>">
          <input type="hidden" name="upi" value="<?php echo $upi; ?>">
          <input type="hidden" name="cash" value="<?php echo $cash; ?>">
          <input type="hidden" name="upiid" value="<?php echo $upiid; ?>">
          <input type="hidden" name="bank-a" value="<?php echo $bank_a; ?>">
          <input type="hidden" name="cardno-a" value="<?php echo $cardno_a; ?>">
          <input type="hidden" name="cash-a" value="<?php echo $cash_a; ?>">
          <input type="hidden" name="card-a" value="<?php echo $card_a; ?>">
          <div style="text-align:center">
            <button type="submit" class="btn btn-primary">Confirm and Generate Bill</button>
            <button type="button" class="btn btn-danger" onclick="history.back();">Cancel</button>
          </div>


        </form>

      </section>
      <script>
        $(document).ready(function() {
          $('#is_died').change(function() {
            $('input[name="is_died"]').val(this.checked ? '1' : '0');
          });
        });
      </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>
<?php

  }
}
?>