<?php
// orders.php - Professional order history page (blue/gray theme, integrates with cart system)
session_start();
include_once 'config.php';
include_once 'auth.php';

// Ensure user is logged in
if (!is_logged_in()) {
    set_flash_message('error', 'Please log in to view your orders.');
    header("Location: login.php?redirect=orders");
    exit();
}

$user_id = $_SESSION['user_id'];
$orders = $conn->query("SELECT id, total, status, items, created_at FROM orders WHERE user_id = $user_id ORDER BY created_at DESC");

include_once 'header.php';
?>

<style>
    .orders-container {
        max-width: 900px;
        margin: 120px auto;
        padding: 30px;
        background-color: white;
        box-shadow: 0 6px 15px rgba(0,0,0,0.1);
        border-radius: 12px;
        transition: box-shadow 0.3s ease;
    }
    .orders-container:hover {
        box-shadow: 0 8px 20px rgba(0,0,0,0.15);
    }
    .table th, .table td {
        vertical-align: middle;
    }
    .btn-primary {
        background-color: #0D6EFD;
        border-color: #0D6EFD;
        transition: background-color 0.3s ease, transform 0.2s ease;
    }
    .btn-primary:hover {
        background-color: #0c5fdb;
        transform: translateY(-2px);
    }
    .accordion-button {
        font-family: 'Roboto', sans-serif;
        color: #0D6EFD;
    }
    .accordion-button:not(.collapsed) {
        background-color: #F8F9FA;
        color: #212529;
    }
    h2 {
        font-family: 'Inter', sans-serif;
        color: #212529;
    }
    .alert-link {
        color: #0D6EFD;
    }
</style>

<div class="container orders-container">
    <h2 class="text-center mb-4"><i class="fas fa-shopping-bag me-2"></i>My Orders</h2>
    
    <?php if ($orders->num_rows == 0): ?>
        <div class="alert alert-info text-center">You have no orders yet. <a href="products.php" class="link-primary">Shop now</a>.</div>
    <?php else: ?>
        <div class="accordion" id="ordersAccordion">
            <?php while ($order = $orders->fetch_assoc()): ?>
                <div class="accordion-item">
                    <h2 class="accordion-header" id="orderHeading<?php echo $order['id']; ?>">
                        <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#orderCollapse<?php echo $order['id']; ?>" aria-expanded="false" aria-controls="orderCollapse<?php echo $order['id']; ?>">
                            Order #<?php echo $order['id']; ?> - KES<?php echo number_format($order['total'], 2); ?> (<?php echo htmlspecialchars($order['status']); ?>) - <?php echo date('F j, Y, g:i a', strtotime($order['created_at'])); ?>
                        </button>
                    </h2>
                    <div id="orderCollapse<?php echo $order['id']; ?>" class="accordion-collapse collapse" aria-labelledby="orderHeading<?php echo $order['id']; ?>" data-bs-parent="#ordersAccordion">
                        <div class="accordion-body">
                            <h5>Order Details</h5>
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <th>Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $items = $order['items'] ? json_decode($order['items'], true) : [];
                                    $total = 0;
                                    if (!empty($items)) {
                                        $ids = implode(',', array_map('intval', array_keys($items)));
                                        $result = $conn->query("SELECT id, name, price, image FROM products WHERE id IN ($ids)");
                                        while ($row = $result->fetch_assoc()):
                                            $subtotal = $row['price'] * $items[$row['id']];
                                            $total += $subtotal;
                                    ?>
                                        <tr>
                                            <td>
                                                <img src="<?php echo htmlspecialchars($row['image'] ?? 'placeholder.jpg'); ?>" alt="<?php echo htmlspecialchars($row['name']); ?>" width="50" class="img-fluid me-2">
                                                <?php echo htmlspecialchars($row['name']); ?>
                                            </td>
                                            <td><?php echo $items[$row['id']]; ?></td>
                                            <td>KES<?php echo number_format($row['price'], 2); ?></td>
                                            <td>KES<?php echo number_format($subtotal, 2); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="3" class="text-end fw-bold">Total:</td>
                                        <td>KES<?php echo number_format($total, 2); ?></td>
                                    </tr>
                                </tfoot>
                            <?php } else { ?>
                                <tr><td colspan="4">No items found for this order.</td></tr>
                            <?php } ?>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php endif; ?>
    <div class="text-center mt-4">
        <a href="products.php" class="btn btn-primary">Continue Shopping</a>
    </div>
</div>

<?php include_once 'footer.php'; ?>