<?php
declare(strict_types=1);

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

rvu_ensure_announcement_tables($pdo);
$user = rvu_announcement_user($pdo);
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

function rvu_announcement_upload_root(): string {
    $root = __DIR__ . '/../uploads/announcements';
    if (!is_dir($root) && !mkdir($root, 0775, true) && !is_dir($root)) {
        rvu_announcement_json(['detail' => 'Unable to create announcement upload directory.'], 500);
    }
    return $root;
}

function rvu_announcement_make_image_thumbnail(string $source, string $target, string $mime): bool {
    if (!extension_loaded('gd')) return false;
    $create = match ($mime) {
        'image/jpeg' => 'imagecreatefromjpeg',
        'image/png' => 'imagecreatefrompng',
        'image/webp' => 'imagecreatefromwebp',
        default => null,
    };
    if ($create === null || !function_exists($create)) return false;
    $src = @$create($source);
    if (!$src) return false;
    $w = imagesx($src);
    $h = imagesy($src);
    if ($w <= 0 || $h <= 0) {
        imagedestroy($src);
        return false;
    }
    $maxW = 1200;
    $maxH = 675;
    $ratio = min($maxW / $w, $maxH / $h, 1);
    $nw = max(1, (int)round($w * $ratio));
    $nh = max(1, (int)round($h * $ratio));
    $dst = imagecreatetruecolor($nw, $nh);
    if (in_array($mime, ['image/png', 'image/webp'], true)) {
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
    }
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $nw, $nh, $w, $h);
    $ok = imagewebp($dst, $target, 82);
    imagedestroy($src);
    imagedestroy($dst);
    return $ok;
}

