<?php
// debug_order.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$host = "localhost";
$user = "mhsg3183_loundry";
$pass = "mhsg3183_loundry123";
$db   = "mhsg3183_loundry";

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get latest order
$query = "SELECT * FROM orders ORDER BY id DESC LIMIT 1";
$result = $conn->query($query);
$order = $result->fetch_assoc();

if (!$order) {
    die("No orders found.");
}

echo "<h3>Latest Order (ID: {$order['id']})</h3>";
echo "Total (Raw): '{$order['total']}' (Type: " . gettype($order['total']) . ")<br>";
echo "Paid Amount (Raw): '{$order['paid_amount']}' (Type: " . gettype($order['paid_amount']) . ")<br>";

// Get payments for this order
$query = "SELECT * FROM payments WHERE order_id = " . (int)$order['id'];
$p_result = $conn->query($query);

echo "<h3>Payments</h3>";
$sum_payments = 0;
while ($row = $p_result->fetch_assoc()) {
    echo "Payment ID: {$row['id']}, Amount: '{$row['amount']}'<br>";
    $sum_payments += (float)$row['amount'];
}

echo "<h3>Analysis</h3>";
echo "Sum of Payments: $sum_payments<br>";
echo "Order Paid Amount: " . (float)$order['paid_amount'] . "<br>";
echo "Remaining Calculation: max(0, " . (float)$order['total'] . " - " . (float)$order['paid_amount'] . ") = " . max(0, (float)$order['total'] - (float)$order['paid_amount']) . "<br>";

$conn->close();
?>
