<?php 
error_reporting(0);
session_start();
include '../include/connection.php';
$conn = db();

$order_id = $_POST['order_id'] ?? 0;
$order_id = intval($order_id);

// --- Fetch order info ---
$qry = $conn->prepare("SELECT * FROM tbl_order WHERE odr_id = ?");
$qry->bind_param("i", $order_id);
$qry->execute();
$order = $qry->get_result()->fetch_assoc();

if (!$order) {
    echo "<p class='text-center text-danger'>Order not found.</p>";
    exit;
}

// --- Fetch order items from tbl_temp_cart ---
$itemSql = $conn->prepare("SELECT * FROM tbl_temp_cart WHERE cuser = ?");
$itemSql->bind_param("s", $order['cuser']);
$itemSql->execute();
$items = $itemSql->get_result();

echo "<div class='p-2'>";

echo "<h5>Order ID: <b>{$order['order_id']}</b></h5>";
echo "<p><b>Name:</b> {$order['fname']} {$order['lname']}<br>";
echo "<b>Email:</b> {$order['odr_email']}<br>";
echo "<b>Phone:</b> {$order['odr_phone']}<br>";
echo "<b>Address:</b> {$order['address']}, {$order['city']}, {$order['state']}, {$order['country']} - {$order['zipcode']}</p>";

echo "<hr><h6>Order Items</h6>";

if ($items->num_rows == 0) {
    echo "<p class='text-center text-muted'>No items found for this order.</p>";
} else {
    echo "<table class='table table-bordered table-striped'>
            <thead>
              <tr>
                <th>Image</th>
                <th>Product</th>
                <th>Color</th>
                <th>Qty</th>
                <th>Price</th>
                <th>Total</th>
              </tr>
            </thead>
            <tbody>";

    $grandtotal = 0;
    while ($item = $items->fetch_assoc()) {
        $total = $item['price'] * $item['quantity'];
        $grandtotal += $total;
        $imgPath = !empty($item['product_image'])
            ? "../upload/category/" . htmlspecialchars($item['product_image'])
            : "https://via.placeholder.com/60x60?text=No+Image";

        echo "<tr>
                <td><img src='{$imgPath}' alt='' width='60' height='60'></td>
                <td><a href='{$item['product_url']}' target='_blank'>" . htmlspecialchars($item['product_title']) . "</a></td>
                <td>" . htmlspecialchars($item['color']) . "</td>
                <td>" . htmlspecialchars($item['quantity']) . "</td>
                <td>₹" . number_format($item['price'], 2) . "</td>
                <td>₹" . number_format($total, 2) . "</td>
              </tr>";
    }

    echo "</tbody></table>";
    echo "<h5 class='text-end'><b>Grand Total: ₹" . number_format($grandtotal, 2) . "</b></h5>";
}

echo "</div>";
?>
