<?php
// api/chat_media_download.php
// Authenticated streaming endpoint for chat images/documents/audio/video.

if (ob_get_level() === 0) ob_start();
ini_set('display_errors', '0');
ini_set('html_errors', '0');
error_reporting(E_ALL);

function rvu_chat_download_bootstrap_error(string $message, int $status = 500): never {
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['detail' => $message], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    require_once __DIR__ . '/../config/database.php';
    require_once __DIR__ . '/chat_media_common.php';
} catch (Throwable $e) {
    rvu_chat_download_bootstrap_error('Chat media backend could not start: ' . $e->getMessage());
}

rvu_chat_media_cors();
if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code(204);
    exit;
}

try {
    if (strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'GET') {
        rvu_chat_media_json(['detail' => 'Only GET is supported.'], 405);
    }

    rvu_ensure_chat_media_table($pdo);
    rvu_chat_media_require_user($pdo);

    $token = strtolower(trim((string)($_GET['token'] ?? '')));
    if (!preg_match('/^[a-f0-9]{64}$/', $token)) {
        rvu_chat_media_json(['detail' => 'A valid media token is required.'], 422);
    }

    $stmt = $pdo->prepare("SELECT original_name, relative_path, mime_type, size_bytes
                           FROM chat_media_uploads
                           WHERE access_token = ? AND deleted_at IS NULL LIMIT 1");
    $stmt->execute([$token]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) rvu_chat_media_json(['detail' => 'Attachment not found.'], 404);

    $root = realpath(__DIR__ . '/..');
    if (!$root) throw new RuntimeException('Application root could not be resolved.');
    $relative = ltrim(str_replace(['\\', '..'], ['/', ''], (string)$row['relative_path']), '/');
    $fullPath = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative);
    if (!is_file($fullPath)) rvu_chat_media_json(['detail' => 'The attachment file is missing from storage.'], 404);

    $size = filesize($fullPath);
    if ($size === false) throw new RuntimeException('Attachment size could not be read.');

    $start = 0;
    $end = $size - 1;
    $status = 200;
    $rangeHeader = trim((string)($_SERVER['HTTP_RANGE'] ?? ''));
    if ($rangeHeader !== '' && preg_match('/^bytes=(\d*)-(\d*)$/', $rangeHeader, $matches)) {
        $rangeStart = $matches[1] === '' ? null : (int)$matches[1];
        $rangeEnd = $matches[2] === '' ? null : (int)$matches[2];

        if ($rangeStart === null && $rangeEnd !== null) {
            $length = min($rangeEnd, $size);
            $start = max(0, $size - $length);
        } elseif ($rangeStart !== null) {
            $start = $rangeStart;
        }
        if ($rangeEnd !== null) $end = min($rangeEnd, $size - 1);

        if ($start < 0 || $start > $end || $start >= $size) {
            while (ob_get_level() > 0) @ob_end_clean();
            http_response_code(416);
            header('Content-Range: bytes */' . $size);
            exit;
        }
        $status = 206;
    }

    $length = $end - $start + 1;
    while (ob_get_level() > 0) @ob_end_clean();
    http_response_code($status);
    header('Content-Type: ' . ((string)$row['mime_type'] ?: 'application/octet-stream'));
    header('Content-Length: ' . $length);
    header('Accept-Ranges: bytes');
    if ($status === 206) {
        header("Content-Range: bytes $start-$end/$size");
    }
    header('X-Content-Type-Options: nosniff');
    header('Cache-Control: private, max-age=3600');

    $original = rvu_chat_media_clean_filename((string)$row['original_name']);
    $disposition = isset($_GET['inline']) && in_array(strtolower((string)$_GET['inline']), ['1', 'true', 'yes'], true)
        ? 'inline'
        : 'attachment';
    header("Content-Disposition: $disposition; filename*=UTF-8''" . rawurlencode($original));

    $fp = fopen($fullPath, 'rb');
    if ($fp === false) throw new RuntimeException('Attachment could not be opened.');
    if ($start > 0) fseek($fp, $start);

    $remaining = $length;
    while ($remaining > 0 && !feof($fp)) {
        $chunk = fread($fp, min(1024 * 1024, $remaining));
        if ($chunk === false) break;
        echo $chunk;
        $remaining -= strlen($chunk);
        if (function_exists('fastcgi_finish_request')) {
            // Do not call fastcgi_finish_request here; it would end a partial stream.
        }
        flush();
    }
    fclose($fp);
    exit;
} catch (Throwable $e) {
    rvu_chat_media_json(['detail' => 'Unable to deliver chat attachment: ' . $e->getMessage()], 500);
}