if ($method === 'POST') {
    $announcementId = (int)($_POST['announcement_id'] ?? 0);
    $type = strtolower(trim((string)($_POST['media_type'] ?? 'image')));
    if ($announcementId <= 0) rvu_announcement_json(['detail' => 'announcement_id is required.'], 422);
    $announcement = rvu_announcement_fetch($pdo, $announcementId, (int)$user['id']);
    if (!$announcement) rvu_announcement_json(['detail' => 'Announcement not found.'], 404);
    if (!rvu_announcement_can_manage($user, (int)$announcement['author_id'])) rvu_announcement_json(['detail' => 'You cannot upload media to this announcement.'], 403);

    $root = rvu_announcement_upload_root();
    $finfo = new finfo(FILEINFO_MIME_TYPE);

    if ($type === 'video') {
        if (!isset($_FILES['video']) || !is_uploaded_file($_FILES['video']['tmp_name'])) rvu_announcement_json(['detail' => 'Video file is required.'], 422);
        $file = $_FILES['video'];
        if ((int)$file['size'] > 10 * 1024 * 1024) rvu_announcement_json(['detail' => 'Video must not exceed 10 MB.'], 422);
        $mime = $finfo->file($file['tmp_name']) ?: '';
        $allowed = ['video/mp4' => 'mp4', 'video/webm' => 'webm', 'video/quicktime' => 'mov'];
        if (!isset($allowed[$mime])) rvu_announcement_json(['detail' => 'Only MP4, WebM and MOV videos are allowed.'], 422);
        $count = $pdo->prepare("SELECT COUNT(*) FROM campus_announcement_media WHERE announcement_id = ? AND media_type = 'video'");
        $count->execute([$announcementId]);
        if ((int)$count->fetchColumn() >= 1) rvu_announcement_json(['detail' => 'Only one video is allowed per announcement.'], 422);
        $name = 'announcement_' . $announcementId . '_video_' . bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
        $absolute = $root . DIRECTORY_SEPARATOR . $name;
        if (!move_uploaded_file($file['tmp_name'], $absolute)) rvu_announcement_json(['detail' => 'Unable to save video.'], 500);
        $relative = 'uploads/announcements/' . $name;
        $stmt = $pdo->prepare("INSERT INTO campus_announcement_media (announcement_id, media_type, media_path, thumbnail_path, size_bytes, position)
                               VALUES (?, 'video', ?, NULL, ?, 0) RETURNING id");
        $stmt->execute([$announcementId, $relative, (int)$file['size']]);
        rvu_announcement_json(['data' => ['id' => (int)$stmt->fetchColumn(), 'announcement_id' => $announcementId, 'type' => 'video', 'path' => $relative, 'thumbnail_path' => '', 'size_bytes' => (int)$file['size']]], 201);
    }

    $files = $_FILES['images'] ?? null;
    if (!$files || !isset($files['name']) || !is_array($files['name'])) rvu_announcement_json(['detail' => 'At least one image is required.'], 422);
    $count = $pdo->prepare("SELECT COUNT(*) FROM campus_announcement_media WHERE announcement_id = ? AND media_type = 'image'");
    $count->execute([$announcementId]);
    $existing = (int)$count->fetchColumn();
    $remaining = 6 - $existing;
    if ($remaining <= 0) rvu_announcement_json(['detail' => 'This announcement already has 6 pictures.'], 422);

    $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
    $result = [];
    $total = min(count($files['name']), $remaining);
    for ($i = 0; $i < $total; $i++) {
        if (($files['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) continue;
        $tmp = $files['tmp_name'][$i];
        if (!is_uploaded_file($tmp)) continue;
        if ((int)$files['size'][$i] > 8 * 1024 * 1024) continue;
        $mime = $finfo->file($tmp) ?: '';
        if (!isset($allowed[$mime])) continue;
        $base = 'announcement_' . $announcementId . '_' . bin2hex(random_bytes(8));
        $name = $base . '.' . $allowed[$mime];
        $absolute = $root . DIRECTORY_SEPARATOR . $name;
        if (!move_uploaded_file($tmp, $absolute)) continue;
        $relative = 'uploads/announcements/' . $name;
        $thumbName = $base . '_thumb.webp';
        $thumbAbsolute = $root . DIRECTORY_SEPARATOR . $thumbName;
        $thumbRelative = '';
        if (rvu_announcement_make_image_thumbnail($absolute, $thumbAbsolute, $mime)) $thumbRelative = 'uploads/announcements/' . $thumbName;
        $position = $existing + $i;
        $stmt = $pdo->prepare("INSERT INTO campus_announcement_media (announcement_id, media_type, media_path, thumbnail_path, size_bytes, position)
                               VALUES (?, 'image', ?, ?, ?, ?) RETURNING id");
        $stmt->execute([$announcementId, $relative, $thumbRelative !== '' ? $thumbRelative : null, (int)$files['size'][$i], $position]);
        $result[] = ['id' => (int)$stmt->fetchColumn(), 'announcement_id' => $announcementId, 'type' => 'image', 'path' => $relative, 'thumbnail_path' => $thumbRelative, 'size_bytes' => (int)$files['size'][$i]];
    }
    if (!$result) rvu_announcement_json(['detail' => 'No valid images were uploaded.'], 422);
    rvu_announcement_json(['data' => $result], 201);
}

if ($method === 'DELETE') {
    $mediaId = (int)($_GET['id'] ?? 0);
    if ($mediaId <= 0) rvu_announcement_json(['detail' => 'Media id is required.'], 422);
    $stmt = $pdo->prepare("SELECT m.id, m.media_path, m.thumbnail_path, a.author_id
                           FROM campus_announcement_media m
                           INNER JOIN campus_announcements a ON a.id = m.announcement_id
                           WHERE m.id = ? LIMIT 1");
    $stmt->execute([$mediaId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) rvu_announcement_json(['detail' => 'Media not found.'], 404);
    if (!rvu_announcement_can_manage($user, (int)$row['author_id'])) rvu_announcement_json(['detail' => 'You cannot delete this media.'], 403);
    $pdo->prepare('DELETE FROM campus_announcement_media WHERE id = ?')->execute([$mediaId]);
    $root = realpath(__DIR__ . '/..');
    if ($root) {
        foreach (['media_path', 'thumbnail_path'] as $key) {
            $rel = trim((string)($row[$key] ?? ''));
            if ($rel === '' || strpos($rel, '..') !== false) continue;
            $path = $root . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $rel);
            if (is_file($path)) @unlink($path);
        }
    }
    rvu_announcement_json(['message' => 'Media deleted.']);
}

rvu_announcement_json(['detail' => 'Method not allowed.'], 405);
