<?php
// Fetch orders from DB
$ordersResult = $conn->query("SELECT o.order_id, o.user_id, o.order_date, o.status, o.total, u.firstName, u.lastName, u.email 
                              FROM orders o 
                              JOIN users u ON o.user_id = u.id 
                              ORDER BY o.order_date DESC");

$orders = [];
while ($row = $ordersResult->fetch_assoc()) {
    $row['user'] = $row['firstName'] . ' ' . $row['lastName'];
    $orders[] = $row;
}

// Summary Cards
$totalOrders = count($orders);
$pendingOrders = count(array_filter($orders, fn($o) => $o['status']=='pending'));
$completedOrders = count(array_filter($orders, fn($o) => $o['status']=='completed'));
$cancelledOrders = count(array_filter($orders, fn($o) => $o['status']=='cancelled'));
?>
<div class="main-content">
    <h1>Orders Overview</h1>

    <!-- Summary Cards -->
    <div class="card-container">
        <div class="card"><h3>Total Orders</h3><p><?= $totalOrders ?></p></div>
        <div class="card"><h3>Pending</h3><p><?= $pendingOrders ?></p></div>
        <div class="card"><h3>Completed</h3><p><?= $completedOrders ?></p></div>
        <div class="card"><h3>Cancelled</h3><p><?= $cancelledOrders ?></p></div>
    </div>

    <!-- Search -->
    <div>
        <input type="text" id="searchInput" placeholder="Search by user or email">
        <select id="filterStatus">
            <option value="">All Status</option>
            <option value="pending">Pending</option>
            <option value="completed">Completed</option>
            <option value="cancelled">Cancelled</option>
        </select>
    </div>

    <!-- Orders Table -->
    <table id="ordersTable">
        <thead>
            <tr>
                <th>Order #</th>
                <th>User</th>
                <th>Email</th>
                <th>Total</th>
                <th>Status</th>
                <th>Order Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($orders as $order): ?>
            <tr data-id="<?= $order['order_id'] ?>"
                data-user="<?= htmlspecialchars($order['user']) ?>"
                data-email="<?= htmlspecialchars($order['email']) ?>"
                data-total="<?= $order['total'] ?>"
                data-status="<?= $order['status'] ?>"
                data-date="<?= $order['order_date'] ?>">
                <td>#<?= $order['order_id'] ?></td>
                <td><?= htmlspecialchars($order['user']) ?></td>
                <td><?= htmlspecialchars($order['email']) ?></td>
                <td><?= number_format($order['total'],2) ?></td>
                <td><?= ucfirst($order['status']) ?></td>
                <td><?= $order['order_date'] ?></td>
                <td><button class="view-btn">View</button></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Order Modal -->
<div class="modal" id="orderModal">
    <div class="modal-content">
        <span class="modal-close">&times;</span>
        <h2>Order Details</h2>
        <p><strong>Order #:</strong> <span id="modalOrderID"></span></p>
        <p><strong>User:</strong> <span id="modalUser"></span></p>
        <p><strong>Email:</strong> <span id="modalEmail"></span></p>
        <p><strong>Total:</strong> $<span id="modalTotal"></span></p>
        <p><strong>Status:</strong> <span id="modalStatus"></span></p>
        <p><strong>Date:</strong> <span id="modalDate"></span></p>
    </div>
</div>

<script>
// Modal functionality
const orderModal = document.getElementById('orderModal');
const modalCloseBtns = document.querySelectorAll('.modal-close');

modalCloseBtns.forEach(btn => btn.addEventListener('click', () => {
    btn.closest('.modal').style.display = 'none';
}));

document.querySelectorAll('.view-btn').forEach(btn => {
    btn.addEventListener('click', e => {
        const tr = e.target.closest('tr');
        document.getElementById('modalOrderID').textContent = tr.dataset.id;
        document.getElementById('modalUser').textContent = tr.dataset.user;
        document.getElementById('modalEmail').textContent = tr.dataset.email;
        document.getElementById('modalTotal').textContent = parseFloat(tr.dataset.total).toFixed(2);
        document.getElementById('modalStatus').textContent = tr.dataset.status;
        document.getElementById('modalDate').textContent = tr.dataset.date;
        orderModal.style.display = 'flex';
    });
});

// Search & filter
const searchInput = document.getElementById('searchInput');
const filterStatus = document.getElementById('filterStatus');
const tableRows = document.querySelectorAll('#ordersTable tbody tr');

function filterOrders() {
    const searchText = searchInput.value.toLowerCase();
    const statusFilter = filterStatus.value;
    tableRows.forEach(tr => {
        const user = tr.dataset.user.toLowerCase();
        const email = tr.dataset.email.toLowerCase();
        const status = tr.dataset.status;
        const matches = (user.includes(searchText) || email.includes(searchText)) &&
                        (statusFilter === '' || status === statusFilter);
        tr.style.display = matches ? '' : 'none';
    });
}

searchInput.addEventListener('input', filterOrders);
filterStatus.addEventListener('change', filterOrders);

// Close modal on outside click
window.addEventListener('click', e => {
    if(e.target.classList.contains('modal')) e.target.style.display='none';
});
</script>
