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

?>
<?php
// Enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(E_ALL);

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect form data
    $patId = trim($_POST['AdPatientId']); // Remove extra spaces
    $contact = trim($_POST['Adcontact']); // Remove extra spaces
    $particulars = $_POST['Particulars'];
    $quantities = $_POST['Quantity'];
    $consultants = $_POST['consultant'];
    $optionlab = $_POST['optionlab'];
    $billType = $_POST['billtype'];
    $insuranceName = $_POST['InsuranceName'] ?: '';
    $insuranceNo = $_POST['InsuranceNo'] ?: '';
    $bank = $_POST['bank'] ?: '';
    $cardno = $_POST['cardno'] ?: '';
    $upi = $_POST['upi'] ?: '';
    $cash = $_POST['cash'] ?: '';
    $upiid = $_POST['upiid'] ?: '';
    $createdBy = trim($_POST['preparedby']); // Remove extra spaces
    $createdAt = date('Y-m-d H:i:s');

    // Debugging: Print input values
    // echo "Contact: $contact, PatId: $patId<br>";

    // Query to fetch patient details
    $queryPatient = "SELECT PatId FROM patientdetails WHERE Contact='$contact' OR PatId='$patId'";
    // Debugging: Print the query
    // echo "Patient Query: $queryPatient<br>";
    
    $patientResult = mysqli_query($db, $queryPatient);
    
    if ($patientResult) {
        // Check if patient exists
        if (mysqli_num_rows($patientResult) > 0) {
            $row = $patientResult->fetch_assoc();
            $patid = $row['PatId']; // Fetch patient ID
            // echo "Retrieved PatId: $patid<br>"; 
            
            if (empty($patid)) {
                echo "<script>alert('No patient found with the provided ID or Contact Number!')</script>";
                exit;
            }

            // Generate a new BillNo (starting from 1)
            $billNoQuery = "SELECT COUNT(*) as total FROM examination";
            $billNoResult = mysqli_query($db, $billNoQuery);
            $billNoRow = $billNoResult->fetch_assoc();
            $nextBillNo = $billNoRow['total'] + 1; // Increment for the next BillNo
            $abillid = "VH/E24/" . $nextBillNo; // New BillNo
            
            // Initialize a flag to check if insertions are successful
            $insertSuccessful = true;

            // Loop through each particular to insert details
            foreach ($particulars as $index => $particular) {
                $quantity = $quantities[$index];
                $consultant = $consultants[$index];
                $option = $optionlab[$index];

                // Calculate Unit Price from the selected option
                $priceQuery = "SELECT Price FROM particulars WHERE Description='$particular'";
                $priceResult = mysqli_query($db, $priceQuery);
                $priceRow = $priceResult->fetch_assoc();
                $unitPrice = $priceRow['Price'] ?? 0; // Default to 0 if not found

                // Calculate the amount
                $amount = $unitPrice * $quantity;

                // Insert examination record
                $insertExam = "INSERT INTO examination (PatId, Particulars, Quantity, UnitPrice, Amount, optionlab, consultant, InsuranceName, InsuranceNo, bank, cardno, upi, cash, upiid, created_at, created_by, BillNo) 
                    VALUES ('$patid', '$particular', '$quantity', '$unitPrice', '$amount', '$option', '$consultant', '$insuranceName', '$insuranceNo', '$bank', '$cardno', '$upi', '$cash', '$upiid', '$createdAt', '$createdBy', '$abillid')";

                // Execute the insert and check for errors
                if (!mysqli_query($db, $insertExam)) {
                    echo "Error inserting examination record: " . mysqli_error($db);
                    $insertSuccessful = false;
                    break; // Stop further insertion attempts
                }
            }

            // If all insertions are successful, notify the user
        if ($insertSuccessful) {
    echo "<script>alert('Examination details added and Bill No generated: $abillid!');</script>";
    header("Location: edit_examintaion.php?billNo=$abillid&PatId=$patid&amount=$amount");
    exit;


}


        } else {
            echo "<script>alert('No patient found with the provided ID or Contact Number!')</script>";
        }
    } else {
        echo "Error in query: " . mysqli_error($db);
    }
}
?>



<!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">
span{
    color:red;
}
.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>
<script type="text/javascript">
  function validateForm() {
  var x = document.forms["checkForm"]["PatientId"].value;
  var y = document.forms["checkForm"]["con"].value;
  if (x == "" && y=="") {
    alert("Patient ID or Phone Number must be filled out");
    return false;
  }
}
</script>
</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="OPDPatientsList.php">View OPD Patients Lists</a></li>
            <li><a href="OPDPatients.php">View OPD Patients Bills</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"><? 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-2"></div> 
<div class="col-md-8">
  <div class="shadow p-3 mb-5 bg-light rounded">
<form method="POST" action="" onsubmit="return validateForm()" name="checkForm">
<h2 style="text-align: center;font-weight: bold;color:#fff;background-color: #279480;padding:10px;">Add Examination</h2>
<div class="row">
    <div class="form-group col">
  <label for="PatientId">Patient ID</label>
  <input  class="form-control" type="text" name="AdPatientId" id="PatientId">
