<?php
declare(strict_types=1);
require_once __DIR__ . '/app/Helpers/bootstrap.php';
require_once __DIR__ . '/app/Helpers/trip-changes.php';
ob_start(static function (string $html): string {
    if (language() === 'de') { return $html; }
    return strtr($html, ['<html lang="de">' => '<html lang="en">', 'Bild bearbeiten · TripTale' => t('image.title') . ' · TripTale', '>← Zurück<' => '>' . t('image.back') . '<', '>Bild: <' => '>' . t('image.prefix') . ' <', '>Bild auswählen<' => '>' . t('image.choose') . '<', '>JPG, PNG oder WebP · maximal 10 MB<' => '>' . t('image.hint') . '<', '>Datei auswählen<' => '>' . t('image.select_file') . '<', '>Noch kein Bild ausgewählt<' => '>' . t('image.none') . '<', '>Bild speichern<' => '>' . t('image.save') . '<', '>Bild löschen<' => '>' . t('image.delete') . '<', "'Noch kein Bild ausgewählt'" => json_encode(t('image.none'), JSON_UNESCAPED_UNICODE), "confirm('Dieses Bild wirklich löschen?')" => 'confirm(' . json_encode(t('image.confirm_delete'), JSON_UNESCAPED_UNICODE) . ')']);
});

ob_start(static function (string $html): string {
    return language() !== 'de' ? str_replace('<h1>Bild: ', '<h1>', $html) : $html;
});
$user = require_login();
$type = (string)($_GET['type'] ?? '');
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
$types = [
    'trip' => ['table' => 'trips', 'field' => 'title', 'label' => 'Reise', 'back' => '/trip-edit.php?id='],
    'attraction' => ['table' => 'attractions', 'field' => 'name', 'label' => 'Sehenswürdigkeit', 'back' => '/attraction-edit.php?id='],
    'accommodation' => ['table' => 'accommodations', 'field' => 'name', 'label' => 'Unterkunft', 'back' => '/catalog-edit.php?type=accommodation&id='],
    'restaurant' => ['table' => 'restaurants', 'field' => 'name', 'label' => 'Essen & Trinken', 'back' => '/catalog-edit.php?type=restaurant&id='],
    'custom' => ['table' => 'trip_day_items', 'field' => 'title', 'label' => 'Programmpunkt', 'back' => '/item-edit.php?id='],
    'custom_point' => ['table' => 'custom_points', 'field' => 'name', 'label' => 'Eigener Programmpunkt', 'back' => '/custom-point-edit.php?id='],
];
if (!$id || !isset($types[$type])) { http_response_code(404); exit(t('image.error_not_found')); }
$meta = $types[$type];

