<?php
// api/news_videos.php
// One optional video per news post. Maximum 10 MB.

declare(strict_types=1);

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

/** Convert PHP's upload-size settings such as 2M or 512K to bytes. */
function rvu_video_ini_bytes(string $value): int {
    $value = trim($value);
    if ($value === '') return 0;
    $unit = strtolower(substr($value, -1));
    $number = (float)$value;
    if ($unit === 'g') return (int)($number * 1024 * 1024 * 1024);
    if ($unit === 'm') return (int)($number * 1024 * 1024);
    if ($unit === 'k') return (int)($number * 1024);
    return (int)$number;
}

try {
    rvu_ensure_news_tables($pdo);
    $user = rvu_news_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    $path = trim((string)($_SERVER['PATH_INFO'] ?? ''), '/');
    $videoId = ctype_digit($path) ? (int)$path : null;

    if ($method === 'POST') {
        // PHP can discard both $_POST and $_FILES when post_max_size is hit.
        // Detect that first so the client gets a useful message instead of
        // the misleading "news_id is required" response.
        $contentLength = (int)($_SERVER['CONTENT_LENGTH'] ?? 0);
        $postLimit = rvu_video_ini_bytes((string)ini_get('post_max_size'));
        if ($postLimit > 0 && $contentLength > $postLimit) {
            rvu_news_json([
                'detail' => 'The video request is larger than this server allows. Set PHP post_max_size to at least 12M and upload_max_filesize to 10M, then restart the web server. The app limit remains 10 MB per video.',
            ], 413);
        }

        $newsId = (int)($_POST['news_id'] ?? 0);
        if ($newsId <= 0) rvu_news_json(['detail' => 'A valid news_id is required.'], 422);

        $stmt = $pdo->prepare('SELECT author_id FROM campus_news WHERE id = ?');
        $stmt->execute([$newsId]);
        $authorId = $stmt->fetchColumn();
        if (!$authorId) rvu_news_json(['detail' => 'News article not found.'], 404);
        if (!rvu_news_can_manage($user, (int)$authorId)) {
            rvu_news_json(['detail' => 'You can only attach video to your own news article.'], 403);
        }

        $existingStmt = $pdo->prepare('SELECT id FROM campus_news_videos WHERE news_id = ? LIMIT 1');
        $existingStmt->execute([$newsId]);
        if ($existingStmt->fetchColumn()) {
            rvu_news_json(['detail' => 'This post already has a video. Remove it before uploading another one.'], 422);
        }

        if (!isset($_FILES['video'])) rvu_news_json(['detail' => 'No video was selected.'], 422);
        $file = $_FILES['video'];
        $error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);
        if ($error !== UPLOAD_ERR_OK) {
            if (in_array($error, [UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE], true)) {
                rvu_news_json(['detail' => 'The video is larger than the server upload limit. Increase PHP upload_max_filesize/post_max_size and keep the app limit at 10 MB.'], 422);
            }
            rvu_news_json(['detail' => 'The selected video could not be uploaded.'], 422);
        }

        $size = (int)($file['size'] ?? 0);
        if ($size <= 0) rvu_news_json(['detail' => 'The selected video is empty.'], 422);
        if ($size > 10 * 1024 * 1024) {
            rvu_news_json(['detail' => 'Video must not exceed 10 MB.'], 422);
        }

        $tmp = (string)$file['tmp_name'];
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = (string)$finfo->file($tmp);
        $allowed = [
            'video/mp4' => 'mp4',
            'video/webm' => 'webm',
            'video/quicktime' => 'mov',
        ];
        if (!isset($allowed[$mime])) {
            rvu_news_json(['detail' => 'Only MP4, WebM and MOV video files are allowed. MP4 is recommended for widest playback support.'], 422);
        }

        $uploadDir = __DIR__ . '/../uploads/news/videos';
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
            throw new RuntimeException('Unable to create uploads/news/videos directory.');
        }

        $filename = 'video_' . gmdate('Ymd_His') . '_' . bin2hex(random_bytes(10)) . '.' . $allowed[$mime];
        $destination = $uploadDir . DIRECTORY_SEPARATOR . $filename;
        if (!move_uploaded_file($tmp, $destination)) {
            throw new RuntimeException('Failed to store the video on the server.');
        }

        $relative = 'uploads/news/videos/' . $filename;
        $originalName = trim((string)($file['name'] ?? 'Campus video')) ?: 'Campus video';
        $insert = $pdo->prepare('INSERT INTO campus_news_videos (news_id, video_path, original_name, mime_type, size_bytes) VALUES (?, ?, ?, ?, ?) RETURNING id, created_at');
        $insert->execute([$newsId, $relative, mb_substr($originalName, 0, 255), $mime, $size]);
        $created = $insert->fetch(PDO::FETCH_ASSOC);

        rvu_news_json([
            'message' => 'Video uploaded.',
            'video' => [
                'id' => (int)$created['id'],
                'path' => $relative,
                'file_name' => $originalName,
                'mime_type' => $mime,
                'size_bytes' => $size,
                'created_at' => $created['created_at'],
            ],
        ], 201);
    }

    if ($method === 'DELETE' && $videoId !== null) {
        $stmt = $pdo->prepare("SELECT v.video_path, n.author_id
                               FROM campus_news_videos v
                               INNER JOIN campus_news n ON n.id = v.news_id
                               WHERE v.id = ?");
        $stmt->execute([$videoId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) rvu_news_json(['detail' => 'News video not found.'], 404);
        if (!rvu_news_can_manage($user, (int)$row['author_id'])) {
            rvu_news_json(['detail' => 'You cannot remove this video.'], 403);
        }

        $pdo->prepare('DELETE FROM campus_news_videos WHERE id = ?')->execute([$videoId]);
        rvu_news_delete_media_file((string)$row['video_path']);
        rvu_news_json(['message' => 'Video removed.']);
    }

    rvu_news_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_news_json(['detail' => 'News video server error: ' . $e->getMessage()], 500);
}
