<?php
/**
 * Colex Screenshot Upload API
 *
 * Handles image uploads for Colex chat conversations. Saves via the
 * shared ScreenshotStorage class (same driver seam trade screenshots use
 * — see that class's own header comment re: the future Cloudflare R2
 * move) and records ownership in colex_screenshots, then returns a URL
 * pointing at the ownership-checked GET /api/colex/view-screenshot
 * endpoint — never a raw static path.
 *
 * 2026-08-19 security fix (pre-launch audit remediation, Phase 3): this
 * endpoint previously saved real files to a plain, Apache-served static
 * directory with no per-image DB row and no per-request ownership check
 * at all — anyone with the (unguessable, but not access-controlled) URL
 * could read the file, forever, with no session required. Rebuilt to
 * mirror api/journal/upload-screenshot.php's already-fixed pattern
 * exactly. The on-disk directory layout (public/uploads/screenshots/
 * {userId}/{filename}) is UNCHANGED from before this fix — only the
 * returned URL and the new ownership row are new — so no already-
 * uploaded file needs moving. public/uploads/screenshots/ now also has
 * its own .htaccess (Require all denied), closing off the old direct
 * static path as a bypass alongside the new endpoint.
 *
 * Optional `conversation_id` form field: if provided, verified to belong
 * to this user before being attached to the ownership row (a foreign
 * conversation_id is silently dropped, never trusted). Not currently read
 * back anywhere — see colex_screenshots' own migration comment: Colex's
 * chat.php endpoint doesn't yet persist an uploaded screenshot's URL into
 * a message's `cards`, a real, separate, non-security gap, flagged but
 * out of scope for this fix.
 */

// Ensure this file is accessed through the router
if (!isset($auth) || !isset($db)) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Direct access not permitted.']);
    exit;
}

require_once __DIR__ . '/../../src/ScreenshotStorage.php';

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

if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Authentication required', 'message' => 'Please sign in to upload screenshots']);
    exit;
}

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

$userId = $auth->getUserId();

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

// Optional, ownership-verified before trusting it.
$conversationId = null;
$rawConversationId = trim((string)($_POST['conversation_id'] ?? ''));
if ($rawConversationId !== '') {
    $owned = $db->raw(
        'SELECT id FROM colex_conversations WHERE id = ? AND user_id = ?',
        [$rawConversationId, $userId]
    );
    if (!empty($owned)) {
        $conversationId = $rawConversationId;
    }
}

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

try {
    $id = $db->insert('colex_screenshots', [
        'conversation_id' => $conversationId,
        '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'],
    ]);

    // getimagesize() needs the real path on disk — cheap, always available
    // (no GD dependency), used only for display sizing.
    $realPath = ScreenshotStorage::localPathFor($stored['storage_key'], 'screenshots');
    $dimensions = @getimagesize($realPath);

    echo json_encode([
        'success' => true,
        'id' => $id,
        'url' => '/traderalign/api/colex/view-screenshot?id=' . $id,
        'filename' => $stored['original_filename'],
        'mime_type' => $stored['mime_type'],
        'width' => $dimensions ? $dimensions[0] : 0,
        'height' => $dimensions ? $dimensions[1] : 0,
        'size' => $stored['file_size_bytes'],
    ]);
} catch (\Throwable $e) {
    // Same defensive pattern as api/journal/upload-screenshot.php's own
    // 2026-08-19 fix: the file already landed on disk above — clean it up
    // if the DB row never made it, so a failed save doesn't leave an
    // orphaned, ownerless file behind.
    error_log('colex/upload-screenshot.php DB insert failed: ' . $e->getMessage());
    ScreenshotStorage::delete($stored['storage_driver'], $stored['storage_key'], 'screenshots');
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to save screenshot. Please try again.']);
}
