<?php
/**
 * GET /api/journal/trade-screenshots?trade_id=X — real list of a trade's
 * uploaded screenshots (id, url, filename, uploaded_at), ownership-
 * checked. Used to populate the upload/view modal on open and to refresh
 * it after an upload or delete, without a full page reload.
 */
require_once __DIR__ . '/../../src/ScreenshotStorage.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();

$tradeId = trim((string)($_GET['trade_id'] ?? ''));
if ($tradeId === '') {
    http_response_code(400);
    echo json_encode(['error' => 'trade_id is required']);
    exit;
}

$trade = $db->selectById('trades', $tradeId);
if (!$trade) {
    http_response_code(404);
    echo json_encode(['error' => 'Trade not found']);
    exit;
}

$rows = $db->select('trade_screenshots', 'trade_id = :tid', [':tid' => $tradeId], '*', 'uploaded_at DESC');

$screenshots = array_map(function ($r) {
    return [
        'id' => $r['id'],
        // 2026-08-19 security fix: ownership-checked endpoint by id, not
        // ScreenshotStorage::urlFor()'s old direct-static-file URL.
        'url' => '/traderalign/api/journal/view-screenshot?id=' . $r['id'],
        'filename' => $r['original_filename'],
        'uploaded_at' => $r['uploaded_at'],
    ];
}, $rows);

echo json_encode(['success' => true, 'screenshots' => $screenshots]);
