<?php
// Admin orders view page
session_start();

if (empty($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require __DIR__ . '/db_config.php';

// Get all orders
$orders = [];
$result = $conn->query("
    SELECT id, user_id, user_name, user_email, total_price, status, order_date
    FROM orders
    ORDER BY order_date DESC
    LIMIT 100
");

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $orders[] = $row;
    }
}

// Get order details if viewing a specific order
$viewOrderId = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$viewOrder = null;
$viewOrderItems = [];

if ($viewOrderId > 0) {
    $stmt = $conn->prepare("SELECT * FROM orders WHERE id = ?");
    $stmt->bind_param('i', $viewOrderId);
    $stmt->execute();
    $res = $stmt->get_result();
    if ($res && $res->num_rows > 0) {
        $viewOrder = $res->fetch_assoc();
        
        // Get items for this order
        $itemsStmt = $conn->prepare("SELECT * FROM order_items WHERE order_id = ?");
        $itemsStmt->bind_param('i', $viewOrderId);
        $itemsStmt->execute();
        $itemsRes = $itemsStmt->get_result();
        while ($item = $itemsRes->fetch_assoc()) {
            $viewOrderItems[] = $item;
        }
        $itemsStmt->close();
    }
    $stmt->close();
}

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Orders - Admin</title>
    <link rel="stylesheet" href="styles.css">
</head>
<!-- <body class="admin-with-sidebar">
<php include __DIR__ . '/admin_sidebar.php'; ?> -->
<?php // Admin pages don't include the main site header ?>

<main class="admin-main-content" style="padding: 24px; margin-top: 0; margin-bottom: 24px;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
        <h1 style="font-size: 28px; margin: 0;">📋 Orders</h1>
<?php
// Default link
$dashboardLink = "admin_dashboard.php";

// Adjust based on role
if (isset($_SESSION['role'])) {
    switch ($_SESSION['role']) {
        case 'admin':
            $dashboardLink = "admin_dashboard.php";
            break;
        case 'subadmin':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        case 'editor':
            $dashboardLink = "subadmin_dashboard.php";
            break;
        default:
            $dashboardLink = "admin_dashboard.php"; // fallback
    }
}
?>

<a href="<?php echo $dashboardLink; ?>" class="back-btn">← Back to Dashboard</a>

<style>
.back-btn {
    background-color: orange;
    color: white;
    padding: 8px 14px;
    text-decoration: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
}
.back-btn:hover {
    background-color: darkorange;
}
</style>


        <!-- <a href="admin_dashboard.php" class="btn" style="background: #F07E2D; color:#fff;">← Back to Dashboard</a>
     -->
    </div>

    <?php if ($viewOrderId > 0 && $viewOrder): ?>
        <!-- Order Details View -->
        <div style="background: #fff; padding: 24px; border-radius: 8px; margin-bottom: 24px;">
            <h2>Order #<?php echo $viewOrder['id']; ?></h2>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin: 16px 0;">
                <div>
                    <strong>Customer:</strong> <?php echo htmlspecialchars($viewOrder['user_name']); ?>
                </div>
                <div>
                    <strong>Email:</strong> <?php echo htmlspecialchars($viewOrder['user_email']); ?>
                </div>
                <div>
                    <strong>Date:</strong> <?php echo date('M d, Y H:i', strtotime($viewOrder['order_date'])); ?>
                </div>
                <div>
                    <strong>Status:</strong> <span style="background: #e3f2fd; color: #1565c0; padding: 4px 8px; border-radius: 4px;"><?php echo htmlspecialchars($viewOrder['status']); ?></span>
                </div>
                <div>
                    <strong>Total:</strong> $<?php echo number_format($viewOrder['total_price'], 2); ?>
                </div>
            </div>

            <div style="margin: 16px 0;">
                <strong>Shipping Address:</strong>
                <p style="background: #f5f5f5; padding: 12px; border-radius: 4px; margin-top: 8px;">
                    <?php echo nl2br(htmlspecialchars($viewOrder['shipping_address'] ?? '')); ?>
                </p>
            </div>

            <div style="margin: 16px 0;">
                <strong>Items:</strong>
                <table style="width: 100%; border-collapse: collapse; margin-top: 8px;">
                    <thead>
                        <tr style="background: #f5f5f5;">
                            <th style="padding: 8px; text-align: left;">Product</th>
                            <th style="padding: 8px; text-align: center;">Qty</th>
                            <th style="padding: 8px; text-align: right;">Price</th>
                            <th style="padding: 8px; text-align: right;">Subtotal</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($viewOrderItems as $item): ?>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 8px;"><?php echo htmlspecialchars($item['product_title']); ?></td>
                            <td style="padding: 8px; text-align: center;"><?php echo $item['quantity']; ?></td>
                            <td style="padding: 8px; text-align: right;">$<?php echo number_format($item['product_price'], 2); ?></td>
                            <td style="padding: 8px; text-align: right;">$<?php echo number_format($item['subtotal'], 2); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div style="margin-top: 24px;">
                <a href="admin_orders.php" class="btn" style="background: #999;">Back to Orders</a>
            </div>
        </div>
    <?php else: ?>
        <!-- Orders List View -->
        <div style="background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
            <table style="width: 100%; border-collapse: collapse;">
                <thead style="background: #f5f5f5;">
                    <tr>
                        <th style="padding: 12px; text-align: left;">Order ID</th>
                        <th style="padding: 12px; text-align: left;">Customer</th>
                        <th style="padding: 12px; text-align: center;">Date</th>
                        <th style="padding: 12px; text-align: right;">Total</th>
                        <th style="padding: 12px; text-align: center;">Status</th>
                        <th style="padding: 12px; text-align: center;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)): ?>
                    <tr>
                        <td colspan="6" style="padding: 24px; text-align: center; color: #999;">No orders yet</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                        <tr style="border-bottom: 1px solid #eee;">
                            <td style="padding: 12px;"><strong>#<?php echo $order['id']; ?></strong></td>
                            <td style="padding: 12px;"><?php echo htmlspecialchars($order['user_name']); ?></td>
                            <td style="padding: 12px; text-align: center;"><?php echo date('M d, Y', strtotime($order['order_date'])); ?></td>
                            <td style="padding: 12px; text-align: right;">$<?php echo number_format($order['total_price'], 2); ?></td>
                            <td style="padding: 12px; text-align: center;">
                                <span style="background: #e3f2fd; color: #1565c0; padding: 4px 8px; border-radius: 4px; font-size: 12px;">
                                    <?php echo htmlspecialchars($order['status']); ?>
                                </span>
                            </td>
                            <td style="padding: 12px; text-align: center;">
                                <a href="?view=<?php echo $order['id']; ?>" class="btn" style="padding: 6px 12px; font-size: 12px;">View</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</main>

<?php include __DIR__ . '/footer.php'; ?>
<script>
function toggleAdminSidebar() {
    const sidebar = document.getElementById('adminSidebarContainer');
    const mainContent = document.querySelector('.admin-main-content');
    sidebar.classList.toggle('collapsed');
    mainContent.classList.toggle('with-collapsed-sidebar');
    localStorage.setItem('adminSidebarCollapsed', sidebar.classList.contains('collapsed') ? '1' : '0');
}
document.addEventListener('DOMContentLoaded', function() {
    const isCollapsed = localStorage.getItem('adminSidebarCollapsed') === '1';
    if (isCollapsed) {
        document.getElementById('adminSidebarContainer').classList.add('collapsed');
        document.querySelector('.admin-main-content').classList.add('with-collapsed-sidebar');
    }
});
</script>
</body>
</html>
