<?php
/**
 * POST /api/journal/upload-screenshot — multipart/form-data
 * (trade_id, screenshot file). $auth/$db already set up by index.php's
 * router (same pattern as api/journal/update-note.php). Ownership is
 * enforced via ScopedDb::selectById() on the trade itself before
 * anything is written to disk or the database — a foreign trade_id
 * never even reaches ScreenshotStorage::store().
 */
require_once __DIR__ . '/../../src/ScreenshotStorage.php';

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

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

$userId = $auth->requireAuth();

$tradeId = trim((string)($_POST['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;
}

if (!isset($_FILES['screenshot'])) {
    http_response_code(400);
    echo json_encode(['error' => 'No file uploaded']);
    exit;
}

try {
    $stored = ScreenshotStorage::store($userId, $tradeId, $_FILES['screenshot']);
} catch (\RuntimeException $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
    exit;
}

try {
    $id = $db->insert('trade_screenshots', [
        'trade_id' => $tradeId,
        'storage_driver' => $stored['storage_driver'],
        'storage_key' => $stored['storage_key'],
        'original_filename' => $stored['original_filename'],
        'mime_type' => $stored['mime_type'],
        'file_size_bytes' => $stored['file_size_bytes'],
    ]);

    echo json_encode([
        'success' => true,
        'id' => $id,
        // 2026-08-19 security fix: served through the ownership-checked
        // view-screenshot endpoint (by id), not ScreenshotStorage::urlFor()'s
        // old direct-static-file URL — see that endpoint's own docblock.
        'url' => '/traderalign/api/journal/view-screenshot?id=' . $id,
        'filename' => $stored['original_filename'],
    ]);
} catch (\Throwable $e) {
    // 2026-08-19 security fix: this DB insert previously had no try/catch
    // at all — an uncaught exception here would propagate raw, which (if
    // display_errors were ever accidentally on) means a stack trace, and
    // otherwise a bare 500 with the file already saved to disk but no DB
    // row pointing at it. Same file was already uploaded to disk above —
    // best-effort cleanup so a failed save doesn't leave an orphaned file.
    error_log('journal/upload-screenshot.php DB insert failed: ' . $e->getMessage());
    ScreenshotStorage::delete($stored['storage_driver'], $stored['storage_key']);
    http_response_code(500);
    echo json_encode(['error' => 'Failed to save screenshot. Please try again.']);
}