if ($type === 'custom') {
    $query = db()->prepare('SELECT i.id, i.title AS name, i.image_path, d.trip_id, t.created_by FROM ' . table('trip_day_items') . ' i JOIN ' . table('trip_days') . ' d ON d.id = i.trip_day_id JOIN ' . table('trips') . ' t ON t.id = d.trip_id WHERE i.id = :id AND i.item_type = \'custom\'');
} else {
    $query = db()->prepare('SELECT id, ' . $meta['field'] . ' AS name, image_path, created_by FROM ' . table($meta['table']) . ' WHERE id = :id');
}
$query->execute([':id' => $id]);
$entry = $query->fetch();
if (!$entry) { http_response_code(404); exit(t('image.error_not_found')); }
$canEdit = $user['role'] === 'main_admin' || (int)$entry['created_by'] === (int)$user['id'];
if (!$canEdit && in_array($type, ['trip', 'custom'], true)) {
    $tripId = $type === 'trip' ? (int)$id : (int)$entry['trip_id'];
    $adminCheck = db()->prepare('SELECT 1 FROM ' . table('trip_admins') . ' WHERE trip_id = :trip_id AND user_id = :user_id');
    $adminCheck->execute([':trip_id' => $tripId, ':user_id' => $user['id']]);
    $canEdit = (bool)$adminCheck->fetchColumn();
}
if (!$canEdit) { http_response_code(403); exit(t('image.error_access')); }

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_image'])) {
    verify_csrf();
    if (!empty($entry['image_path']) && (str_starts_with($entry['image_path'], 'uploads/') || str_starts_with($entry['image_path'], 'storage/uploads/'))) {
        @unlink(__DIR__ . '/' . $entry['image_path']);
    }
    db()->prepare('UPDATE ' . table($meta['table']) . ' SET image_path = NULL WHERE id = :id')->execute([':id' => $id]);
    if ($type === 'trip') { triptale_log_trip_change((int)$id, (int)$user['id'], 'trip_image_deleted', 'Das Reisebild wurde gelöscht.'); }
    header('Location: ' . $meta['back'] . $id . '&image=deleted'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    if (empty($_FILES['image']['tmp_name'])) {
        $error = t('image.error_choose');
    } elseif ((int)$_FILES['image']['size'] > 10 * 1024 * 1024) {
        $error = t('image.error_size');
    } else {
        $info = @getimagesize($_FILES['image']['tmp_name']);
        $extensions = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_WEBP => 'webp'];
        if (!$info || !isset($extensions[$info[2]])) {
            $error = t('image.error_type');
        } else {
            $directory = __DIR__ . '/uploads';
            if (!is_dir($directory) && !mkdir($directory, 0755, true)) {
                $error = t('image.error_directory');
            } else {
                $tmp = (string)$_FILES['image']['tmp_name'];
                $filename = $type . '-' . $id . '-' . bin2hex(random_bytes(6)) . '.jpg';
                $path = $directory . '/' . $filename;
                $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,
                    };
                    if ($source) {
                        if ($info[2] === IMAGETYPE_JPEG) {
                            $source = triptale_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, $path, 86);
                        imagedestroy($canvas); imagedestroy($source);
                    }
                }
                if (!$stored) {
                    $filename = $type . '-' . $id . '-' . bin2hex(random_bytes(6)) . '.' . $extensions[$info[2]];
                    $path = $directory . '/' . $filename;
                    $stored = move_uploaded_file($tmp, $path);
                }
                if (!$stored) {
                    $error = t('image.error_save');
                } else {
                    $relative = 'uploads/' . $filename;
                    if (!empty($entry['image_path']) && (str_starts_with($entry['image_path'], 'uploads/') || str_starts_with($entry['image_path'], 'storage/uploads/'))) {
                        @unlink(__DIR__ . '/' . $entry['image_path']);
                    }
                    db()->prepare('UPDATE ' . table($meta['table']) . ' SET image_path = :path WHERE id = :id')->execute([':path' => $relative, ':id' => $id]);
                    if ($type === 'trip') { triptale_log_trip_change((int)$id, (int)$user['id'], 'trip_image_updated', 'Das Reisebild wurde geändert.'); }
                    header('Location: ' . $meta['back'] . $id . '&image=changed'); exit;
                }
            }
        }
    }
}
?>
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Bild bearbeiten · TripTale</title>
<style>
body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:24px;color:#17202a}main{max-width:620px;margin:auto;background:#fff;padding:24px;border-radius:14px;box-shadow:0 4px 18px #0001}.button,button{display:inline-block;padding:10px 13px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.back+h1{margin-top:26px}.delete{background:#9d2d2d}.error{background:#ffe6e3;padding:12px;border-radius:7px}.preview{display:block;width:100%;max-height:320px;object-fit:contain!important;border-radius:14px;clip-path:inset(0 round 14px);background:#f4f6f8;margin:14px 0}.file-area{margin-top:20px;padding:16px;background:#edf5f6;border-left:4px solid #75aeb9;border-radius:10px}.file-area h2{font-size:1.05rem;margin:0 0 6px}.file-hint{margin:0 0 12px;color:#59636d;font-size:.92rem}.file-picker{display:inline-block;padding:10px 13px;background:#126e82;color:#fff;border-radius:7px;font-weight:700;cursor:pointer}.file-picker input{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden}.file-name{display:block;margin-top:10px;color:#59636d;font-size:.92rem;overflow-wrap:anywhere}.save{margin-top:16px}.delete-form{margin-top:8px}*{box-sizing:border-box}@media(max-width:600px){body{padding:12px}main{padding:16px}.button:not(.back),button{width:100%;text-align:center}.back{display:inline-block!important;width:auto!important;max-width:100%!important;white-space:normal}.back+h1{margin-top:22px}.file-picker{display:block;text-align:center}.save{width:100%}}
</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main>
<a class="button back" href="<?= htmlspecialchars($meta['back'] . $id, ENT_QUOTES, 'UTF-8') ?>">← Zurück</a>
<h1>Bild: <?= htmlspecialchars($entry['name'], ENT_QUOTES, 'UTF-8') ?></h1>
<?php if ($entry['image_path']): ?><img class="preview" src="/<?= htmlspecialchars($entry['image_path'], ENT_QUOTES, 'UTF-8') ?>" alt=""><?php endif; ?>
<?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
<form method="post" enctype="multipart/form-data"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><section class="file-area"><h2>Bild auswählen</h2><p class="file-hint">JPG, PNG oder WebP · maximal 10 MB</p><label class="file-picker">Datei auswählen<input id="image-file" name="image" type="file" accept="image/jpeg,image/png,image/webp" required></label><span class="file-name" id="file-name">Noch kein Bild ausgewählt</span></section><button class="save" type="submit">Bild speichern</button></form>
<?php if ($entry['image_path']): ?><form class="delete-form" method="post" onsubmit="return confirm('Dieses Bild wirklich löschen?');"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><button name="delete_image" class="delete" type="submit">Bild löschen</button></form><?php endif; ?>
</main><script>const fileInput=document.getElementById('image-file');const fileName=document.getElementById('file-name');fileInput?.addEventListener('change',()=>{fileName.textContent=fileInput.files.length?fileInput.files[0].name:'Noch kein Bild ausgewählt';});</script></body></html>
