<?php

declare(strict_types=1);

/**
 * Responsive Bild-Varianten erzeugen (GD, läuft auch auf Shared Hosting).
 *
 * Resize (proportional auf Zielbreiten):
 *   php bin/img-resize.php <quelle> <ziel-basis> <breite>[,<breite>...] [qualität=78]
 *   → ziel-basis-<breite>.jpg je Breite
 *
 * Crop (exaktes Format, mittig beschnitten, z.B. OG-Image):
 *   php bin/img-resize.php --crop <quelle> <ziel.jpg> <breite>x<höhe> [qualität=78]
 */
if (PHP_SAPI !== 'cli') {
    exit(1);
}

require dirname(__DIR__) . '/app/bootstrap.php';

$args = array_slice($argv, 1);
$crop = false;
if (($args[0] ?? '') === '--crop') {
    $crop = true;
    array_shift($args);
}

if (count($args) < 3) {
    fwrite(STDERR, "Nutzung: siehe Datei-Kommentar\n");
    exit(1);
}

[$src, $dest, $spec] = $args;
$quality = (int) ($args[3] ?? 78);

if ($crop) {
    $image = match (strtolower(pathinfo($src, PATHINFO_EXTENSION))) {
        'jpg', 'jpeg' => imagecreatefromjpeg($src),
        'png'         => imagecreatefrompng($src),
        'webp'        => imagecreatefromwebp($src),
        default       => null,
    };
    if (!$image) {
        fwrite(STDERR, "Kann Quelle nicht lesen: {$src}\n");
        exit(1);
    }

    $srcW = imagesx($image);
    $srcH = imagesy($image);

    [$w, $h] = array_map('intval', explode('x', $spec));
    $srcRatio = $srcW / $srcH;
    $dstRatio = $w / $h;
    if ($srcRatio > $dstRatio) {
        $cropH = $srcH;
        $cropW = (int) round($srcH * $dstRatio);
    } else {
        $cropW = $srcW;
        $cropH = (int) round($srcW / $dstRatio);
    }
    $x = (int) (($srcW - $cropW) / 2);
    $y = (int) (($srcH - $cropH) / 2);
    $out = imagecreatetruecolor($w, $h);
    imagecopyresampled($out, $image, 0, 0, $x, $y, $w, $h, $cropW, $cropH);
    imagejpeg($out, $dest, $quality);
    echo "{$dest} ({$w}x{$h})\n";
    exit(0);
}

try {
    $variants = resize_image_variants($src, $dest, array_map('intval', explode(',', $spec)), $quality);
} catch (RuntimeException $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}

foreach ($variants as $variant) {
    echo "{$variant['file']} ({$variant['width']}x{$variant['height']}, " . round($variant['bytes'] / 1024) . " KB)\n";
}
