<?php
declare(strict_types=1);

require __DIR__ . '/../auth.php';
requireLogin();

header('Content-Type: application/json; charset=utf-8');

$storeFile = $_POST['storeFile'] ?? '';
$itemIdRaw = $_POST['item_id'] ?? '';

if ($storeFile === '' || !preg_match('~^[a-z0-9._-]+\.json$~i', $storeFile)) {
    echo json_encode(['ok' => false, 'error' => 'Ungültiger Store.']);
    exit;
}

$itemId = (int)$itemIdRaw;
if ($itemId <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Ungültige Artikel-ID.']);
    exit;
}

if (empty($_FILES['image']['tmp_name']) || ($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
    echo json_encode(['ok' => false, 'error' => 'Kein Bild empfangen.']);
    exit;
}

// Store finden
$stmt = $pdo->prepare('SELECT id FROM stores WHERE file = :file LIMIT 1');
$stmt->execute([':file' => $storeFile]);
$store = $stmt->fetch();

if (!$store) {
    echo json_encode(['ok' => false, 'error' => 'Store nicht gefunden.']);
    exit;
}
$storeId = (int)$store['id'];

// Item prüfen (muss zum Store gehören)
$stmt = $pdo->prepare('SELECT image_path FROM items WHERE id = :id AND store_id = :sid LIMIT 1');
$stmt->execute([':id' => $itemId, ':sid' => $storeId]);
$item = $stmt->fetch();

if (!$item) {
    echo json_encode(['ok' => false, 'error' => 'Artikel nicht gefunden.']);
    exit;
}

$oldImage = (string)($item['image_path'] ?? '');

// Upload dir
$uploadDir = __DIR__ . '/../uploads/items/';
if (!is_dir($uploadDir)) {
    @mkdir($uploadDir, 0775, true);
}

$tmp = $_FILES['image']['tmp_name'];

// Bildinfos holen
$info = @getimagesize($tmp);
if ($info === false) {
    echo json_encode(['ok' => false, 'error' => 'Datei ist kein Bild.']);
    exit;
}

$mime = $info['mime'] ?? '';

// Bild laden
switch ($mime) {
    case 'image/png':
        $src = @imagecreatefrompng($tmp);
        break;
    case 'image/webp':
        $src = @imagecreatefromwebp($tmp);
        break;
    default:
        $src = @imagecreatefromjpeg($tmp);
        break;
}

if ($src === false) {
    echo json_encode(['ok' => false, 'error' => 'Bild konnte nicht gelesen werden.']);
    exit;
}

// EXIF-Orientation nur bei JPEG korrigieren
if ($mime === 'image/jpeg' && function_exists('exif_read_data')) {
    $exif = @exif_read_data($tmp);
    if (!empty($exif['Orientation'])) {
        $orientation = (int)$exif['Orientation'];
        switch ($orientation) {
            case 3: // 180°
                $rotated = imagerotate($src, 180, 0);
                if ($rotated) {
                    imagedestroy($src);
                    $src = $rotated;
                }
                break;
            case 6: // 90° CW
                $rotated = imagerotate($src, -90, 0);
                if ($rotated) {
                    imagedestroy($src);
                    $src = $rotated;
                }
                break;
            case 8: // 90° CCW
                $rotated = imagerotate($src, 90, 0);
                if ($rotated) {
                    imagedestroy($src);
                    $src = $rotated;
                }
                break;
        }
    }
}

$w = imagesx($src);
$h = imagesy($src);

// Max. Breite 1200px, Höhe proportional
$maxW = 1200;
if ($w > $maxW) {
    $ratio = $maxW / $w;
    $newW = $maxW;
    $newH = (int)round($h * $ratio);

    $dst = imagecreatetruecolor($newW, $newH);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
} else {
    $dst = $src;
}

// Ziel-Dateiname immer JPG
$filename = 'item_' . $itemId . '_' . time() . '.jpg';
$target   = $uploadDir . $filename;

// Qualität so anpassen, dass ~max 500 KB rauskommt
$quality  = 85;
$maxBytes = 500 * 1024; // 500 KB

do {
    ob_start();
    imagejpeg($dst, null, $quality);
    $data = ob_get_clean();
    $size = strlen($data);

    if ($size > $maxBytes && $quality > 40) {
        $quality -= 10;
    } else {
        break;
    }
} while (true);

// final auf Platte schreiben
file_put_contents($target, $data);

imagedestroy($src);
if ($dst !== $src) {
    imagedestroy($dst);
}

// Altes Bild löschen (falls vorhanden)
if ($oldImage !== '') {
    $oldPath = $uploadDir . $oldImage;
    if (is_file($oldPath)) {
        @unlink($oldPath);
    }
}

// Pfad in DB speichern
$stmt = $pdo->prepare('UPDATE items SET image_path = :img WHERE id = :id AND store_id = :sid');
$stmt->execute([
    ':img' => $filename,
    ':id'  => $itemId,
    ':sid' => $storeId,
]);

echo json_encode(['ok' => true, 'filename' => $filename]);
exit;
