<?php
require_once __DIR__ . '/../functions.php';
requireAuth();
$page_title = 'My Orders';
$db = db();
$user = getCurrentUser();
$stmt = $db->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user['id']]);
$orders = $stmt->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cancel_order_id'])) {
    $cancelId = (int)$_POST['cancel_order_id'];
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ? AND user_id = ?");
    $stmt->execute([$cancelId, $user['id']]);
    $order = $stmt->fetch();
    if ($order && in_array($order['status'], ['pending', 'confirmed'])) {
        $db->beginTransaction();
        try {
            $stmt = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
            $stmt->execute([$cancelId]);
            foreach ($stmt->fetchAll() as $item) {
                $db->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?")->execute([$item['quantity'], $item['product_id']]);
            }
            $db->prepare("UPDATE orders SET status = 'cancelled' WHERE id = ?")->execute([$cancelId]);
            $db->commit();
            flash('success', 'Order cancelled successfully.');
        } catch (Exception $e) {
            $db->rollBack();
            flash('error', 'Failed to cancel order.');
        }
    }
    header('Location: orders.php');
    exit;
}

require_once __DIR__ . '/../includes/header.php';
?>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">My Orders</h1>
    <?php if (count($orders) === 0): ?>
    <div class="text-center py-16"><i class="fas fa-shopping-bag text-gray-300 text-5xl mb-4"></i><h2 class="text-xl font-semibold text-gray-800 mb-2">No orders yet</h2><a href="../catalog.php" class="text-primary-600 hover:underline">Start shopping</a></div>
    <?php else: ?>
    <div class="space-y-4">
        <?php foreach ($orders as $o): $canCancel = in_array($o['status'], ['pending', 'confirmed']); ?>
        <div class="bg-white rounded-xl border border-gray-200 p-6 hover:shadow-sm transition">
            <a href="order-detail.php?id=<?= $o['id'] ?>" class="block">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="font-semibold text-gray-800"><?= h($o['order_number']) ?></p>
                        <p class="text-sm text-gray-500"><?= date('d M Y, h:i A', strtotime($o['created_at'])) ?></p>
                    </div>
                    <div class="text-right">
                        <p class="font-bold text-gray-800"><?= formatPrice($o['total']) ?></p>
                        <p class="mt-1"><?= getStatusBadge($o['status']) ?></p>
                    </div>
                </div>
            </a>
            <?php if ($canCancel): ?>
            <form method="POST" class="mt-3 pt-3 border-t border-gray-100" onsubmit="return confirm('Cancel this order?')">
                <input type="hidden" name="cancel_order_id" value="<?= $o['id'] ?>">
                <button type="submit" class="text-sm text-red-600 hover:text-red-800 underline">Cancel Order</button>
            </form>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