</div>
<p style="text-align:center;padding-top:5px;">(or)</p>

<div class="form-group col">
  <label for="con">Phone Number</label>
  <input  class="form-control" type="text" name="Adcontact" id="con">
</div>
</div>
 <div class="row">
              <div class="form-group col">
                <label for="">Particulars<span>*</span></label>
                <select class="form-control" name="Particulars[]" required>
                  <option value="">Choose Option</option>
                  <?php
                  $qu2 = mysqli_query($db, "SELECT * FROM particulars ORDER BY Description ASC");
                  while ($row = $qu2->fetch_assoc()) {
                    $desp = $row['Description'];
                    // echo "<option value=\"$desp\">$desp</option>";
                    $price = $row['Price']; // Assuming 'Price' is a column in your particulars table
                    echo "<option value=\"$desp\" data-price=\"$price\">$desp</option>";
                  }
                  ?>
                </select>

                <!--</div>-->
                <!--</div>-->

                </select>
              </div>
              <div class="form-group col">
                <label for="">Quantity<span>*</span></label>
                <input class="form-control" type="text" name="Quantity[]" id="" required>
              </div>
              <div class="form-group col">
                <label for="">Consultant<span>*</span></label>
                <select class="form-control" name="consultant[]" required>
                  <option value="">Choose Option</option>
                  <?php
                  $qu2 = mysqli_query($db, "SELECT `doc_name` FROM `docotorslist`");
                  while ($row = $qu2->fetch_assoc()) {
                    $doc_name = $row['doc_name'];
                    $selected = ($doc_name == "VH") ? "selected" : "";
                    echo "<option value=\"$doc_name\" $selected>$doc_name</option>";
                  }
                  ?>
                </select>
              </div>



              <div class="form-group col">
                <label for="">Department<span>*</span></label>
                <select class="form-control" name="optionlab[]">
                  <option value="">Choose Option</option>
                  <option value="Radiology">Radiology </option>
                  <option value="Lab Test">Labouratory</option>
                  <option value="Cardiology">Cardiology</option>


                </select>
              </div>
              <!--<div class="form-group col">-->
              <!--</div>-->
            </div>  
            <div class="input-group control-group after-add-more">
              <button class="btn btn-success add-more" type="button"><i class="glyphicon glyphicon-plus"></i>Add Particulars</button>
            </div><br>
            <!---->
              <br>
            <h4>Payment Details</h4>
            <hr>
            <div class="row">
              <div class="form-group col">
                <label for="">Bill Type<span>*</span></label>
                <select class="form-control" name="billtype" id="PaymentMode" required>
                  <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="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="cardDetails">
              <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">
              <div class="form-group col">
                <label for="bank">Upi Amount<span></span></label>
                <input class="form-control" type="text" name="upi">
              </div>
              <div class="form-group col">
                <label for="cardno">Cash Amount<span></span></label>
                <input class="form-control" type="text" name="cash" id="cash">
              </div>

            </div>
             <div class="row" id="upiDetails">
              <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 class="row">
              <div class="form-group col">
                <label for="bdate">Date<span>*</span></label>
                <input class="form-control" type="date" name="bdate" id="bdate" value="<?php echo date('Y-m-d'); ?>" required>
              </div>
              <div class="form-group col">
                <label for="btime">Time<span>*</span></label>
                <input class="form-control" type="time" name="btime" id="btime"  value="<?php echo date('H:i'); ?>"  required>
              </div>
            </div>
              <div class="row">
              <div class="form-group col">
                <label for="totalAmount">Total Amount</label>
                <input class="form-control" type="text" id="totalAmount" name="totalAmount" readonly>
              </div>
            </div>
<!---->

            <!--/-->
  <input type="hidden" name="preparedby" value="<? echo $name?>">
<button type="submit" class="btn btn-primary">Preview</button>
</form>
<!---->
<div class="copy hide">
        <div class="control-group row">
          <div class="form-group col">
            <label for="">Particulars</label>
            <select class="form-control" name="Particulars[]">
              <option value="">Choose Option</option>
              <?php
              $qu2 = mysqli_query($db, "SELECT * FROM particulars");
              while ($row = $qu2->fetch_assoc()) {
                $desp = $row['Description'];
                // echo "<option value=\"$desp\">$desp</option>";
                $price = $row['Price']; // Assuming 'Price' is a column in your particulars table
                echo "<option value=\"$desp\" data-price=\"$price\">$desp</option>";
              }
              ?>
            </select>
          </div>
          <div class="form-group col">
            <label for="">Quantity</label>
            <input class="form-control" type="text" name="Quantity[]" id="">
          </div>
          <div class="form-group col">
            <label for="">Consultant</label>
            <select class="form-control" name="consultant[]">
            <option value="">Choose Option</option>
