<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Orders';
$db = db();

$orderId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($orderId) {
    $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->execute([$orderId]);
    $order = $stmt->fetch();
    if (!$order) { header('Location: orders.php'); exit; }
    $stmt = $db->prepare("SELECT * FROM order_items WHERE order_id = ?");
    $stmt->execute([$orderId]);
    $items = $stmt->fetchAll();
    $user = null;
    if ($order['user_id']) {
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->execute([$order['user_id']]);
        $user = $stmt->fetch();
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $status = $_POST['status'] ?? $order['status'];
        $paymentStatus = $_POST['payment_status'] ?? $order['payment_status'];
        $adminNotes = $_POST['admin_notes'] ?? '';
        $db->prepare("UPDATE orders SET status=?, payment_status=?, admin_notes=?, shipped_at=IF(?='shipped' AND shipped_at IS NULL, NOW(), shipped_at), delivered_at=IF(?='delivered' AND delivered_at IS NULL, NOW(), delivered_at) WHERE id=?")
            ->execute([$status, $paymentStatus, $adminNotes, $status, $status, $orderId]);
        
        flash('success', 'Order updated!');
        header('Location: orders.php?id=' . $orderId);
        exit;
    }
    
    require_once __DIR__ . '/../includes/admin-header.php';
    ?>
    <a href="orders.php" class="text-sm text-primary-600 hover:underline mb-4 inline-block"><i class="fas fa-arrow-left mr-1"></i> Back to Orders</a>
    <form method="POST" class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2 space-y-6">
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <div class="flex items-center justify-between mb-4"><h2 class="font-semibold text-gray-800">Order #<?= h($order['order_number']) ?></h2><?= getStatusBadge($order['status']) ?></div>
                <div class="grid grid-cols-2 gap-4 text-sm">
                    <div><span class="text-gray-500">Date</span><p><?= date('d M Y, h:i A', strtotime($order['created_at'])) ?></p></div>
                    <div><span class="text-gray-500">Payment</span><p><?= ucfirst($order['payment_method']) ?> - <?= getStatusBadge($order['payment_status']) ?></p></div>
                    <div><span class="text-gray-500">Customer</span><p><?= h($user['name'] ?? $order['shipping_name']) ?> (<?= h($user['email'] ?? '') ?>)</p></div>
                    <div><span class="text-gray-500">Phone</span><p><?= h($order['shipping_phone']) ?></p></div>
                </div>
                <?php if ($order['shipping_name']): ?>
                <hr class="my-4">
                <h4 class="font-medium text-gray-700 mb-2">Shipping Address</h4>
                <p class="text-sm text-gray-600"><?= h($order['shipping_name']) ?>, <?= h($order['shipping_address']) ?>, <?= h($order['shipping_city']) ?>, <?= h($order['shipping_state']) ?> - <?= h($order['shipping_pincode']) ?></p>
                <?php endif; ?>
            </div>
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h3 class="font-semibold text-gray-800 mb-4">Order Items</h3>
                <?php foreach ($items as $item): ?>
                <div class="flex items-center gap-4 py-3 border-b last:border-0">
                    <div class="w-12 h-12 bg-gray-50 rounded overflow-hidden shrink-0 flex items-center justify-center">
                        <?php if ($item['image_url']): ?><img src="<?= strpos($item['image_url'], '://') === false ? BASE_PATH . '/' . h($item['image_url']) : h($item['image_url']) ?>" alt="" class="w-full h-full object-cover"><?php else: ?><i class="fas fa-box text-gray-300"></i><?php endif; ?>
                    </div>
                    <div class="flex-1"><p class="font-medium text-sm"><?= h($item['product_name']) ?></p><p class="text-xs text-gray-500">Qty: <?= $item['quantity'] ?> x <?= formatPrice($item['unit_price']) ?></p><?php if ($item['variant_info']): ?><p class="text-xs text-gray-400"><?= h($item['variant_info']) ?></p><?php endif; ?></div>
                    <p class="font-medium text-sm"><?= formatPrice($item['total']) ?></p>
                </div>
                <?php endforeach; ?>
                <hr class="my-3">
                <div class="space-y-1 text-sm text-right">
                    <div class="flex justify-end gap-4"><span class="text-gray-500">Subtotal:</span><span><?= formatPrice($order['subtotal']) ?></span></div>
                    <?php if ($order['discount_amount'] > 0): ?><div class="flex justify-end gap-4"><span class="text-green-600">Discount:</span><span>-<?= formatPrice($order['discount_amount']) ?></span></div><?php endif; ?>
                    <div class="flex justify-end gap-4"><span class="text-gray-500">Tax:</span><span><?= formatPrice($order['tax_amount']) ?></span></div>
                    <div class="flex justify-end gap-4"><span class="text-gray-500">Shipping:</span><span><?= $order['shipping_amount'] > 0 ? formatPrice($order['shipping_amount']) : 'Free' ?></span></div>
                    <div class="flex justify-end gap-4 text-lg font-bold"><span>Total:</span><span><?= formatPrice($order['total']) ?></span></div>
                </div>
            </div>
        </div>
        <div class="space-y-6">
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h3 class="font-semibold text-gray-800 mb-4">Update Order</h3>
                <div class="space-y-4">
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                            <?php foreach (['pending','confirmed','processing','shipped','delivered','cancelled','refunded'] as $s): ?>
                            <option value="<?= $s ?>" <?= $order['status'] === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Payment Status</label>
                        <select name="payment_status" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                            <?php foreach (['pending','paid','failed','refunded'] as $s): ?>
                            <option value="<?= $s ?>" <?= $order['payment_status'] === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div><label class="block text-sm font-medium text-gray-700 mb-1">Admin Notes</label><textarea name="admin_notes" rows="3" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"><?= h($order['admin_notes'] ?? '') ?></textarea></div>
                    <button type="submit" class="w-full bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700">Update Order</button>
                </div>
            </div>
            <?php if ($order['notes']): ?>
            <div class="bg-white rounded-xl border border-gray-200 p-6">
                <h3 class="font-semibold text-gray-800 mb-2">Customer Notes</h3>
                <p class="text-sm text-gray-600"><?= h($order['notes']) ?></p>
            </div>
            <?php endif; ?>
        </div>
    </form>
    <?php
    require_once __DIR__ . '/../includes/admin-footer.php';
    exit;
}

// List all orders
$orders = $db->query("SELECT o.*, u.name as customer_name FROM orders o LEFT JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC")->fetchAll();

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
    <table class="w-full text-sm">
        <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Order</th><th class="px-4 py-3 font-medium">Customer</th><th class="px-4 py-3 font-medium">Date</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium">Payment</th><th class="px-4 py-3 font-medium">Total</th><th class="px-4 py-3 font-medium"></th></tr></thead>
        <tbody>
            <?php foreach ($orders as $o): ?>
            <tr class="border-t hover:bg-gray-50">
                <td class="px-4 py-3 font-medium"><?= h($o['order_number']) ?></td>
                <td class="px-4 py-3"><?= h($o['customer_name'] ?: $o['shipping_name'] ?: 'Guest') ?></td>
                <td class="px-4 py-3 text-gray-500"><?= date('d M Y', strtotime($o['created_at'])) ?></td>
                <td class="px-4 py-3"><?= getStatusBadge($o['status']) ?></td>
                <td class="px-4 py-3"><?= getStatusBadge($o['payment_status']) ?></td>
                <td class="px-4 py-3 font-medium"><?= formatPrice($o['total']) ?></td>
                <td class="px-4 py-3"><a href="orders.php?id=<?= $o['id'] ?>" class="text-primary-600 hover:underline">View</a></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
