<?php
include("dbConfig.php");

// Check if patientId is sent via POST
if (isset($_POST['patientId'])) {
    $patientId = $db->real_escape_string($_POST['patientId']);

    // SQL query to fetch the total amount from the `bill` table for the given PatientId
    $billQuery = "SELECT 
                      SUM(PayableAmount) AS TotalPayableAmount 
                  FROM bill 
                  WHERE PatientId = '$patientId'";

    // SQL query to fetch the total amount from the `examination` table for the given PatientId
    $examinationQuery = "SELECT 
                             SUM(Amount) AS TotalExaminationAmount 
                         FROM examination 
                         WHERE PatId = '$patientId'";

    // Execute both queries
    $billResult = $db->query($billQuery);
    $examinationResult = $db->query($examinationQuery);

    // Initialize totals
    $billTotal = 0;
    $examinationTotal = 0;

    // Fetch the results and store them
    if ($billResult->num_rows > 0) {
        $billRow = $billResult->fetch_assoc();
        $billTotal = $billRow['TotalPayableAmount'] ?? 0;
    }

    if ($examinationResult->num_rows > 0) {
        $examinationRow = $examinationResult->fetch_assoc();
        $examinationTotal = $examinationRow['TotalExaminationAmount'] ?? 0;
    }

    // Calculate the combined total
    $combinedTotal = $billTotal + $examinationTotal;

    // Output the combined total
    echo "" . number_format($combinedTotal, 2);
} else {
    echo "Invalid Request";
}

// Close the connection
$db->close();
?>