<?php
$qu2 = mysqli_query($db, "SELECT `doc_name` FROM `docotorslist`");
while ($row = $qu2->fetch_assoc()) {
    $doc_name = $row['doc_name'];
    $selected = ($doc_name == "VH") ? 'selected' : '';
    echo "<option value=\"$doc_name\" $selected>$doc_name</option>";
}
?>

            </select>
          </div>
          <div class="form-group col">
            <label for="">Department<span></span></label>
            <select class="form-control" name="optionlab[]">
              <option value="">Choose Option</option>
              <option value="Radiology">Radiology </option>
              <option value="Lab Test">Labouratory</option>
              <option value="Cardiology">Cardiology</option>

            </select>
          </div>
          <div class="input-group-btn col" style="margin-top:30px;">
            <button class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
          </div>
        </div>
      </div>
      <!---->
</div>
</div>
<div class="col-md-2"></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>
    $(document).ready(function() {
      // Function to calculate the total amount
      function calculateTotal() {
        var totalAmount = 0;

        // Loop through each set of Particulars and Quantity
        $('select[name="Particulars[]"]').each(function(index) {
          var price = $(this).find(':selected').data('price') || 0; // Get the price of the selected particular
          var quantity = $('input[name="Quantity[]"]').eq(index).val() || 0; // Get the corresponding quantity

          totalAmount += price * quantity; // Add to the total amount
        });

        // Update the total amount field
        $('#totalAmount').val(totalAmount.toFixed(2));
      }

      // Event listener for static and dynamically added Particulars or Quantity inputs
      $(document).on('change keyup', 'select[name="Particulars[]"], input[name="Quantity[]"]', function() {
        calculateTotal(); // Call the function on change or keyup event
      });

      calculateTotal();

    });
  </script>

 <script type="text/javascript">
  $("#PaymentMode").change(function() {
  var paymentMode = $(this).val();

  // Hide all sections by default
  $('#InsDetails').hide();
  $('#cardDetails').hide();
  $('#upiCashDetails').hide();
  $('#upiDetails').hide();  // Hides UPI Amount section

  // Remove required attributes for all input fields
  $('#InsuranceName, #InsuranceNo').removeAttr('required');
  $('input[name="bank"], input[name="cardno"]').removeAttr('required');
  $('input[name="upi"], input[name="cash"]').removeAttr('required');
  $('input[name="upiid"]').removeAttr('required');  // Removes required from UPI Amount field

  if (paymentMode == "Insurance") {
    // Show insurance details and make fields required
    $('#InsDetails').show();
    $('#InsuranceName').attr('required', '');
    $('#InsuranceNo').attr('required', '');
  } else if (paymentMode == "Card") {
    // Show card details and make fields required
    $('#cardDetails').show();
    $('input[name="bank"]').attr('required', '');
    $('input[name="cardno"]').attr('required', '');
  } else if (paymentMode == "Cash and UPI") {
    // Show UPI and Cash details and make fields required
    $('#upiCashDetails').show();
    $('input[name="upi"]').attr('required', '');   // UPI ID required
    $('input[name="cash"]').attr('required', '');  // Cash amount required
  } else if (paymentMode == "UPI") {
    // Show only the UPI Amount section
    $('#upiDetails').show();  // Shows UPI Amount section
    $('input[name="upiid"]').attr('required', '');  // UPI Amount required
  }
});


    $("#PaymentMode").trigger("change");
  </script>
  <script type="text/javascript">
    $(document).ready(function() {


      $(".add-more").click(function() {
        var html = $(".copy").html();
        $(".after-add-more").before(html);
      });


      $("body").on("click", ".remove", function() {
        $(this).parents(".control-group").remove();
      });


    });
  </script>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script type="text/javascript">
   
$("#PaymentMode").change(function() {
  var paymentMode = $(this).val();

  // Hide all sections by default
  $('#InsDetails').hide();
  $('#cardDetails').hide();
  $('#upiCashDetails').hide();
  $('#upiDetails').hide();  // Hides UPI Amount section

  // Remove required attributes for all input fields
  $('#InsuranceName, #InsuranceNo').removeAttr('required');
  $('input[name="bank"], input[name="cardno"]').removeAttr('required');
  $('input[name="upi"], input[name="cash"]').removeAttr('required');
  $('input[name="upiid"]').removeAttr('required');  // Removes required from UPI Amount field

  if (paymentMode == "Insurance") {
    // Show insurance details and make fields required
    $('#InsDetails').show();
    $('#InsuranceName').attr('required', '');
    $('#InsuranceNo').attr('required', '');
  } else if (paymentMode == "Card") {
    // Show card details and make fields required
    $('#cardDetails').show();
    $('input[name="bank"]').attr('required', '');
    $('input[name="cardno"]').attr('required', '');
  } else if (paymentMode == "Cash and UPI") {
    // Show UPI and Cash details and make fields required
    $('#upiCashDetails').show();
    $('input[name="upi"]').attr('required', '');   // UPI ID required
    $('input[name="cash"]').attr('required', '');  // Cash amount required
  } else if (paymentMode == "UPI") {
    // Show only the UPI Amount section
    $('#upiDetails').show();  // Shows UPI Amount section
    $('input[name="upiid"]').attr('required', '');  // UPI Amount required
  }
});
$("#PaymentMode").trigger("change");
</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>