<?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 order_items oi
        LEFT JOIN orders o ON oi.order_id = o.id
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN products p ON oi.product_id = p.id
        WHERE CONCAT(u.first_name, " ", u.last_name) LIKE ?
        OR p.name LIKE ?
    ');
    $countStmt->execute([$search, $search]);
    $total = $countStmt->fetch()['total'];

    // Get payments (order items) with related info
    $stmt = $pdo->prepare('
        SELECT 
            oi.id as payment_id,
            oi.order_id,
            oi.product_id,
            oi.quantity,
            oi.price as amount,
            oi.created_at,
            CONCAT(u.first_name, " ", u.last_name) as customer_name,
            u.email as customer_email,
            p.name as product_name,
            o.payment_status as status,
            o.updated_at
        FROM order_items oi
        LEFT JOIN orders o ON oi.order_id = o.id
        LEFT JOIN users u ON o.user_id = u.id
        LEFT JOIN products p ON oi.product_id = p.id
        WHERE CONCAT(u.first_name, " ", u.last_name) LIKE ?
        OR p.name LIKE ?
        ORDER BY oi.created_at DESC
        LIMIT ? OFFSET ?
    ');
    $stmt->execute([$search, $search, $limit, $offset]);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Add default payment method (placeholder)
    foreach ($payments as &$payment) {
        $payment['payment_method'] = 'Credit Card';
    }

    echo json_encode([
        'success' => true,
        'payments' => $payments,
        '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 payments: ' . $e->getMessage()
    ]);
}
