<?php
declare(strict_types=1);

function comment_correct_jpeg_orientation($image, string $file)
{
    return triptale_correct_jpeg_orientation($image, $file);
}

function comment_image_paths(int $commentId): array
{
    $q = db()->prepare('SELECT id,file_path FROM ' . table('trip_comment_images') . ' WHERE comment_id=:comment ORDER BY sort_order,id');
    $q->execute([':comment' => $commentId]);
    return $q->fetchAll();
}

function comment_remove_image_file(string $relativePath): void
{
    if (str_starts_with($relativePath, 'uploads/comment-images/')) @unlink(__DIR__ . '/../../' . $relativePath);
}

function comment_remove_images_for_comment(int $commentId): void
{
    foreach (comment_image_paths($commentId) as $image) comment_remove_image_file((string)$image['file_path']);
    $q = db()->prepare('DELETE FROM ' . table('trip_comment_images') . ' WHERE comment_id=:comment');
    $q->execute([':comment' => $commentId]);
}

function comment_images_for_trip(int $tripId): array
{
    $q = db()->prepare('SELECT ci.file_path FROM ' . table('trip_comment_images') . ' ci JOIN ' . table('trip_comments') . ' c ON c.id=ci.comment_id WHERE c.trip_id=:trip');
    $q->execute([':trip' => $tripId]);
    return array_column($q->fetchAll(), 'file_path');
}

function comment_store_uploaded_images(int $commentId, array $files): ?string
{
    $existing = comment_image_paths($commentId); $uploads = [];
    foreach (($files['tmp_name'] ?? []) as $key => $tmp) if (($files['error'][$key] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) $uploads[] = $key;
    if (count($existing) + count($uploads) > 3) return 'Zu einem Kommentar sind höchstens drei Bilder möglich.';
    if (!$uploads) return null;
    foreach ($uploads as $key) {
        $number = $key + 1;
        if (($files['error'][$key] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) return 'Bild ' . $number . ' konnte nicht hochgeladen werden. Bitte wähle es noch einmal aus.';
        if ((int)($files['size'][$key] ?? 0) > 10 * 1024 * 1024) return 'Bild ' . $number . ' ist größer als 10 MB. Bitte wähle ein kleineres Bild aus.';
        $imageInfo = @getimagesize((string)$files['tmp_name'][$key]);
        if (!$imageInfo || !in_array($imageInfo[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP], true)) return 'Bild ' . $number . ' ist kein JPG-, PNG- oder WebP-Bild.';
    }
    $directory = __DIR__ . '/../../uploads/comment-images';
    if (!is_dir($directory) && !mkdir($directory, 0755, true)) return 'Der Bilderordner konnte nicht angelegt werden.';
    foreach ($uploads as $key) {
        if (($files['error'][$key] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) return 'Mindestens ein Bild konnte nicht hochgeladen werden.';
        if ((int)($files['size'][$key] ?? 0) > 10 * 1024 * 1024) return 'Jedes Bild darf höchstens 10 MB groß sein.';
        $tmp = (string)$files['tmp_name'][$key]; $info = @getimagesize($tmp); $types = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_WEBP => 'webp'];
        if (!$info || !isset($types[$info[2]])) return 'Bitte nur JPG-, PNG- oder WebP-Bilder hochladen.';
        $file = 'comment-' . $commentId . '-' . bin2hex(random_bytes(8)) . '.jpg'; $target = $directory . '/' . $file; $stored = false;
        if (function_exists('imagecreatetruecolor') && function_exists('imagejpeg')) {
            $source = match ($info[2]) { IMAGETYPE_JPEG => function_exists('imagecreatefromjpeg') ? @imagecreatefromjpeg($tmp) : false, IMAGETYPE_PNG => function_exists('imagecreatefrompng') ? @imagecreatefrompng($tmp) : false, IMAGETYPE_WEBP => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($tmp) : false, default => false };
            if ($source) { if ($info[2] === IMAGETYPE_JPEG) $source=comment_correct_jpeg_orientation($source,$tmp); $width=imagesx($source);$height=imagesy($source);$scale=min(1,1600/max($width,$height));$newWidth=max(1,(int)round($width*$scale));$newHeight=max(1,(int)round($height*$scale));$canvas=imagecreatetruecolor($newWidth,$newHeight);imagefill($canvas,0,0,imagecolorallocate($canvas,255,255,255));imagecopyresampled($canvas,$source,0,0,0,0,$newWidth,$newHeight,$width,$height);$stored=imagejpeg($canvas,$target,84);imagedestroy($canvas);imagedestroy($source); }
        }
        if (!$stored) { $file='comment-'.$commentId.'-'.bin2hex(random_bytes(8)).'.'.$types[$info[2]]; $target=$directory.'/'.$file; $stored=move_uploaded_file($tmp,$target); }
        if (!$stored) return 'Ein Bild konnte nicht gespeichert werden.';
        $q=db()->prepare('INSERT INTO '.table('trip_comment_images').' (comment_id,file_path,sort_order) VALUES (:comment,:path,:position)');
        $q->execute([':comment'=>$commentId,':path'=>'uploads/comment-images/'.$file,':position'=>count($existing)]); $existing[]=['id'=>0];
    }
    return null;
}
