<?php
// api/news_download.php
// Signed, low-memory downloads. Videos are streamed in chunks; multiple images
// are packaged server-side so Flutter never loads the complete download into RAM.

declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/news_common.php';

function rvu_download_stream_file(string $absolute, string $downloadName, string $contentType, bool $deleteAfter = false): void {
    if (!is_file($absolute) || !is_readable($absolute)) {
        http_response_code(404);
        echo 'File not found.';
        exit;
    }

    while (ob_get_level() > 0) @ob_end_clean();
    header('Content-Type: ' . $contentType);
    header('Content-Length: ' . filesize($absolute));
    header('Content-Disposition: attachment; filename="' . addcslashes($downloadName, '"\\') . '"');
    header('Cache-Control: private, no-store');
    header('X-Content-Type-Options: nosniff');

    $handle = fopen($absolute, 'rb');
    if (!$handle) {
        http_response_code(500);
        exit;
    }
    while (!feof($handle)) {
        echo fread($handle, 1024 * 1024); // 1 MB chunks
        flush();
    }
    fclose($handle);
    if ($deleteAfter && is_file($absolute)) @unlink($absolute);
    exit;
}

try {
    rvu_ensure_news_tables($pdo);
    $newsId = (int)($_GET['news_id'] ?? 0);
    $type = strtolower(trim((string)($_GET['type'] ?? '')));
    $expires = (int)($_GET['expires'] ?? 0);
    $signature = trim((string)($_GET['signature'] ?? ''));

    if ($newsId <= 0 || !in_array($type, ['images', 'video'], true) || $expires <= 0 || $signature === '') {
        http_response_code(400);
        echo 'Invalid download request.';
        exit;
    }
    if ($expires < time()) {
        http_response_code(410);
        echo 'This download link has expired.';
        exit;
    }

    $expected = rvu_news_download_signature($newsId, $type, $expires);
    if (!hash_equals($expected, $signature)) {
        http_response_code(403);
        echo 'Invalid download signature.';
        exit;
    }

    if ($type === 'video') {
        $stmt = $pdo->prepare('SELECT video_path, original_name, mime_type FROM campus_news_videos WHERE news_id = ? LIMIT 1');
        $stmt->execute([$newsId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) {
            http_response_code(404);
            echo 'Video not found.';
            exit;
        }
        $absolute = rvu_news_absolute_media_path((string)$row['video_path']);
        if (!$absolute) {
            http_response_code(404);
            echo 'Video not found.';
            exit;
        }
        $name = trim((string)$row['original_name']) ?: ('campus_news_video_' . $newsId . '.mp4');
        rvu_download_stream_file($absolute, $name, (string)$row['mime_type']);
    }

    $stmt = $pdo->prepare('SELECT image_path FROM campus_news_images WHERE news_id = ? ORDER BY position, id');
    $stmt->execute([$newsId]);
    $paths = $stmt->fetchAll(PDO::FETCH_COLUMN) ?: [];
    if (!$paths) {
        http_response_code(404);
        echo 'No pictures found.';
        exit;
    }

    if (count($paths) === 1) {
        $absolute = rvu_news_absolute_media_path((string)$paths[0]);
        if (!$absolute || !is_file($absolute)) {
            http_response_code(404);
            echo 'Picture not found.';
            exit;
        }
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = (string)$finfo->file($absolute);
        $extension = pathinfo($absolute, PATHINFO_EXTENSION) ?: 'jpg';
        rvu_download_stream_file($absolute, 'campus_news_' . $newsId . '_photo.' . $extension, $mime ?: 'application/octet-stream');
    }

    if (!class_exists('ZipArchive')) {
        http_response_code(500);
        echo 'PHP ZipArchive is required to download multiple pictures as one ZIP file.';
        exit;
    }

    $temp = tempnam(sys_get_temp_dir(), 'rvu_news_');
    if ($temp === false) throw new RuntimeException('Unable to create temporary ZIP file.');
    $zipPath = $temp . '.zip';
    @unlink($temp);

    $zip = new ZipArchive();
    if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
        throw new RuntimeException('Unable to create the pictures ZIP file.');
    }

    $added = 0;
    foreach ($paths as $index => $relative) {
        $absolute = rvu_news_absolute_media_path((string)$relative);
        if (!$absolute || !is_file($absolute)) continue;
        $extension = pathinfo($absolute, PATHINFO_EXTENSION) ?: 'jpg';
        $zip->addFile($absolute, 'photo_' . ($index + 1) . '.' . $extension);
        $added++;
    }
    $zip->close();

    if ($added === 0) {
        @unlink($zipPath);
        http_response_code(404);
        echo 'No downloadable pictures were found.';
        exit;
    }

    rvu_download_stream_file($zipPath, 'campus_news_' . $newsId . '_photos.zip', 'application/zip', true);
} catch (Throwable $e) {
    http_response_code(500);
    echo 'Download error: ' . $e->getMessage();
} finally {
    if (isset($zipPath) && is_string($zipPath) && is_file($zipPath)) @unlink($zipPath);
}
