<?php
/**
 * GET /api/journal/view-screenshot?id=X — the ONE place a trade screenshot
 * is actually served from. Ownership-checked (2026-08-19 security fix):
 * previously screenshots were served as plain static files under
 * public/uploads/trade-screenshots/{userId}/{tradeId}/{filename} — Apache
 * served them to anyone who had the URL, with no per-request check that
 * the requester was the owner, relying entirely on the filename's
 * unguessability. This routes every real read through the same
 * user_id-scoped ownership check every other resource in this app already
 * gets (via ScopedDb::selectById()), matching the spec's explicit "file
 * access should go through the same ownership check as any other
 * resource" requirement.
 *
 * public/uploads/trade-screenshots/ itself is now .htaccess-blocked from
 * direct web access (see that directory's own .htaccess) — this endpoint
 * is the only way in, even for the owner.
 */
require_once __DIR__ . '/../../src/ScreenshotStorage.php';

$userId = $auth->requireAuth();

$screenshotId = trim((string)($_GET['id'] ?? ''));
if ($screenshotId === '') {
    http_response_code(400);
    exit('Missing id');
}

$row = $db->selectById('trade_screenshots', $screenshotId);
if (!$row) {
    http_response_code(404);
    exit('Not found');
}

if ($row['storage_driver'] !== 'local') {
    http_response_code(500);
    exit('Unsupported storage driver');
}

$path = ScreenshotStorage::localPathFor($row['storage_key']);
if (!is_file($path)) {
    http_response_code(404);
    exit('Not found');
}

header('Content-Type: ' . ($row['mime_type'] ?: 'application/octet-stream'));
header('Content-Length: ' . filesize($path));
header('Cache-Control: private, max-age=3600');
header('X-Content-Type-Options: nosniff');
// Never let a served image execute as HTML/script even if mime_type were
// ever wrong — Content-Disposition: inline still displays it normally in
// an <img>, this only affects what happens if someone navigates to the
// URL directly with an unexpected stored mime_type.
header('Content-Security-Policy: default-src \'none\'; sandbox');
readfile($path);
