<?php
require_once '../includes/header.php';
require_once '../includes/require_admin.php';

// Check if we're marking orders as seen
if (isset($_GET['mark_seen']) && $_GET['mark_seen'] == 'all') {
    // Mark all orders as seen by setting a session variable with the current time
    $_SESSION['last_order_check'] = date('Y-m-d H:i:s');
    header("Location: " . SITE_URL . "/admin/orders.php");
    exit();
}

// Get the last check time from session, default to a long time ago if not set
$last_check_time = isset($_SESSION['last_order_check']) ? $_SESSION['last_order_check'] : '1970-01-01 00:00:00';

// Get all orders with user information
$stmt = $pdo->query("
    SELECT o.*, u.username, u.email 
    FROM orders o 
    JOIN users u ON o.user_id = u.id 
    ORDER BY o.order_date DESC
");
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Count new orders since last check
$new_orders_count = 0;
$has_new_orders = false;
foreach ($orders as $order) {
    if (strtotime($order['order_date']) > strtotime($last_check_time)) {
        $new_orders_count++;
        $has_new_orders = true;
    }
}
?>

<div class="container">
    <div class="admin-header">
        <h2>Manage Orders</h2>
        <?php if ($has_new_orders): ?>
            <div class="notification message success" id="newOrderNotification">
                <strong><?php echo $new_orders_count; ?> new order<?php echo $new_orders_count > 1 ? 's' : ''; ?> since your last visit!</strong>
                <a href="?mark_seen=all" class="btn btn-small btn-outline" style="float: right; margin-top: -5px;">Mark as Seen</a>
            </div>
        <?php endif; ?>
    </div>
    
    <div class="admin-nav">
        <ul>
            <li><a href="<?php echo SITE_URL; ?>/admin/index.php">Dashboard</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/products.php">Products</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/manage_users.php">Users</a></li>
            <li><a href="<?php echo SITE_URL; ?>/admin/orders.php" class="active">Orders</a></li>
        </ul>
    </div>
    
    <?php if (empty($orders)): ?>
        <p>No orders found.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table" id="ordersTable">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>User</th>
                        <th>Email</th>
                        <th>Total Amount</th>
                        <th>Date</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <tr <?php echo (strtotime($order['order_date']) > strtotime($last_check_time)) ? 'class="new-order"' : ''; ?>>
                            <td><?php echo $order['id']; ?></td>
                            <td><?php echo htmlspecialchars($order['username']); ?></td>
                            <td><?php echo htmlspecialchars($order['email']); ?></td>
                            <td>$<?php echo number_format($order['total_amount'], 2); ?></td>
                            <td><?php echo date('M j, Y g:i A', strtotime($order['order_date'])); ?></td>
                            <td>
                                <?php if (strtotime($order['order_date']) > strtotime($last_check_time)): ?>
                                    <span class="status-new">NEW</span>
                                <?php else: ?>
                                    <span class="status-seen">SEEN</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="<?php echo SITE_URL; ?>/admin/order_details.php?id=<?php echo $order['id']; ?>" class="btn btn-outline btn-small">View Details</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<style>
.new-order {
    background-color: #e8f4f8;
    font-weight: bold;
}

.status-new {
    background-color: #2ecc71;
    color: white;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 0.8em;
}

.status-seen {
    background-color: #95a5a6;
    color: white;
    padding: 3px 8px;
    border-radius: 4px;
    font-size: 0.8em;
}

.notification.message.success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
}
</style>

<script>
// Auto-hide notification after 10 seconds
setTimeout(function() {
    var notification = document.getElementById('newOrderNotification');
    if (notification) {
        notification.style.display = 'none';
    }
}, 10000);

// Check for new orders every 30 seconds
setInterval(function() {
    fetch('<?php echo SITE_URL; ?>/admin/check_new_orders.php')
        .then(response => response.json())
        .then(data => {
            if (data.new_orders > 0) {
                // Show notification
                if (!document.getElementById('newOrderNotification')) {
                    var notificationHtml = `
                        <div class="notification message success" id="newOrderNotification">
                            <strong>${data.new_orders} new order${data.new_orders > 1 ? 's' : ''}!</strong>
                            <a href="?mark_seen=all" class="btn btn-small btn-outline" style="float: right; margin-top: -5px;">Mark as Seen</a>
                        </div>
                    `;
                    document.querySelector('.admin-header').insertAdjacentHTML('beforeend', notificationHtml);
                    
                    // Auto-hide after 10 seconds
                    setTimeout(function() {
                        var notification = document.getElementById('newOrderNotification');
                        if (notification) {
                            notification.style.display = 'none';
                        }
                    }, 10000);
                }
            }
        })
        .catch(error => {
            console.log('Error checking for new orders:', error);
        });
}, 30000);
</script>

<?php require_once '../includes/footer.php'; ?>