products.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. <?php
  2. require_once __DIR__ . '/../config.php';
  3. require_once __DIR__ . '/../includes/functions.php';
  4. if (empty($_SESSION['admin_logged_in'])) {
  5. header('Location: login.php');
  6. exit;
  7. }
  8. $pageTitle = 'Produkte verwalten';
  9. $message = '';
  10. $messageType = '';
  11. $categories = getCategories();
  12. function handleImageUpload($fileInputName = 'image_file') {
  13. if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) {
  14. return ['success' => true, 'filename' => null];
  15. }
  16. $file = $_FILES[$fileInputName];
  17. if ($file['error'] !== UPLOAD_ERR_OK) {
  18. return ['success' => false, 'message' => 'Upload fehlgeschlagen.'];
  19. }
  20. $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
  21. $originalName = basename($file['name']);
  22. $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
  23. if (!in_array($extension, $allowedExtensions, true)) {
  24. return ['success' => false, 'message' => 'Ungültiger Dateityp.'];
  25. }
  26. $finfo = new finfo(FILEINFO_MIME_TYPE);
  27. $mimeType = $finfo->file($file['tmp_name']);
  28. $allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
  29. if (!in_array($mimeType, $allowedMimes, true)) {
  30. return ['success' => false, 'message' => 'Die Datei ist kein gültiges Bild.'];
  31. }
  32. $imagesDir = __DIR__ . '/../assets/images';
  33. if (!is_dir($imagesDir)) {
  34. mkdir($imagesDir, 0755, true);
  35. }
  36. $safeBaseName = preg_replace('/[^a-zA-Z0-9_-]/', '-', pathinfo($originalName, PATHINFO_FILENAME));
  37. $safeBaseName = trim((string) $safeBaseName, '-');
  38. if ($safeBaseName === '') {
  39. $safeBaseName = 'bild';
  40. }
  41. $targetFilename = $safeBaseName . '.' . $extension;
  42. $targetPath = $imagesDir . '/' . $targetFilename;
  43. $counter = 1;
  44. while (file_exists($targetPath)) {
  45. $targetFilename = $safeBaseName . '-' . $counter . '.' . $extension;
  46. $targetPath = $imagesDir . '/' . $targetFilename;
  47. $counter++;
  48. }
  49. if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
  50. return ['success' => false, 'message' => 'Bild konnte nicht gespeichert werden.'];
  51. }
  52. return ['success' => true, 'filename' => $targetFilename];
  53. }
  54. function buildProductAvailabilityFields($sizesInput, $submittedValues = [], $existingValues = []) {
  55. $sizes = getProductSizes(['sizes' => (string) $sizesInput]);
  56. if (empty($sizes)) {
  57. $sizes = ['Standard'];
  58. }
  59. $availabilityLabels = [];
  60. foreach ($sizes as $size) {
  61. $fieldName = 'availability_' . str_replace([' ', ','], '_', $size);
  62. if (isset($submittedValues[$fieldName])) {
  63. $availabilityLabels[$size] = trim((string) $submittedValues[$fieldName]);
  64. } else {
  65. $availabilityLabels[$size] = trim((string) ($existingValues[$size] ?? ''));
  66. }
  67. }
  68. return [
  69. 'sizes' => implode(',', $sizes),
  70. 'availability_labels' => $availabilityLabels,
  71. ];
  72. }
  73. function getSubmittedProductCategoryIds($submittedValues) {
  74. $selectedCategoryIds = normalizeProductCategoryIds($submittedValues['categories'] ?? []);
  75. $validCategoryIds = [];
  76. foreach ($selectedCategoryIds as $categoryId) {
  77. if (getCategoryById($categoryId) !== null) {
  78. $validCategoryIds[] = $categoryId;
  79. }
  80. }
  81. return $validCategoryIds;
  82. }
  83. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  84. $products = getProducts();
  85. if (empty($categories)) {
  86. $message = 'Bitte zuerst mindestens eine Kategorie anlegen.';
  87. $messageType = 'error';
  88. } elseif (isset($_POST['add_product']) || isset($_POST['update_product'])) {
  89. $uploadResult = handleImageUpload();
  90. if (!$uploadResult['success']) {
  91. $message = $uploadResult['message'];
  92. $messageType = 'error';
  93. } else {
  94. $categoryIds = getSubmittedProductCategoryIds($_POST);
  95. $existingLabels = [];
  96. $productId = isset($_POST['product_id']) ? (int) $_POST['product_id'] : 0;
  97. foreach ($products as $product) {
  98. if ((int) $product['id'] === $productId) {
  99. $existingLabels = $product['availability_labels'] ?? [];
  100. break;
  101. }
  102. }
  103. $sizeData = buildProductAvailabilityFields($_POST['sizes'] ?? '', $_POST, $existingLabels);
  104. if (empty($categoryIds)) {
  105. $message = 'Bitte mindestens eine gültige Kategorie auswählen.';
  106. $messageType = 'error';
  107. } else {
  108. $record = [
  109. 'name' => sanitize($_POST['name'] ?? ''),
  110. 'description' => trim((string) ($_POST['description'] ?? '')),
  111. 'categories' => $categoryIds,
  112. 'image' => $uploadResult['filename'] !== null ? $uploadResult['filename'] : trim((string) ($_POST['image'] ?? '')),
  113. 'sizes' => $sizeData['sizes'],
  114. 'availability_labels' => $sizeData['availability_labels'],
  115. ];
  116. if ($record['name'] === '') {
  117. $message = 'Bitte einen Produktnamen eingeben.';
  118. $messageType = 'error';
  119. } elseif (isset($_POST['add_product'])) {
  120. $newId = empty($products) ? 1 : (max(array_map(function ($product) {
  121. return (int) $product['id'];
  122. }, $products)) + 1);
  123. $record['id'] = $newId;
  124. $products[] = $record;
  125. saveProducts($products);
  126. $message = 'Produkt wurde angelegt.';
  127. $messageType = 'success';
  128. } else {
  129. $updated = false;
  130. foreach ($products as &$product) {
  131. if ((int) $product['id'] === $productId) {
  132. $record['id'] = $productId;
  133. $product = $record;
  134. $updated = true;
  135. break;
  136. }
  137. }
  138. unset($product);
  139. if ($updated) {
  140. saveProducts($products);
  141. $message = 'Produkt wurde aktualisiert.';
  142. $messageType = 'success';
  143. } else {
  144. $message = 'Produkt nicht gefunden.';
  145. $messageType = 'error';
  146. }
  147. }
  148. }
  149. }
  150. }
  151. if (isset($_POST['delete_product'])) {
  152. $productId = (int) ($_POST['product_id'] ?? 0);
  153. $products = array_values(array_filter($products, function ($product) use ($productId) {
  154. return (int) $product['id'] !== $productId;
  155. }));
  156. saveProducts($products);
  157. $message = 'Produkt wurde gelöscht.';
  158. $messageType = 'success';
  159. }
  160. }
  161. $products = getProducts();
  162. $editingProduct = isset($_GET['edit']) ? getProductById((int) $_GET['edit']) : null;
  163. $bodyClass = 'admin-page';
  164. include __DIR__ . '/../includes/header.php';
  165. ?>
  166. <div class="admin-header">
  167. <h2>Produkte verwalten</h2>
  168. <div>
  169. <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
  170. </div>
  171. </div>
  172. <?php if ($message !== ''): ?>
  173. <div class="alert alert-<?php echo escape($messageType); ?>">
  174. <?php echo escape($message); ?>
  175. </div>
  176. <?php endif; ?>
  177. <?php
  178. $currentProduct = $editingProduct ?: [
  179. 'id' => '',
  180. 'name' => '',
  181. 'description' => '',
  182. 'categories' => [],
  183. 'sizes' => 'Standard',
  184. 'availability_labels' => ['Standard' => ''],
  185. 'image' => '',
  186. ];
  187. $currentSizes = getProductSizes($currentProduct);
  188. if (empty($currentSizes)) {
  189. $currentSizes = ['Standard'];
  190. }
  191. ?>
  192. <div class="panel panel-lg">
  193. <h3><?php echo $editingProduct ? 'Produkt bearbeiten' : 'Neues Produkt anlegen'; ?></h3>
  194. <form method="POST" enctype="multipart/form-data">
  195. <?php if ($editingProduct): ?>
  196. <input type="hidden" name="product_id" value="<?php echo (int) $editingProduct['id']; ?>">
  197. <?php endif; ?>
  198. <div class="form-group">
  199. <label for="name">Name *</label>
  200. <input type="text" id="name" name="name" required value="<?php echo escape($currentProduct['name']); ?>">
  201. </div>
  202. <div class="form-group">
  203. <label for="description">Beschreibung</label>
  204. <textarea id="description" name="description" rows="4"><?php echo escape($currentProduct['description']); ?></textarea>
  205. </div>
  206. <div class="form-group">
  207. <label for="categories">Kategorien *</label>
  208. <select id="categories" name="categories[]" multiple size="<?php echo max(3, min(8, count($categories))); ?>" required>
  209. <?php foreach ($categories as $category): ?>
  210. <option value="<?php echo escape($category['id']); ?>" <?php echo in_array($category['id'], getProductCategoryIds($currentProduct), true) ? 'selected' : ''; ?>>
  211. <?php echo escape($category['label']); ?>
  212. </option>
  213. <?php endforeach; ?>
  214. </select>
  215. </div>
  216. <div class="form-group">
  217. <label for="sizes">Größen (kommagetrennt) *</label>
  218. <input type="text" id="sizes" name="sizes" required value="<?php echo escape($currentProduct['sizes']); ?>" placeholder="Standard" oninput="updateAvailabilityFields()">
  219. <small>Für Artikel ohne Varianten z. B. <code>Standard</code> oder <code>Einheitsgröße</code>.</small>
  220. </div>
  221. <div id="availability-group">
  222. <?php foreach ($currentSizes as $size): ?>
  223. <div class="form-group">
  224. <label>Lieferhinweis für Größe "<?php echo escape($size); ?>"</label>
  225. <textarea name="availability_<?php echo escape(str_replace([' ', ','], '_', $size)); ?>" rows="2" placeholder="Optionaler Hinweis"><?php echo escape($currentProduct['availability_labels'][$size] ?? ''); ?></textarea>
  226. </div>
  227. <?php endforeach; ?>
  228. </div>
  229. <div class="form-group">
  230. <label for="image">Bilddateiname</label>
  231. <input type="text" id="image" name="image" value="<?php echo escape($currentProduct['image']); ?>">
  232. </div>
  233. <div class="form-group">
  234. <label for="image_file">Oder Bild hochladen</label>
  235. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  236. </div>
  237. <button type="submit" name="<?php echo $editingProduct ? 'update_product' : 'add_product'; ?>" class="btn">
  238. <?php echo $editingProduct ? 'Produkt aktualisieren' : 'Produkt anlegen'; ?>
  239. </button>
  240. <?php if ($editingProduct): ?>
  241. <a href="products.php" class="btn btn-secondary">Abbrechen</a>
  242. <?php endif; ?>
  243. </form>
  244. </div>
  245. <script>
  246. function updateAvailabilityFields() {
  247. const sizesInput = document.getElementById('sizes');
  248. const group = document.getElementById('availability-group');
  249. const currentValues = {};
  250. group.querySelectorAll('textarea').forEach((textarea) => {
  251. currentValues[textarea.name] = textarea.value;
  252. });
  253. const sizes = sizesInput.value
  254. .split(',')
  255. .map((size) => size.trim())
  256. .filter((size, index, all) => size && all.indexOf(size) === index);
  257. const finalSizes = sizes.length > 0 ? sizes : ['Standard'];
  258. let html = '';
  259. finalSizes.forEach((size) => {
  260. const safeName = size.replace(/[ ,]/g, '_');
  261. const fieldName = 'availability_' + safeName;
  262. const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '';
  263. html += '<div class="form-group">';
  264. html += '<label>Lieferhinweis für Größe "' + size.replace(/"/g, '&quot;') + '"</label>';
  265. html += '<textarea name="' + fieldName + '" rows="2" placeholder="Optionaler Hinweis">' + currentValue.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
  266. html += '</div>';
  267. });
  268. group.innerHTML = html;
  269. }
  270. </script>
  271. <h3>Alle Produkte</h3>
  272. <?php if (empty($products)): ?>
  273. <p>Keine Produkte vorhanden.</p>
  274. <?php else: ?>
  275. <div class="table-responsive">
  276. <table class="responsive-table">
  277. <thead>
  278. <tr>
  279. <th>ID</th>
  280. <th>Name</th>
  281. <th>Kategorien</th>
  282. <th>Größen</th>
  283. <th>Lieferhinweise</th>
  284. <th>Aktionen</th>
  285. </tr>
  286. </thead>
  287. <tbody>
  288. <?php foreach ($products as $product): ?>
  289. <tr>
  290. <td data-label="ID"><?php echo (int) $product['id']; ?></td>
  291. <td data-label="Name"><?php echo escape($product['name']); ?></td>
  292. <td data-label="Kategorien"><?php echo escape(implode(', ', getCategoryLabels(getProductCategoryIds($product)))); ?></td>
  293. <td data-label="Größen"><?php echo escape(implode(', ', getProductSizes($product))); ?></td>
  294. <td data-label="Lieferhinweise">
  295. <?php
  296. $labels = [];
  297. foreach (($product['availability_labels'] ?? []) as $size => $label) {
  298. if (trim((string) $label) !== '') {
  299. $labels[] = $size . ': ' . $label;
  300. }
  301. }
  302. echo empty($labels) ? 'Keine' : escape(implode(' | ', $labels));
  303. ?>
  304. </td>
  305. <td data-label="Aktionen">
  306. <a href="?edit=<?php echo (int) $product['id']; ?>" class="btn btn-small">Bearbeiten</a>
  307. <form method="POST" class="inline-form" onsubmit="return confirm('Produkt wirklich löschen?');">
  308. <input type="hidden" name="product_id" value="<?php echo (int) $product['id']; ?>">
  309. <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
  310. </form>
  311. </td>
  312. </tr>
  313. <?php endforeach; ?>
  314. </tbody>
  315. </table>
  316. </div>
  317. <?php endif; ?>
  318. <?php include __DIR__ . '/../includes/footer.php'; ?>