<?php
/**
 * GET /api/journal/trades-more — progressive-loading ("Show More") batch
 * endpoint for Journal Trades. Accepts the exact same filter params as
 * the Journal Trades page itself, plus offset/limit, and returns the next
 * batch of pre-rendered trade rows. Uses the same query/render functions
 * as the initial server-rendered page (src/JournalTradesQuery.php) so the
 * two can never disagree about which trades match or how they're ordered.
 *
 * $auth/$db are already available here — set up by index.php's router
 * before dispatching to this file (same pattern as api/strategy/load.php).
 */
require_once __DIR__ . '/../../src/JournalTradesQuery.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$userId = $auth->requireAuth();

$filters = buildJournalTradesFilters($_GET);
$offset  = max(0, (int)($_GET['offset'] ?? 0));
$limit   = max(1, min(100, (int)($_GET['limit'] ?? 10)));

$trades = journalTradesFetch($db, $userId, $filters, $offset, $limit);
$total  = journalTradesCount($db, $userId, $filters);

$html = '';
foreach ($trades as $t) {
    $html .= renderJournalTradeRowHtml($t);
}

echo json_encode([
    'html'    => $html,
    'count'   => count($trades),
    'loaded'  => $offset + count($trades),
    'total'   => $total,
    'hasMore' => ($offset + count($trades)) < $total,
]);
