products.php 15 KB

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