<?php
// File where comics are stored
$filename = 'comic.json';

// Load existing data or initialize array
if (file_exists($filename)) {
    $json = file_get_contents($filename);
    $data = json_decode($json, true);
    if (!is_array($data)) $data = [];
} else {
    $data = [];
}

// Collect title and url
$title = isset($_GET['title']) ? trim($_GET['title']) : '';
$url   = isset($_GET['url'])   ? trim($_GET['url'])   : '';

if (!$title || !$url) {
    die("❌ Missing title or URL");
}

// Collect all img* keys (img1, img2, etc.)
$images = [];
foreach ($_GET as $key => $value) {
    if (preg_match('/^img\d+$/', $key)) {
        $images[] = $value;
    }
}

if (empty($images)) {
    die("❌ No images selected.");
}

// Build new entry
$new_entry = [
    'title'  => $title,
    'url'    => $url,
    'images' => $images
];

// Append to existing array
$data[] = $new_entry;

// Save back to file
file_put_contents($filename, json_encode($data, JSON_PRETTY_PRINT));

// Output success
echo "<h2>✅ Comic saved!</h2>";
echo "<p><strong>Title:</strong> " . htmlspecialchars($title) . "</p>";
echo "<p><strong>URL:</strong> " . htmlspecialchars($url) . "</p>";
echo "<p><strong>Images:</strong></p><ul>";
foreach ($images as $img) {
    echo "<li><a href='" . htmlspecialchars($img) . "'>" . htmlspecialchars($img) . "</a></li>";
}
echo "</ul>";
?>
