<?php 
include("../db/cn.php");

if (!isset($_GET["id"])) {
  die("ID parameter is missing.");
}

$id = $_GET["id"];
$rec_patient = mysqli_query($connection, "SELECT * FROM patient WHERE id = '$id'");
$row_patient = mysqli_fetch_array($rec_patient);

if ($connection->connect_error) {
  die("Connection failed: " . $connection->connect_error);
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $patientId = $_POST["patientId"];
  $doctor = $_POST["doctor"];
  $subtotal = $_POST["subtotal"];
  $discount = $_POST["discount"];
  $deposit = $_POST["deposit"];
  $due = $_POST["due"];
  $paymentMethod = $_POST["paymentMethod"];
  $p_name = $_POST["p_name"];
  $date_time = date("Y-m-d");
  
  $invoiceId = uniqid();
  
  $sql_invoice = "INSERT INTO lab_invoice (
    invoice_id,
    p_id,
    p_name,
    ref_doctor,
    sub_total,
    discount_amount,
    deposit_amount,
    due,
    deposit_type,
    date_time
  ) VALUES (
    '$invoiceId',
    '$patientId',
    '$p_name',
    '$doctor',
    '$subtotal',
    '$discount',
    '$deposit',
    '$due',
    '$paymentMethod',
    '$date_time'
  )";
  
  if ($connection->query($sql_invoice) === TRUE) {
    if (isset($_POST['labTest']) && is_array($_POST['labTest'])) {
      $labTests = $_POST['labTest'];
      foreach ($labTests as $labTest) {
        list($itemName, $itemPrice) = explode('-', $labTest);
        
        $sql_item = "INSERT INTO lab_invoice_items (invoice_id, test_name, test_price, date_time)
                     VALUES ('$invoiceId', '$itemName', '$itemPrice', '$date_time')";
        
        if ($connection->query($sql_item) !== TRUE) {
          echo "Error: " . $sql_item . "<br>" . $connection->error;
        }
      }
      
      echo "";
    } else {
      echo "";
    }
  } else {
    echo "Error: " . $sql_invoice . "<br>" . $connection->error;
  }
}
?>

<!DOCTYPE html>

<html lang="en">

<head>
    <meta charset="utf-8" />
    <link rel="apple-touch-icon" sizes="76x76" href="../assets/img/apple-icon.png">
    <link rel="icon" type="image/png" href="../img/print_logo.png">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>Laboratory L.I.M.S</title>
    <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport' />
    <link href="https://fonts.googleapis.com/css?family=Quicksand:500,700,200" rel="stylesheet" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link href="../assets/css/light-bootstrap-dashboard.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .modal-lg-custom {
            max-width: 90% !important;
        }
		.btn-outline-dark{
		   background:#2C2C2C;
		   color:#fff;	
			}
			.btn-outline-dark:hover{
			    background:#fff;
				color:#2C2C2C;
				border:1px solid #2C2C2C;	
				}
		.bg-dark{
		   background:#7A2355;
		   color:#fff;	
			}
    </style>
</head>

