<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

header('Content-Type: application/json');
hw_require_auth(['admin']);

try {
    $pdo = hw_db();
    
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $offset = ($page - 1) * $limit;
    $search = isset($_GET['search']) ? '%' . $_GET['search'] . '%' : '%';

    // Get total count
    $countStmt = $pdo->prepare('SELECT COUNT(*) as total FROM orders WHERE id LIKE ? OR user_id LIKE ?');
    $countStmt->execute([$search, $search]);
    $total = $countStmt->fetch()['total'];

    // Get orders with customer and item info
    $stmt = $pdo->prepare('
        SELECT 
            o.id,
            o.user_id,
            o.total_amount,
            o.status,
            o.payment_status,
            o.created_at,
            o.updated_at,
            CONCAT(u.first_name, " ", u.last_name) as customer_name,
            u.email as customer_email,
            COUNT(oi.id) as item_count
        FROM orders o
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN order_items oi ON o.id = oi.order_id
        WHERE o.id LIKE ? OR o.user_id LIKE ?
        GROUP BY o.id
        ORDER BY o.created_at DESC
        LIMIT ? OFFSET ?
    ');
    $stmt->execute([$search, $search, $limit, $offset]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        'success' => true,
        'orders' => $orders,
        'pagination' => [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit)
        ]
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Failed to load orders: ' . $e->getMessage()
    ]);
}
