<?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($_GET['patientId'])) {

  $patientId = $_GET['patientId'];

  $query = mysqli_query($db, "SELECT * FROM patientdetails WHERE PatId='$patientId' OR Contact='$contact' AND `is_deleted` = 1 ");
  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 BillNo, Amount, and AdvanceDate

    // Fetch advances including AdvanceDate
    // Query to fetch advance records, including advanceTime
    $advanceQuery = "SELECT BillNo, Amount, AdvanceDate, advanceTime ,PaymentMode FROM advance WHERE PatId='$patid'  AND `is_deleted` = 1";
    $advanceResult = mysqli_query($db, $advanceQuery);

    // Initialize variables
    $advanceAmount = 0;
    $advances = []; // Ensure this is initialized to avoid undefined variable warnings

    // Loop through results to sum up amounts and store BillNo, Amount, AdvanceDate, and advanceTime
    while ($row = $advanceResult->fetch_assoc()) {
      $advanceAmount += $row['Amount']; // Sum up the advance amounts
      $advances[] = $row; // Store each row (BillNo, Amount, AdvanceDate, and advanceTime) in the array
    }
       $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'];
    // }

    $qbill = mysqli_query($db, "SELECT * FROM finalbill WHERE PatientId='$patientId'  AND `is_deleted` = 1");
    while ($row = $qbill->fetch_assoc()) {
      $total = $row['TotalAmount'];
      $insuranceAmt = $row['insuranceAmt'];
      $fdiscount = $row['DiscountAmount'];
      $advance = $row['AdvanceAmount'];
      $payablef = $row['PayableAmount'];
      $distime = $row['DischargeTime'];
      $FinalBillno = $row['FinalBillNo'];
      $disdate = $row['DischargeDate'];
      $paymentmode = $row['PaymentMode'];
      $InsuranceName = $row['InsuranceName'];
      $InsuranceNo = $row['InsuranceNo'];
      $bank = $row['bank'];
      $cardno = $row['cardno'];
      $upi = $row['upi'];
      $cash = $row['cash'];
    }



    $res1 = mysqli_query($db, "SELECT * FROM bill where PatientId='$patid'  AND `is_deleted` = 1");
    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">
        body {
          font-weight: bold;
        }

        .nav-menu a {
          padding: 3px 3px;
        }

        .patientde {
          border: 1px solid black;
        }

        .patientamt {
          border: 2px solid black;
        }

        .patientde tr td {
          border: 1px solid black;
        }

        .patientamt tr td {
          border: 2px solid black;
        }


        .patientde tr td {
          border: 1px solid black;
        }

        .patientde thead th {
          vertical-align: bottom !important;
          border: 1px solid black !important;
        }


        .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;
        }

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

        .table-bordered,
        .table-bordered th,
        .table-bordered td {
          border: 1px solid black !important;
        }

        .table-bordered th,
        .table-bordered td {
          padding: 8px;
          text-align: left;
        }
      </style>

    </head>

    <body>
      <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>
      <section>
        <div class="row">
          <div class="col-md-1"></div>
          <div class="col-md-10">



            <div class="row">
              <div class="col-md-6 col-sm-6">
                <h3> <img src="assets/img/logo.png" style="width:90px;">Vidyaranya Hospital PVt LTD</h3>
              </div>
              <!--<div class="col-md-1"></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">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>
            <div class="row">
              <div class="col-md-12 text-center">
                <?php if ($PatientType == "OPD") {
                  echo '<label style="font-size:15pt"><b>OUT PATIENT FIANL BILL</b></label>';
                } elseif ($PatientType == "IPD") {
                  echo '<label style="font-size:15pt"><b>IN PATIENT FINAL BILL</b></label>';
                } else {
                  echo '<label style="font-size:15pt"><b>PATIENT FIANL BILL</b></label>';
                }
                ?>
              </div>
            </div>
            <hr>
            <div class="row">
              <div class="col-md-6  col-sm-6">
                <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 No.</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">
                <table>
                  <tr>
                    <td valign="top">Gender/Age/Blood Group</td>
                    <td valign="top">: <?php echo $gender . "/ " . $age . " Years/ " . $blood; ?></td>
                  </tr>

                  <tr>
                    <td valign="top">Consultant</td>
                    <td valign="top">: <?php echo $Consultant; ?></td>
                  </tr>
                  <tr>
                    <td valign="top">Patient Type/Case Type</td>
                    <td valign="top">: <?php echo $PatientType . "/ " . $CaseType; ?></td>
                  </tr>
                  <tr>
                    <td valign="top">Admit Date/Time</td>
                    <td valign="top">: <?php echo $AdmitDate . ", " . $AdmitTime; ?></td>
                  </tr>
                  <tr>
                    <td valign="top">Payment Mode</td>
                    <td valign="top">: <?php echo  $paymentmode; ?></td>
                  </tr>
                  <tr>
                    <td valign="top">Discharge Date-Time</td>
                    <td valign="top">: <?php echo $disdate . ", " . $distime; ?></td>
                  </tr>
                  <?php if ($paymentmode == "Insurance") {
                    echo "<tr><td>Insurance Name</td>";
                    echo "<td>: $InsuranceName</td></tr>";
                    echo "<tr><td>Number</td>";
                    echo "<td>: $InsuranceNo</td></tr>";
                  }

                  if ($paymentmode == "Card") {
                    echo "<tr><td>Bank Name</td>";
                    echo "<td>: $bank</td></tr>";
                    echo "<tr><td>Card Number</td>";
                    echo "<td>: $cardno</td></tr>";
                  }
                  if ($paymentmode == "Cash and UPI") {
                    echo "<tr><td>Cash Amount</td>";
                    echo "<td>: $cash</td></tr>";
                    echo "<tr><td>UPI Amount</td>";
                    echo "<td>: $upi</td></tr>";
                  }
                  if ($paymentmode == "Cash and Card") {
                    echo "Bank Name: $bank<br>Card Number: $cardno";
                    echo "<tr><td>Cash Amount</td>";
                    echo "<td>: $cash_a</td></tr>";
                    echo "<tr><td>Card Amount</td>";
                    echo "<td>: $card_a</td></tr>";
                  }
                  ?>

                  <tr>
                    <td valign="top">Discharge Bill No</td>
                    <td valign="top">: <?php echo $FinalBillno; ?></td>
                  </tr>
                </table>
              </div>
            </div>
            <br>


            <table class="table table-hover patientde">
              <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 `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>

            <?php

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

            ?>


            <div class="row">
              <div class="col-md-6">

                <table class="table table-bordered patientamt" style="border:1px solid black !important">
                  <thead>
                    <tr>
                      <th>Bill Number</th>
                      <th>Advance Amount</th>
                      <th>PaymentMode</th>
                      <th>Advance Date</th>
                      <!--<th>Advance Time</th>-->
                      <!-- New column for Advance Time -->
                    </tr>
                  </thead>
                  <tbody>
                    <?php
                    // Check if there are any advances
                    if (empty($advances)) {
                      echo "<tr><td colspan='3'>No advance records found.</td></tr>"; // Adjust colspan to 4
                    } else {
                      // Display each BillNo with its corresponding Amount, AdvanceDate, and advanceTime
                      foreach ($advances as $advance) {
                        echo "<tr>";
                        echo "<td>" . htmlspecialchars($advance['BillNo']) . "</td>"; // Display BillNo
                        echo "<td>" . htmlspecialchars($advance['Amount']) . "</td>"; 
                          echo "<td>" . htmlspecialchars($advance['PaymentMode']) . "</td>";
                        echo "<td>" . htmlspecialchars($advance['AdvanceDate']) . "</td>"; // Display AdvanceDate
                        // echo "<td>" . htmlspecialchars($advance['advanceTime']) . "</td>"; 
                        echo "</tr>";
                      }

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

              </div>
              <div class="col-md-6">
                   <table class="table table-bordered patientamt" style="border:1px solid black !important">
                 
  <thead>
    <tr>
      <th>Final Bill Number</th>
      <th>Total</th>
      <th>Payment Mode</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><?php echo $FinalBillno; ?></td>
      <td><?php echo $payable; ?></td>
      <td><?php echo $paymentmode . "</br>" . $disdate . " " . date('H:i A', strtotime($distime)); ?></td>
      
    </tr>
  </tbody>
</table>


                <?php
                if ($paymentmode == "Insurance") {
                ?>
                  <table class="table table-bordered patientamt">
                    <tr>
                      <td>Total Bill Amount</td>
                      <td><?php echo $total; ?></td>
                    </tr>

                    <tr>
                      <td>Insurance Claim Amount</td>
                      <td><?php echo $insuranceAmt; ?></td>
                    </tr>
                    <tr>
                      <td>Discount Amount</td>
                      <td><?php echo $fdiscount; ?></td>
                    </tr>

                    <tr>
                      <td>Final Paid Amount</td>
                      <td><?php echo $finalamt = $payablef; ?></td>
                    </tr>
                  </table>


                <?php } else {
                // $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 patientamt">
                  <!--  <tr>-->
                       
                  <!--  <td>Payment Mode</td>-->
                  <!--  <td > <?php echo  $paymentmode; ?></td>-->
                  <!--</tr>-->
                        <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>
    <tr>
        <td><b>Final Paid Amount</b></td>
        <td><b><?php echo number_format($payable); ?></b></td>
    </tr>                     
                  </table>


                <?php } ?>




              </div>
            </div>

            <div>
              <h6 style="font-weight:bold"><?php echo getIndianCurrency($total) . " only/-"; ?></h6>
            </div>
            <br><br>
            <div class="row">
              <div class="col-md-1"></div>
              <div class="col-md-7">
              </div>
              <div class="col-md-4">
                <h6 style="font-weight:bold;">Authorized Signatory</h6>
                <br>
                <h6>Prepared by <?php echo $name ?></h6>

              </div>
            </div>



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

          </div>
        </div>




      </section>

      <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

  }
}
?>