<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Seller Orders - Flex Market</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3>Orders</h3>
        <a href="<?= base_url('seller/analytics') ?>" class="btn btn-outline-primary">Analytics</a>
    </div>

    <?php if (!empty($orders)): ?>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                <tr>
                    <th>Order ID</th>
                    <th>Product</th>
                    <th>Buyer</th>
                    <th>Amount</th>
                    <th>Status</th>
                    <th>Placed</th>
                    <th>Action</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($orders as $order): ?>
                    <tr>
                        <td>#<?= esc($order['id']) ?></td>
                        <td><?= esc($order['product_title'] ?? ($order['product_name'] ?? 'N/A')) ?></td>
                        <td><?= esc($order['buyer_name'] ?? 'N/A') ?></td>
                        <td>₹<?= number_format($order['final_price'] ?? 0) ?></td>
                        <td><?= ucwords(str_replace('_',' ',$order['status'] ?? '')) ?></td>
                        <td><?= isset($order['created_at']) ? date('d M Y', strtotime($order['created_at'])) : '-' ?></td>
                        <td>
                            <a href="<?= base_url('seller/order/' . $order['id']) ?>" class="btn btn-sm btn-primary">View</a>
                            <?php if (($order['status'] ?? '') === 'confirmed'): ?>
                                <button onclick="markDispatched(<?= $order['id'] ?>)" class="btn btn-sm btn-warning">Mark Dispatched</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php else: ?>
        <div class="alert alert-info">No orders found.</div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function markDispatched(id) {
    if (!confirm('Mark order as dispatched?')) return;
    fetch('/seller/mark-dispatched/' + id, { method: 'POST' })
        .then(r => r.json()).then(j => {
            alert(j.message || 'Done');
            location.reload();
        }).catch(e => alert('Error'));
}
</script>
</body>
</html>