// edit.php
<?php
include("dbConfig.php");
$billNo = $_GET['billNo'];
$patid = $_GET['PatId'];

// Fetch examination details
$examQuery = "SELECT * FROM examination WHERE BillNo='$billNo' AND PatId='$patid'";
$examResult = mysqli_query($db, $examQuery);
$row = mysqli_fetch_assoc($examResult);
?>

<form method="POST" action="">
    <input type="hidden" name="billNo" value="<?php echo $billNo; ?>">
    <input type="hidden" name="patid" value="<?php echo $patid; ?>">

    <!-- Include form fields for editing -->
    <input type="text" name="particulars" value="<?php echo $row['Particulars']; ?>">
    <input type="text" name="consultant" value="<?php echo $row['consultant']; ?>">
    <input type="text" name="department" value="<?php echo $row['optionlab']; ?>">
    <input type="number" name="quantity" value="<?php echo $row['Quantity']; ?>">
    <input type="number" name="price" value="<?php echo $row['UnitPrice']; ?>">
    <input type="number" name="amount" value="<?php echo $row['Amount']; ?>" readonly>

    <button type="submit">Update</button>
</form>
<!---->
<?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) {
    // Notify the user about the successful addition
    echo "<script>alert('Examination details added and Bill No generated: $abillid!')</script>";
    header("Location: examination_previe.php?billNo=$abillid&PatId=$patid&amount=$amount");

}


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

