<?php
session_start();
include "../config/db.php";

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Include header
include "../includes/header.php";

$user_id = $_SESSION['user_id'];


$orders = mysqli_query($conn,
    "SELECT * FROM orders WHERE user_id='$user_id' ORDER BY id DESC"
    
);
?>

<!-- Main Content Container from header.php -->
<div class="container main-container mt-4">
    <h2 class="mb-4"><i class="fas fa-shopping-bag me-2"></i>My Orders</h2>
    <a href="../products.php" class="btn btn-primary mb-3">
        <i class="fas fa-arrow-left me-2"></i>Continue Shopping
    </a>
    <hr>

    <?php if (mysqli_num_rows($orders) == 0) { ?>
        <div class="alert alert-info">
            <i class="fas fa-info-circle me-2"></i>No orders found.
        </div>
    <?php } ?>

<?php while ($order = mysqli_fetch_assoc($orders)) { ?>

<h3>Order ID: <?php echo $order['id']; ?></h3>
<p>Total: ₹<?php echo $order['total_price']; ?></p>
<p>Date: <?php echo $order['order_date']; ?></p>
<p>Status: 
    <span class="status-badge 
        <?php 
        switch($order['status']) {
            case 'Paid': echo 'status-paid'; break;
            case 'Shipped': echo 'status-shipped'; break;
            case 'Delivered': echo 'status-delivered'; break;
            case 'Cancelled': echo 'status-cancelled'; break;
            case 'Returned': echo 'status-returned'; break;
            case 'In Use': echo 'status-inuse'; break;
            default: echo 'status-pending';
        }
        ?>">
        <?php echo $order['status'] ?? 'Pending'; ?>
    </span>
</p>


<table class="table table-striped table-bordered">
    <thead>
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Qty</th>
        </tr>
    </thead>
    <tbody>

<?php
$items = mysqli_query($conn,
    "SELECT * FROM order_items WHERE order_id='".$order['id']."'"
);

while ($item = mysqli_fetch_assoc($items)) {
?>
<tr>
    <td><?php echo $item['product_name']; ?></td>
    <td>₹<?php echo $item['price']; ?></td>
    <td><?php echo $item['quantity']; ?></td>
</tr>
<?php } ?>
    </tbody>
</table>
<hr>
<?php } ?>
</div>

<?php include "../includes/footer.php"; ?>
