<?php
header('Content-Type: application/json');

$mangaId = $_GET['id'] ?? '';
$chapter = (int)($_GET['chapter'] ?? 0);

if (empty($mangaId) || $chapter <= 0) {
    echo json_encode(['error' => 'Parameter id dan chapter wajib diisi']);
    exit;
}

$storagePath = __DIR__ . '/../storage/' . $mangaId;
$possiblePaths = [
    $storagePath . '/Chapter_' . str_pad($chapter, 3, '0', STR_PAD_LEFT),
    $storagePath . '/chapter_' . str_pad($chapter, 3, '0', STR_PAD_LEFT),
    $storagePath . '/Chapter_' . $chapter,
    $storagePath . '/chapter_' . $chapter,
];

$chapterPath = null;
foreach ($possiblePaths as $path) {
    if (is_dir($path)) {
        $chapterPath = $path;
        break;
    }
}

if (!$chapterPath) {
    echo json_encode(['error' => 'Chapter tidak ditemukan']);
    exit;
}

// Support JPG, JPEG, PNG, WebP
$files = glob($chapterPath . '/*.{jpg,jpeg,png,webp}', GLOB_BRACE);
natsort($files);

$images = [];
foreach ($files as $file) {
    $images[] = 'https://' . $_SERVER['HTTP_HOST'] . '/storage/' . $mangaId . '/' . basename($chapterPath) . '/' . basename($file);
}

echo json_encode(['images' => $images]);
?>