<?php
declare(strict_types=1);

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

// aktuell eingeloggter User
$user       = currentUser();
$creatorId  = (int)$user['id'];

$storeFile = $_POST['storeFile'] ?? ($_POST['store'] ?? null);
$name      = trim($_POST['itemName'] ?? '');
$priceRaw  = $_POST['price'] ?? '0';
$amountRaw = $_POST['amount'] ?? '1';
$unit      = trim($_POST['unit'] ?? '');

if (!$storeFile || $name === '' || $unit === '') {
    header('Location: ../start.php');
    exit;
}

// Store holen
$stmt = $pdo->prepare('SELECT id FROM stores WHERE file = :file');
$stmt->execute([':file' => $storeFile]);
$store = $stmt->fetch();
if (!$store) {
    header('Location: ../start.php');
    exit;
}
$storeId = (int)$store['id'];

// Zahlen normalisieren (deutsche Eingabe)
$priceNorm  = str_replace(['.', ','], ['', '.'], preg_replace('~[^\d,.-]~', '', $priceRaw));
$amountNorm = str_replace(['.', ','], ['', '.'], preg_replace('~[^\d,.-]~', '', $amountRaw));
$price  = (float)($priceNorm !== '' ? $priceNorm : 0);
$amount = (float)($amountNorm !== '' ? $amountNorm : 1);

// sort_order bestimmen
$stmt = $pdo->prepare('SELECT COALESCE(MAX(sort_order) + 1, 0) FROM items WHERE store_id = :sid');
$stmt->execute([':sid' => $storeId]);
$nextSort = (int)$stmt->fetchColumn();

// 1. Artikel ohne Bild anlegen  + created_by speichern
$stmt = $pdo->prepare('
    INSERT INTO items (store_id, name, price, amount, unit, sort_order, created_by)
    VALUES (:sid, :name, :price, :amount, :unit, :sort, :created_by)
');
$stmt->execute([
    ':sid'        => $storeId,
    ':name'       => $name,
    ':price'      => $price,
    ':amount'     => $amount,
    ':unit'       => $unit,
    ':sort'       => $nextSort,
    ':created_by' => $creatorId,
]);

$itemId = (int)$pdo->lastInsertId();

// 2. Bild-Upload (optional) mit EXIF-Rotation, Resize und max. ca. 500 KB
if (!empty($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_OK) {

    $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) {
        $mime = $info['mime'] ?? '';

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

        if ($src !== false) {

            // 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);
            }

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

header('Location: ../articles.php?store=' . urlencode($storeFile));
exit;