<body>
    <div class="wrapper">
        <div class="sidebar" data-image="../assets/img/sidebar-7.jpg">
            <?php include("common/sd.php"); ?>
        </div>
        <div class="main-panel">
            <?php include("common/hd.php"); ?>
            <div class="content">
                
                <div class="container">
    <div class="row">
    <div class="col-sm-4">
    <h2>Invoice </h2>
    </div>
    <div class="col-sm-5"></div>
    <div class="col-sm-3">
   <a href="payment_h.php?id=<?php echo $row_patient["id"];?>"> <button type="button" class="btn btn-dark btn-sm">Back</button></a>
    </div>
    </div>
    <br>
    <form action="invoice_p2.php?id=<?php echo $row_patient["id"]; ?>" method="post">
      <div class="row">
        <div class="col-sm-3">
          <label for="patientId" class="form-label">Patient ID</label>
          <input type="hidden" name="p_name" value="<?php echo $row_patient["p_name"]; ?>" />
          <input type="text" class="form-control" id="patientId" name="patientId" value="<?php echo $row_patient["id"]; ?>" readonly>
          <label for="patientId" class="form-label">Patient Name</label>
           <input type="text" class="form-control " style="text-transform:capitalize;" id="" name="" value="<?php echo $row_patient["p_name"]; ?>" readonly>
         
          <label for="doctor" class="form-label">Doctor</label>
          <select class="form-select" id="doctor" name="doctor">
            <option value="<?php echo $row_patient["doctor"];?>"><?php echo $row_patient["doctor"];?></option>
            <!-- Add more options as needed -->
          </select>
        
          <?php $labTest = mysqli_query($connection, "select * from lab_test"); ?>
          <label for="labTest" class="form-label">Lab Test</label>
          <select class="form-select" id="labTest" name="labTest">
            <option value="">Select Lab Test</option>
            <?php while ($rowLab = mysqli_fetch_array($labTest)) { ?>
              <option value="<?php echo $rowLab["test_name"] . " - " . $rowLab["test_price"]; ?>">
                <?php echo $rowLab["test_name"] . " - " . $rowLab["test_price"]; ?>
              </option>
            <?php } ?>
          </select><br>
          <button type="button" class="btn btn-primary" id="addItemBtn">Add Item</button>
        </div>
        
        <div class="col-sm-6">
          <!-- Table to display selected items -->
          <table class="table text-dark" id="itemTable" >
            <thead >
              <tr >
                <th >Item</th>
                <th >Price</th>
                <th >Action</th>
              </tr>
            </thead>
            <tbody>
              <!-- Selected items will be added dynamically here -->
            </tbody>
          </table>
        </div>
        <div class="col-sm-3">
          <div class="form-group">
            <label for="subtotal" class="form-label">Subtotal</label>
            <input type="text" class="form-control" id="subtotal" name="subtotal" readonly>
          </div>
          <div class="form-group">
            <label for="discount" class="form-label">Discount</label>
            <input type="text" class="form-control" id="discount" name="discount">
          </div>
          <div class="form-group">
            <label for="deposit" class="form-label">Deposit</label>
            <input type="text" class="form-control" id="deposit" name="deposit">
          </div>
          <div class="form-group">
            <label for="due" class="form-label">Due</label>
            <input type="text" class="form-control" id="due" name="due" readonly>
          </div>
          <div class="form-group">
            <label for="grandTotal" class="form-label">Grand Total</label>
            <input type="text" class="form-control" id="grandTotal" name="grandTotal" readonly>
          </div>
          <div class="form-group">
            <label for="paymentMethod" class="form-label">Payment Method</label>
            <select class="form-select" id="paymentMethod" name="paymentMethod">
              <option value="cash">Cash</option>
              <option value="card">Card</option>
              <option value="bank">Bank Transfer</option>
            </select>
          </div>
          <button type="submit" class="btn btn-success btn-sm">Generate Invoice</button>
        </div>
      </div>
    </form>
  </div>
              

          
          
                
            </div>
            
            <footer class="footer">
                <div class="container-fluid">
                </div>
            </footer>
        </div>
    </div>
 <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    document.addEventListener("DOMContentLoaded", function() {
      let addItemBtn = document.getElementById("addItemBtn");
      let itemTableBody = document.querySelector("#itemTable tbody");

      addItemBtn.addEventListener("click", function() {
        let labTest = document.getElementById("labTest");
        let selectedOption = labTest.options[labTest.selectedIndex];

        if (selectedOption.value !== "") {
          let itemText = selectedOption.text;
          let itemParts = itemText.split(" - ");
          let itemName = itemParts[0];
          let itemPrice = parseFloat(itemParts[1]);

          if (!isNaN(itemPrice)) {
            let newRow = document.createElement("tr");
            newRow.innerHTML = `
              <td style="color:#511738;">${itemName}</td>
              <td style="color:#511738;">${itemPrice.toFixed(2)}</td>
              <td style="color:#511738;"><button type="button" class="btn btn-danger btn-sm">x</button></td>
              <input type="hidden" name="labTest[]" value="${itemName}-${itemPrice.toFixed(2)}">
            `;
            itemTableBody.appendChild(newRow);

            let subtotal = document.getElementById("subtotal");
            let currentSubtotal = parseFloat(subtotal.value) || 0;
            subtotal.value = (currentSubtotal + itemPrice).toFixed(2);

            calculateDueAndGrandTotal();
          } else {
            console.error("Invalid item price:", itemPrice);
          }
        }
      });

      itemTableBody.addEventListener("click", function(event) {
        if (event.target.classList.contains("btn-danger")) {
          let row = event.target.closest("tr");
          let price = parseFloat(row.children[1].textContent);

          if (!isNaN(price)) {
            row.remove();

            let subtotal = document.getElementById("subtotal");
            let currentSubtotal = parseFloat(subtotal.value) || 0;
            subtotal.value = (currentSubtotal - price).toFixed(2);

            calculateDueAndGrandTotal();
          }
        }
      });

      document.getElementById("discount").addEventListener("input", calculateDueAndGrandTotal);
      document.getElementById("deposit").addEventListener("input", calculateDueAndGrandTotal);

      function calculateDueAndGrandTotal() {
        let subtotal = parseFloat(document.getElementById("subtotal").value) || 0;
        let discount = parseFloat(document.getElementById("discount").value) || 0;
        let deposit = parseFloat(document.getElementById("deposit").value) || 0;
        let due = document.getElementById("due");
        let grandTotal = document.getElementById("grandTotal");

        let totalDue = subtotal - discount - deposit;
        due.value = totalDue.toFixed(2);
        grandTotal.value = subtotal.toFixed(2);
      }
    });
  </script>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="../assets/js/core/jquery.3.2.1.min.js" type="text/javascript"></script>
    <script src="../assets/js/core/popper.min.js" type="text/javascript"></script>
    <script src="../assets/js/core/bootstrap.min.js" type="text/javascript"></script>
    <script src="../assets/js/plugins/bootstrap-switch.js"></script>
    <script src="../assets/js/plugins/chartist.min.js"></script>
    <script src="../assets/js/plugins/bootstrap-notify.js"></script>
    <script src="../assets/js/light-bootstrap-dashboard.js?v=2.0.0" type="text/javascript"></script>
    <script src="../assets/js/demo.js"></script>
</body>

</html>