<?php
// api/news_images.php

declare(strict_types=1);

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

function rvu_make_news_thumbnail(string $source, string $destination, string $mime): bool {
    if (!extension_loaded('gd')) return false;

    $image = null;
    if ($mime === 'image/jpeg' && function_exists('imagecreatefromjpeg')) {
        $image = @imagecreatefromjpeg($source);
    } elseif ($mime === 'image/png' && function_exists('imagecreatefrompng')) {
        $image = @imagecreatefrompng($source);
    } elseif ($mime === 'image/webp' && function_exists('imagecreatefromwebp')) {
        $image = @imagecreatefromwebp($source);
    }
    if (!$image) return false;

    $width = imagesx($image);
    $height = imagesy($image);
    if ($width <= 0 || $height <= 0) {
        imagedestroy($image);
        return false;
    }

    $targetWidth = min(960, $width);
    $scale = $targetWidth / $width;
    $targetHeight = max(1, (int)round($height * $scale));

    $thumb = imagecreatetruecolor($targetWidth, $targetHeight);
    imagecopyresampled($thumb, $image, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);

    $ok = false;
    if ($mime === 'image/jpeg') {
        $ok = imagejpeg($thumb, $destination, 78);
    } elseif ($mime === 'image/png') {
        $ok = imagepng($thumb, $destination, 6);
    } elseif ($mime === 'image/webp' && function_exists('imagewebp')) {
        $ok = imagewebp($thumb, $destination, 78);
    }

    imagedestroy($thumb);
    imagedestroy($image);
    return $ok;
}

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

    if ($method === 'POST') {
        $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 images to your own news article.'], 403);
        }

        if (!isset($_FILES['images'])) rvu_news_json(['detail' => 'No images were selected.'], 422);

        $files = $_FILES['images'];
        $names = is_array($files['name']) ? $files['name'] : [$files['name']];
        $tmpNames = is_array($files['tmp_name']) ? $files['tmp_name'] : [$files['tmp_name']];
        $errors = is_array($files['error']) ? $files['error'] : [$files['error']];
        $sizes = is_array($files['size']) ? $files['size'] : [$files['size']];

        $countStmt = $pdo->prepare('SELECT COUNT(*) FROM campus_news_images WHERE news_id = ?');
        $countStmt->execute([$newsId]);
        $existingCount = (int)$countStmt->fetchColumn();
        if ($existingCount + count($names) > 6) {
            rvu_news_json(['detail' => 'A news article can contain a maximum of 6 images.'], 422);
        }

        $uploadDir = __DIR__ . '/../uploads/news/images';
        $thumbDir = __DIR__ . '/../uploads/news/thumbs';
        foreach ([$uploadDir, $thumbDir] as $dir) {
            if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
                throw new RuntimeException('Unable to create news media directory.');
            }
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $allowed = [
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/webp' => 'webp',
        ];

        $saved = [];
        $position = $existingCount;
        for ($i = 0; $i < count($names); $i++) {
            if ((int)$errors[$i] !== UPLOAD_ERR_OK) {
                throw new RuntimeException('One of the selected images could not be uploaded.');
            }
            if ((int)$sizes[$i] > 8 * 1024 * 1024) {
                throw new RuntimeException('Each news image must be 8 MB or smaller.');
            }

            $mime = $finfo->file($tmpNames[$i]);
            if (!isset($allowed[$mime])) {
                throw new RuntimeException('Only JPEG, PNG and WebP images are allowed.');
            }

            $token = gmdate('Ymd_His') . '_' . bin2hex(random_bytes(8));
            $filename = 'news_' . $token . '.' . $allowed[$mime];
            $destination = $uploadDir . DIRECTORY_SEPARATOR . $filename;
            if (!move_uploaded_file($tmpNames[$i], $destination)) {
                throw new RuntimeException('Failed to store a news image on the server.');
            }

            $relative = 'uploads/news/images/' . $filename;
            $thumbName = 'thumb_' . $token . '.' . $allowed[$mime];
            $thumbDestination = $thumbDir . DIRECTORY_SEPARATOR . $thumbName;
            $thumbnailRelative = '';
            if (rvu_make_news_thumbnail($destination, $thumbDestination, $mime)) {
                $thumbnailRelative = 'uploads/news/thumbs/' . $thumbName;
            }

            $insert = $pdo->prepare('INSERT INTO campus_news_images (news_id, image_path, thumbnail_path, position) VALUES (?, ?, ?, ?) RETURNING id');
            $insert->execute([$newsId, $relative, $thumbnailRelative !== '' ? $thumbnailRelative : null, $position++]);
            $saved[] = [
                'id' => (int)$insert->fetchColumn(),
                'path' => $relative,
                'thumbnail_path' => $thumbnailRelative,
            ];
        }

        rvu_news_json(['message' => 'Images uploaded.', 'images' => $saved], 201);
    }

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

        $pdo->prepare('DELETE FROM campus_news_images WHERE id = ?')->execute([$imageId]);
        rvu_news_delete_media_file((string)$row['image_path']);
        if (!empty($row['thumbnail_path'])) rvu_news_delete_media_file((string)$row['thumbnail_path']);
        rvu_news_json(['message' => 'Image removed.']);
    }

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