<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';

mocker_admin_require_permission('market-requests');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

require_once __DIR__ . '/db.php';

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$sql = 'SELECT p.id, p.user_id, p.item_id, p.item_title, p.price, COALESCE(p.status, \'pending\') AS status, p.created_at,
               u.username, u.email
        FROM purchases p
        INNER JOIN users u ON u.id = p.user_id
        ORDER BY p.created_at DESC, p.id DESC';

$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

$out = [];
foreach ($rows as $row) {
    $out[] = [
        'id' => (int) $row['id'],
        'userId' => (int) $row['user_id'],
        'username' => $row['username'],
        'email' => $row['email'],
        'itemId' => $row['item_id'],
        'itemTitle' => $row['item_title'],
        'price' => (int) $row['price'],
        'status' => (string) ($row['status'] ?? 'pending'),
        'createdAt' => (int) $row['created_at'],
    ];
}

echo json_encode(
    [
        'ok' => true,
        'purchases' => $out,
    ],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
