<?php
require_once 'config.php';

// Access Control
if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$message = '';
$error = '';

// Handle Status Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $order_id = intval($_POST['order_id']);
    $new_status = $_POST['status'];
    
    if (in_array($new_status, ['pending', 'shipped', 'delivered'])) {
        $stmt = $pdo->prepare("UPDATE orders SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $order_id]);
        $message = "Order status updated successfully.";
    }
}

// Fetch all orders with user names
$orders = $pdo->query("SELECT o.*, u.full_name, u.email FROM orders o JOIN users u ON o.user_id = u.id ORDER BY o.id DESC")->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 
        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="admin-container">
    <aside class="sidebar">
        <ul class="sidebar-menu">
            <li>
                <a href="admin_dashboard.php" class="sidebar-link">📊 Dashboard Overview</a>
            </li>
            <li>
                <a href="admin_products.php" class="sidebar-link">👗 Manage Clothes</a>
            </li>
            <li>
                <a href="admin_orders.php" class="sidebar-link active">📦 Manage Orders</a>
            </li>
            <li>
                <a href="index.php" class="sidebar-link" style="margin-top: 30px; border-top: 1px solid var(--gray-border); padding-top: 20px;">🌐 Go to Shop</a>
            </li>
        </ul>
    </aside>

    <main class="admin-main">
        <div class="section-title">
            <span>Manage Customer Orders</span>
        </div>

        <?php if (!empty($message)): ?>
            <div class="alert alert-success"><?php echo $message; ?></div>
        <?php endif; ?>

        <div class="table-container">
            <h3 style="font-weight: 700; margin-bottom: 20px;">All Orders List</h3>
            <?php if (empty($orders)): ?>
                <p style="color: var(--text-muted); text-align: center; padding: 20px;">No customer orders placed yet.</p>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer Info</th>
                            <th>Items Ordered</th>
                            <th>Net Total</th>
                            <th>Shipping Address</th>
                            <th>Status Control</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order): ?>
                            <tr>
                                <td>
                                    <strong>#ORD-<?php echo str_pad($order['id'], 6, '0', STR_PAD_LEFT); ?></strong>
                                    <div style="font-size: 11px; color: var(--text-muted); margin-top: 5px;">
                                        <?php echo date('d M Y H:i', strtotime($order['created_at'])); ?>
                                    </div>
                                </td>
                                <td>
                                    <div><strong><?php echo htmlspecialchars($order['full_name']); ?></strong></div>
                                    <div style="font-size: 12px; color: var(--text-muted);"><?php echo htmlspecialchars($order['email']); ?></div>
                                </td>
                                <td>
                                    <ul style="list-style: none; padding: 0; font-size: 12px; line-height: 1.4;">
                                        <?php if (isset($items_by_order[$order['id']])): ?>
                                            <?php foreach ($items_by_order[$order['id']] as $item): ?>
                                                <li>- <?php echo htmlspecialchars($item['name']); ?> (x<?php echo $item['quantity']; ?>)</li>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </ul>
                                </td>
                                <td>
                                    <strong>฿<?php echo number_format($order['net_amount'], 2); ?></strong>
                                    <?php if ($order['discount_applied'] > 0): ?>
                                        <div style="font-size: 11px; color: var(--danger);">Disc: -฿<?php echo number_format($order['discount_applied'], 2); ?></div>
                                    <?php endif; ?>
                                    <div style="font-size: 11px; color: var(--success);">Earn: +<?php echo $order['points_earned']; ?> pts</div>
                                </td>
                                <td style="max-width: 250px; font-size: 13px;">
                                    <?php echo htmlspecialchars($order['shipping_address']); ?>
                                </td>
                                <td>
                                    <form action="admin_orders.php" method="POST" style="display: flex; gap: 8px; align-items: center;">
                                        <input type="hidden" name="order_id" value="<?php echo $order['id']; ?>">
                                        <select name="status" class="form-control" style="padding: 6px 12px; font-size: 12px; width: 110px;">
                                            <option value="pending" <?php echo $order['status'] === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                            <option value="shipped" <?php echo $order['status'] === 'shipped' ? 'selected' : ''; ?>>Shipped</option>
                                            <option value="delivered" <?php echo $order['status'] === 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                                        </select>
                                        <button type="submit" name="update_status" class="btn btn-primary" style="padding: 6px 12px; font-size: 12px;">Update</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </main>
</div>

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