<?php
session_start();
require_once 'db.php'; // ✅ Updated to use db.php (PDO connection)

// Redirect if not logged in or session expired
if (!isset($_SESSION['user_id']) || (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 600))) {
    if (isset($_SESSION['user_id'])) unset($_SESSION['user_id']);
    $_SESSION['redirect_after_login'] = $_SERVER['REQUEST_URI'];
    header("Location: login.php");
    exit();
}
$_SESSION['last_activity'] = time();

// Fetch orders from DB (using PDO)
$stmt = $conn->prepare("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");
$stmt->execute();
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 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'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Orders Overview - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body {
    margin: 0;
    font-family: Arial, sans-serif;
    background: #000;
    color: #fff;
    overflow-x: hidden;
    position: relative;
}

/* Background animation */
@keyframes move-bg {
  0% { background-position: 0 0; }
  50% { background-position: 100% 100%; }
  100% { background-position: 0 0; }
}
body::before {
    content: "";
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: radial-gradient(circle at 50% 50%, rgba(255,255,255,0.08), rgba(0,0,0,1));
    background-size: 400% 400%;
    animation: move-bg 20s infinite linear;
    z-index: -1;
}

/* Page layout */
.main-content {
    padding: 40px 20px;
    max-width: 1000px;
    margin: auto;
}

h1 {
    text-align: center;
    margin-bottom: 40px;
    color: #fff;
}

/* Summary cards */
.card-container {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    margin-bottom: 30px;
    gap: 15px;
}
.card {
    background: #111;
    border: 1px solid #333;
    padding: 20px;
    border-radius: 10px;
    width: 200px;
    text-align: center;
    transition: transform 0.3s;
}
.card:hover { transform: scale(1.05); }

/* Search and filter */
input[type="text"], select {
    padding: 10px;
    margin: 10px 5px;
    border: 1px solid #444;
    background: #111;
    color: #fff;
    border-radius: 5px;
}

/* Table styling */
table {
    width: 100%;
    border-collapse: collapse;
    background: #111;
    color: #fff;
    border-radius: 10px;
    overflow: hidden;
}
th, td {
    padding: 12px 10px;
    text-align: left;
    border-bottom: 1px solid #333;
}
th {
    background: #000;
    font-weight: bold;
}
tr:hover {
    background: #222;
}
button.view-btn {
    background: #fff;
    color: #000;
    border: none;
    padding: 6px 12px;
    border-radius: 5px;
    cursor: pointer;
}
button.view-btn:hover {
    background: #ccc;
}

/* Modal */
.modal {
    display: none;
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(0,0,0,0.8);
    justify-content: center;
    align-items: center;
    z-index: 999;
}
.modal-content {
    background: #111;
    color: #fff;
    padding: 30px;
    border-radius: 10px;
    max-width: 400px;
    width: 90%;
    box-shadow: 0 0 20px rgba(255,255,255,0.2);
    position: relative;
    animation: fadeIn 0.4s ease;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}
.modal-close {
    position: absolute;
    top: 10px; right: 15px;
    cursor: pointer;
    font-size: 22px;
    color: #fff;
}
</style>
</head>
<body>

<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['firstName'] . ' ' . $order['lastName']) ?>"
                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['firstName'] . ' ' . $order['lastName']) ?></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>
</body>
</html>
