<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/events_common.php';

function rvu_event_thumbnail(string $source, string $target, string $mime): bool {
    if (!extension_loaded('gd')) return false;
    try {
        if ($mime === 'image/jpeg') $image = @imagecreatefromjpeg($source);
        elseif ($mime === 'image/png') $image = @imagecreatefrompng($source);
        elseif ($mime === 'image/webp' && function_exists('imagecreatefromwebp')) $image = @imagecreatefromwebp($source);
        else return false;
        if (!$image) return false;
        $width = imagesx($image);
        $height = imagesy($image);
        if ($width <= 0 || $height <= 0) {
            imagedestroy($image);
            return false;
        }
        $maxWidth = 1200;
        $scale = min(1, $maxWidth / $width);
        $newWidth = max(1, (int)round($width * $scale));
        $newHeight = max(1, (int)round($height * $scale));
        $thumb = imagecreatetruecolor($newWidth, $newHeight);
        if ($mime === 'image/png') {
            imagealphablending($thumb, false);
            imagesavealpha($thumb, true);
        }
        imagecopyresampled($thumb, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
        $ok = false;
        if ($mime === 'image/jpeg') $ok = imagejpeg($thumb, $target, 82);
        elseif ($mime === 'image/png') $ok = imagepng($thumb, $target, 6);
        elseif ($mime === 'image/webp' && function_exists('imagewebp')) $ok = imagewebp($thumb, $target, 82);
        imagedestroy($thumb);
        imagedestroy($image);
        return (bool)$ok;
    } catch (Throwable $e) {
        return false;
    }
}

try {
    rvu_ensure_event_social_tables($pdo);
    $user = rvu_event_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'POST') {
        $eventId = (int)($_POST['event_id'] ?? 0);
        $mediaType = strtolower(trim((string)($_POST['media_type'] ?? 'image')));
        if ($eventId <= 0) rvu_event_json(['detail' => 'A valid event_id is required.'], 422);
        $event = rvu_event_fetch($pdo, $eventId, (int)$user['id']);
        if (!$event) rvu_event_json(['detail' => 'Event not found.'], 404);
        if (!rvu_event_can_manage($user, $event['author_id'] ?: null)) rvu_event_json(['detail' => 'You can only attach media to events you manage.'], 403);

        $baseDir = __DIR__ . '/../uploads/events';
        $imageDir = $baseDir . '/images';
        $thumbDir = $baseDir . '/thumbs';
        $videoDir = $baseDir . '/videos';
        foreach ([$baseDir, $imageDir, $thumbDir, $videoDir] as $dir) {
            if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
                throw new RuntimeException('Unable to create the event uploads directory.');
            }
        }

        $finfo = new finfo(FILEINFO_MIME_TYPE);

        if ($mediaType === 'video') {
            if (!isset($_FILES['video'])) rvu_event_json(['detail' => 'No video was selected.'], 422);
            $file = $_FILES['video'];
            if ((int)$file['error'] !== UPLOAD_ERR_OK) rvu_event_json(['detail' => 'The event video could not be uploaded.'], 422);
            if ((int)$file['size'] > 10 * 1024 * 1024) rvu_event_json(['detail' => 'Event video must not exceed 10 MB.'], 422);

            $existing = $pdo->prepare("SELECT COUNT(*) FROM campus_event_media WHERE event_id = ? AND media_type = 'video'");
            $existing->execute([$eventId]);
            if ((int)$existing->fetchColumn() >= 1) rvu_event_json(['detail' => 'An event can contain only one video.'], 422);

            $mime = (string)$finfo->file($file['tmp_name']);
            $allowed = [
                'video/mp4' => 'mp4',
                'video/webm' => 'webm',
                'video/quicktime' => 'mov',
            ];
            if (!isset($allowed[$mime])) rvu_event_json(['detail' => 'Only MP4, WebM and MOV event videos are allowed.'], 422);
            $name = 'event_' . $eventId . '_video_' . bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
            $absolute = $videoDir . '/' . $name;
            if (!move_uploaded_file($file['tmp_name'], $absolute)) throw new RuntimeException('Unable to save the event video.');
            $relative = 'uploads/events/videos/' . $name;
            $stmt = $pdo->prepare("INSERT INTO campus_event_media(event_id, media_type, media_path, thumbnail_path, size_bytes, position)
                                   VALUES (?, 'video', ?, NULL, ?, 100) RETURNING id");
            $stmt->execute([$eventId, $relative, (int)$file['size']]);
            $id = (int)$stmt->fetchColumn();
            rvu_event_json(['data' => [
                'id' => $id,
                'event_id' => $eventId,
                'type' => 'video',
                'path' => $relative,
                'thumbnail_path' => '',
                'size_bytes' => (int)$file['size'],
            ]], 201);
        }

        if (!isset($_FILES['images'])) rvu_event_json(['detail' => 'No event pictures 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_event_media WHERE event_id = ? AND media_type = 'image'");
        $countStmt->execute([$eventId]);
        $existingCount = (int)$countStmt->fetchColumn();
        if ($existingCount + count($names) > 6) rvu_event_json(['detail' => 'An event can contain a maximum of 6 pictures.'], 422);

        $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
        $saved = [];
        for ($i = 0; $i < count($names); $i++) {
            if ((int)$errors[$i] !== UPLOAD_ERR_OK) throw new RuntimeException('One of the event pictures could not be uploaded.');
            if ((int)$sizes[$i] > 8 * 1024 * 1024) throw new RuntimeException('Each event picture must be 8 MB or smaller.');
            $mime = (string)$finfo->file($tmpNames[$i]);
            if (!isset($allowed[$mime])) throw new RuntimeException('Only JPEG, PNG and WebP event pictures are allowed.');
            $baseName = 'event_' . $eventId . '_' . bin2hex(random_bytes(8));
            $fileName = $baseName . '.' . $allowed[$mime];
            $absolute = $imageDir . '/' . $fileName;
            if (!move_uploaded_file($tmpNames[$i], $absolute)) throw new RuntimeException('Unable to save an event picture.');
            $relative = 'uploads/events/images/' . $fileName;
            $thumbName = $baseName . '_thumb.' . $allowed[$mime];
            $thumbAbsolute = $thumbDir . '/' . $thumbName;
            $thumbRelative = rvu_event_thumbnail($absolute, $thumbAbsolute, $mime)
                ? 'uploads/events/thumbs/' . $thumbName
                : $relative;
            $position = $existingCount + $i;
            $stmt = $pdo->prepare("INSERT INTO campus_event_media(event_id, media_type, media_path, thumbnail_path, size_bytes, position)
                                   VALUES (?, 'image', ?, ?, ?, ?) RETURNING id");
            $stmt->execute([$eventId, $relative, $thumbRelative, (int)$sizes[$i], $position]);
            $saved[] = [
                'id' => (int)$stmt->fetchColumn(),
                'event_id' => $eventId,
                'type' => 'image',
                'path' => $relative,
                'thumbnail_path' => $thumbRelative,
                'size_bytes' => (int)$sizes[$i],
            ];
        }
        rvu_event_json(['data' => $saved], 201);
    }

    if ($method === 'DELETE') {
        $mediaId = (int)($_GET['id'] ?? 0);
        if ($mediaId <= 0) rvu_event_json(['detail' => 'A valid media id is required.'], 422);
        $stmt = $pdo->prepare('SELECT m.*, e.author_id FROM campus_event_media m INNER JOIN events e ON e.id = m.event_id WHERE m.id = ? LIMIT 1');
        $stmt->execute([$mediaId]);
        $media = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$media) rvu_event_json(['detail' => 'Event media not found.'], 404);
        if (!rvu_event_can_manage($user, $media['author_id'] !== null ? (int)$media['author_id'] : null)) rvu_event_json(['detail' => 'You cannot remove this event media.'], 403);
        $pdo->prepare('DELETE FROM campus_event_media WHERE id = ?')->execute([$mediaId]);
        $root = realpath(__DIR__ . '/..');
        if ($root) {
            foreach (['media_path', 'thumbnail_path'] as $key) {
                $relative = trim((string)($media[$key] ?? ''));
                if ($relative !== '' && str_starts_with(str_replace('\\', '/', $relative), 'uploads/events/')) {
                    $absolute = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative);
                    if (is_file($absolute)) @unlink($absolute);
                }
            }
        }
        rvu_event_json(['message' => 'Event media removed.']);
    }

    rvu_event_json(['detail' => 'Method not allowed.'], 405);
} catch (Throwable $e) {
    rvu_event_json(['detail' => 'Event media server error: ' . $e->getMessage()], 500);
}
