| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364 |
- <?php
- require_once __DIR__ . '/../config.php';
- require_once __DIR__ . '/../includes/functions.php';
- if (empty($_SESSION['admin_logged_in'])) {
- header('Location: login.php');
- exit;
- }
- $pageTitle = 'Produkte verwalten';
- $message = '';
- $messageType = '';
- $categories = getCategories();
- function handleImageUpload($fileInputName = 'image_file') {
- if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) {
- return ['success' => true, 'filename' => null];
- }
- $file = $_FILES[$fileInputName];
- if ($file['error'] !== UPLOAD_ERR_OK) {
- return ['success' => false, 'message' => 'Upload fehlgeschlagen.'];
- }
- $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
- $originalName = basename($file['name']);
- $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
- if (!in_array($extension, $allowedExtensions, true)) {
- return ['success' => false, 'message' => 'Ungültiger Dateityp.'];
- }
- $finfo = new finfo(FILEINFO_MIME_TYPE);
- $mimeType = $finfo->file($file['tmp_name']);
- $allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
- if (!in_array($mimeType, $allowedMimes, true)) {
- return ['success' => false, 'message' => 'Die Datei ist kein gültiges Bild.'];
- }
- $uploadsDir = rtrim(UPLOADS_DIR, '/\\');
- if (!is_dir($uploadsDir)) {
- mkdir($uploadsDir, 0755, true);
- }
- $safeBaseName = preg_replace('/[^a-zA-Z0-9_-]/', '-', pathinfo($originalName, PATHINFO_FILENAME));
- $safeBaseName = trim((string) $safeBaseName, '-');
- if ($safeBaseName === '') {
- $safeBaseName = 'bild';
- }
- $targetFilename = $safeBaseName . '.' . $extension;
- $targetPath = $uploadsDir . '/' . $targetFilename;
- $counter = 1;
- while (file_exists($targetPath)) {
- $targetFilename = $safeBaseName . '-' . $counter . '.' . $extension;
- $targetPath = $uploadsDir . '/' . $targetFilename;
- $counter++;
- }
- if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
- return ['success' => false, 'message' => 'Bild konnte nicht gespeichert werden.'];
- }
- return ['success' => true, 'filename' => $targetFilename];
- }
- function buildProductAvailabilityFields($sizesInput, $submittedValues = [], $existingValues = []) {
- $sizes = getProductSizes(['sizes' => (string) $sizesInput]);
- if (empty($sizes)) {
- $sizes = ['Standard'];
- }
- $availabilityLabels = [];
- foreach ($sizes as $size) {
- $fieldName = 'availability_' . str_replace([' ', ','], '_', $size);
- if (isset($submittedValues[$fieldName])) {
- $availabilityLabels[$size] = trim((string) $submittedValues[$fieldName]);
- } else {
- $availabilityLabels[$size] = trim((string) ($existingValues[$size] ?? ''));
- }
- }
- return [
- 'sizes' => implode(',', $sizes),
- 'availability_labels' => $availabilityLabels,
- ];
- }
- function getSubmittedProductCategoryIds($submittedValues) {
- $selectedCategoryIds = normalizeProductCategoryIds($submittedValues['categories'] ?? []);
- $validCategoryIds = [];
- foreach ($selectedCategoryIds as $categoryId) {
- if (getCategoryById($categoryId) !== null) {
- $validCategoryIds[] = $categoryId;
- }
- }
- return $validCategoryIds;
- }
- if ($_SERVER['REQUEST_METHOD'] === 'POST') {
- $products = getProducts();
- if (empty($categories)) {
- $message = 'Bitte zuerst mindestens eine Kategorie anlegen.';
- $messageType = 'error';
- } elseif (isset($_POST['add_product']) || isset($_POST['update_product'])) {
- $uploadResult = handleImageUpload();
- if (!$uploadResult['success']) {
- $message = $uploadResult['message'];
- $messageType = 'error';
- } else {
- $categoryIds = getSubmittedProductCategoryIds($_POST);
- $existingLabels = [];
- $productId = isset($_POST['product_id']) ? (int) $_POST['product_id'] : 0;
- foreach ($products as $product) {
- if ((int) $product['id'] === $productId) {
- $existingLabels = $product['availability_labels'] ?? [];
- break;
- }
- }
- $sizeData = buildProductAvailabilityFields($_POST['sizes'] ?? '', $_POST, $existingLabels);
- if (empty($categoryIds)) {
- $message = 'Bitte mindestens eine gültige Kategorie auswählen.';
- $messageType = 'error';
- } else {
- $record = [
- 'name' => sanitize($_POST['name'] ?? ''),
- 'description' => trim((string) ($_POST['description'] ?? '')),
- 'categories' => $categoryIds,
- 'image' => $uploadResult['filename'] !== null ? $uploadResult['filename'] : trim((string) ($_POST['image'] ?? '')),
- 'sizes' => $sizeData['sizes'],
- 'availability_labels' => $sizeData['availability_labels'],
- ];
- if ($record['name'] === '') {
- $message = 'Bitte einen Produktnamen eingeben.';
- $messageType = 'error';
- } elseif (isset($_POST['add_product'])) {
- $newId = empty($products) ? 1 : (max(array_map(function ($product) {
- return (int) $product['id'];
- }, $products)) + 1);
- $record['id'] = $newId;
- $products[] = $record;
- saveProducts($products);
- $message = 'Produkt wurde angelegt.';
- $messageType = 'success';
- } else {
- $updated = false;
- foreach ($products as &$product) {
- if ((int) $product['id'] === $productId) {
- $record['id'] = $productId;
- $product = $record;
- $updated = true;
- break;
- }
- }
- unset($product);
- if ($updated) {
- saveProducts($products);
- $message = 'Produkt wurde aktualisiert.';
- $messageType = 'success';
- } else {
- $message = 'Produkt nicht gefunden.';
- $messageType = 'error';
- }
- }
- }
- }
- }
- if (isset($_POST['delete_product'])) {
- $productId = (int) ($_POST['product_id'] ?? 0);
- $products = array_values(array_filter($products, function ($product) use ($productId) {
- return (int) $product['id'] !== $productId;
- }));
- saveProducts($products);
- $message = 'Produkt wurde gelöscht.';
- $messageType = 'success';
- }
- }
- $products = getProducts();
- $editingProduct = isset($_GET['edit']) ? getProductById((int) $_GET['edit']) : null;
- $bodyClass = 'admin-page';
- include __DIR__ . '/../includes/header.php';
- ?>
- <div class="admin-header">
- <h2>Produkte verwalten</h2>
- <div>
- <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
- </div>
- </div>
- <?php if ($message !== ''): ?>
- <div class="alert alert-<?php echo escape($messageType); ?>">
- <?php echo escape($message); ?>
- </div>
- <?php endif; ?>
- <?php
- $currentProduct = $editingProduct ?: [
- 'id' => '',
- 'name' => '',
- 'description' => '',
- 'categories' => [],
- 'sizes' => 'Standard',
- 'availability_labels' => ['Standard' => ''],
- 'image' => '',
- ];
- $currentSizes = getProductSizes($currentProduct);
- if (empty($currentSizes)) {
- $currentSizes = ['Standard'];
- }
- ?>
- <div class="panel panel-lg">
- <h3><?php echo $editingProduct ? 'Produkt bearbeiten' : 'Neues Produkt anlegen'; ?></h3>
- <form method="POST" enctype="multipart/form-data">
- <?php if ($editingProduct): ?>
- <input type="hidden" name="product_id" value="<?php echo (int) $editingProduct['id']; ?>">
- <?php endif; ?>
- <div class="form-group">
- <label for="name">Name *</label>
- <input type="text" id="name" name="name" required value="<?php echo escape($currentProduct['name']); ?>">
- </div>
- <div class="form-group">
- <label for="description">Beschreibung</label>
- <textarea id="description" name="description" rows="4"><?php echo escape($currentProduct['description']); ?></textarea>
- </div>
- <div class="form-group">
- <label for="categories">Kategorien *</label>
- <select id="categories" name="categories[]" multiple size="<?php echo max(3, min(8, count($categories))); ?>" required>
- <?php foreach ($categories as $category): ?>
- <option value="<?php echo escape($category['id']); ?>" <?php echo in_array($category['id'], getProductCategoryIds($currentProduct), true) ? 'selected' : ''; ?>>
- <?php echo escape($category['label']); ?>
- </option>
- <?php endforeach; ?>
- </select>
- </div>
- <div class="form-group">
- <label for="sizes">Größen (kommagetrennt) *</label>
- <input type="text" id="sizes" name="sizes" required value="<?php echo escape($currentProduct['sizes']); ?>" placeholder="Standard" oninput="updateAvailabilityFields()">
- <small>Für Artikel ohne Varianten z. B. <code>Standard</code> oder <code>Einheitsgröße</code>.</small>
- </div>
- <div id="availability-group">
- <?php foreach ($currentSizes as $size): ?>
- <div class="form-group">
- <label>Lieferhinweis für Größe "<?php echo escape($size); ?>"</label>
- <textarea name="availability_<?php echo escape(str_replace([' ', ','], '_', $size)); ?>" rows="2" placeholder="Optionaler Hinweis"><?php echo escape($currentProduct['availability_labels'][$size] ?? ''); ?></textarea>
- </div>
- <?php endforeach; ?>
- </div>
- <div class="form-group">
- <label for="image">Bilddateiname</label>
- <input type="text" id="image" name="image" value="<?php echo escape($currentProduct['image']); ?>">
- </div>
- <div class="form-group">
- <label for="image_file">Oder Bild hochladen</label>
- <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
- </div>
- <button type="submit" name="<?php echo $editingProduct ? 'update_product' : 'add_product'; ?>" class="btn">
- <?php echo $editingProduct ? 'Produkt aktualisieren' : 'Produkt anlegen'; ?>
- </button>
- <?php if ($editingProduct): ?>
- <a href="products.php" class="btn btn-secondary">Abbrechen</a>
- <?php endif; ?>
- </form>
- </div>
- <script>
- function updateAvailabilityFields() {
- const sizesInput = document.getElementById('sizes');
- const group = document.getElementById('availability-group');
- const currentValues = {};
- group.querySelectorAll('textarea').forEach((textarea) => {
- currentValues[textarea.name] = textarea.value;
- });
- const sizes = sizesInput.value
- .split(',')
- .map((size) => size.trim())
- .filter((size, index, all) => size && all.indexOf(size) === index);
- const finalSizes = sizes.length > 0 ? sizes : ['Standard'];
- let html = '';
- finalSizes.forEach((size) => {
- const safeName = size.replace(/[ ,]/g, '_');
- const fieldName = 'availability_' + safeName;
- const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '';
- html += '<div class="form-group">';
- html += '<label>Lieferhinweis für Größe "' + size.replace(/"/g, '"') + '"</label>';
- html += '<textarea name="' + fieldName + '" rows="2" placeholder="Optionaler Hinweis">' + currentValue.replace(/</g, '<').replace(/>/g, '>') + '</textarea>';
- html += '</div>';
- });
- group.innerHTML = html;
- }
- </script>
- <h3>Alle Produkte</h3>
- <?php if (empty($products)): ?>
- <p>Keine Produkte vorhanden.</p>
- <?php else: ?>
- <div class="table-responsive">
- <table class="responsive-table">
- <thead>
- <tr>
- <th>ID</th>
- <th>Name</th>
- <th>Kategorien</th>
- <th>Größen</th>
- <th>Lieferhinweise</th>
- <th>Aktionen</th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($products as $product): ?>
- <tr>
- <td data-label="ID"><?php echo (int) $product['id']; ?></td>
- <td data-label="Name"><?php echo escape($product['name']); ?></td>
- <td data-label="Kategorien"><?php echo escape(implode(', ', getCategoryLabels(getProductCategoryIds($product)))); ?></td>
- <td data-label="Größen"><?php echo escape(implode(', ', getProductSizes($product))); ?></td>
- <td data-label="Lieferhinweise">
- <?php
- $labels = [];
- foreach (($product['availability_labels'] ?? []) as $size => $label) {
- if (trim((string) $label) !== '') {
- $labels[] = $size . ': ' . $label;
- }
- }
- echo empty($labels) ? 'Keine' : escape(implode(' | ', $labels));
- ?>
- </td>
- <td data-label="Aktionen">
- <a href="?edit=<?php echo (int) $product['id']; ?>" class="btn btn-small">Bearbeiten</a>
- <form method="POST" class="inline-form" onsubmit="return confirm('Produkt wirklich löschen?');">
- <input type="hidden" name="product_id" value="<?php echo (int) $product['id']; ?>">
- <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
- </form>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- </div>
- <?php endif; ?>
- <?php include __DIR__ . '/../includes/footer.php'; ?>
|