<?php
require_once 'config.php';

if (!isLoggedIn()) {
    header('Location: login.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$success_msg = isset($_GET['success']) ? 'Thank you! Your order was placed successfully!' : '';

// Fetch all orders of the user
$stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY id DESC");
$stmt->execute([$user_id]);
$orders = $stmt->fetchAll();

// Cache order items for easy lookup
$order_ids = array_column($orders, 'id');
$items_by_order = [];

if (!empty($order_ids)) {
    $in_clause = implode(',', array_fill(0, count($order_ids), '?'));
    $stmt_items = $pdo->prepare("
        SELECT oi.*, p.name, p.image_url 
        FROM order_items oi 
        JOIN products p ON oi.product_id = p.id 
        WHERE oi.order_id IN ($in_clause)
    ");
    $stmt_items->execute($order_ids);
    $items = $stmt_items->fetchAll();
    
    foreach ($items as $item) {
        $items_by_order[$item['order_id']][] = $item;
    }
}
?>
<?php include 'header.php'; ?>

<div class="container">
    <h2>My Orders 📦</h2>
    
    <?php if (!empty($success_msg)): ?>
        <div class="alert alert-success" style="margin-top: 15px;">🌸 <?php echo $success_msg; ?></div>
    <?php endif; ?>

    <div style="margin-top: 30px; display: flex; flex-direction: column; gap: 25px;">
        <?php if (empty($orders)): ?>
            <div style="text-align: center; padding: 40px; background: var(--light); border-radius: var(--radius); border: 1px solid var(--gray-border);">
                <span style="font-size: 40px;">🛍️</span>
                <h3 style="margin-top: 15px;">No orders yet</h3>
                <p style="color: var(--text-muted); margin-bottom: 20px;">You haven't ordered any lovely outfits yet.</p>
                <a href="index.php" class="btn btn-primary">Shop Now</a>
            </div>
        <?php else: ?>
            <?php foreach ($orders as $order): ?>
                <div style="background: var(--light); border-radius: var(--radius); border: 1px solid var(--gray-border); padding: 25px; box-shadow: var(--shadow-sm);">
                    <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--gray-border); padding-bottom: 15px; margin-bottom: 15px;">
                        <div>
                            <span style="color: var(--text-muted); font-size: 13px;">Order ID</span>
                            <h4 style="font-weight: 700;">#ORD-<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></h4>
                        </div>
                        <div style="text-align: right;">
                            <span style="color: var(--text-muted); font-size: 13px;">Date Placed</span>
                            <div style="font-weight: 500; font-size: 14px;"><?php echo date('d M Y H:i', strtotime($order['created_at'])); ?></div>
                        </div>
                        <div>
                            <span class="badge badge-<?php echo $order['status']; ?>">
                                <?php echo ucfirst($order['status']); ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Order Items -->
                    <div style="display: flex; flex-direction: column; gap: 15px;">
                        <?php if (isset($items_by_order[$order['id']])): ?>
                            <?php foreach ($items_by_order[$order['id']] as $item): ?>
                                <div style="display: flex; align-items: center; gap: 15px;">
                                    <img src="<?php echo htmlspecialchars($item['image_url']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" style="width: 50px; height: 60px; object-fit: cover; border-radius: var(--radius-sm);">
                                    <div style="flex-grow: 1;">
                                        <h5 style="font-size: 14px; font-weight: 600;"><?php echo htmlspecialchars($item['name']); ?></h5>
                                        <span style="font-size: 12px; color: var(--text-muted);">Qty: <?php echo $item['quantity']; ?> &times; ฿<?php echo number_format($item['price'], 2); ?></span>
                                    </div>
                                    <div style="font-weight: 600; font-size: 14px;">
                                        ฿<?php echo number_format($item['price'] * $item['quantity'], 2); ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Summary info -->
                    <div style="border-top: 1px solid var(--gray-border); margin-top: 15px; padding-top: 15px; display: flex; justify-content: space-between; align-items: center; font-size: 14px;">
                        <div style="color: var(--text-muted);">
                            Shipping Address: <span style="color: var(--text-color);"><?php echo htmlspecialchars($order['shipping_address']); ?></span>
                        </div>
                        <div style="text-align: right;">
                            <?php if ($order['discount_applied'] > 0): ?>
                                <div style="color: var(--danger); font-size: 13px;">Points Discount: -฿<?php echo number_format($order['discount_applied'], 2); ?></div>
                            <?php endif; ?>
                            <div style="font-weight: 700; font-size: 16px; color: var(--primary-hover);">
                                Net Amount paid: ฿<?php echo number_format($order['net_amount'], 2); ?>
                            </div>
                            <div style="color: var(--success); font-size: 12px; font-weight: 600;">
                                ✨ Earned +<?php echo $order['points_earned']; ?> pts
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

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