products.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. require_once __DIR__ . '/../config.php';
  3. require_once __DIR__ . '/../includes/functions.php';
  4. // Check admin login
  5. if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
  6. header('Location: login.php');
  7. exit;
  8. }
  9. $pageTitle = 'Produkte verwalten';
  10. $message = '';
  11. $messageType = '';
  12. $categories = getCategories();
  13. function handleImageUpload($fileInputName = 'image_file') {
  14. if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) {
  15. return ['success' => true, 'filename' => null];
  16. }
  17. $file = $_FILES[$fileInputName];
  18. if ($file['error'] !== UPLOAD_ERR_OK) {
  19. return ['success' => false, 'message' => 'Upload fehlgeschlagen. Bitte erneut versuchen.'];
  20. }
  21. $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
  22. $originalName = basename($file['name']);
  23. $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
  24. if (!in_array($extension, $allowedExtensions, true)) {
  25. return ['success' => false, 'message' => 'Ungültiger Dateityp. Erlaubt: JPG, PNG, WEBP, GIF.'];
  26. }
  27. $finfo = new finfo(FILEINFO_MIME_TYPE);
  28. $mimeType = $finfo->file($file['tmp_name']);
  29. $allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
  30. if (!in_array($mimeType, $allowedMimes, true)) {
  31. return ['success' => false, 'message' => 'Die hochgeladene Datei ist kein gültiges Bild.'];
  32. }
  33. $imagesDir = __DIR__ . '/../assets/images';
  34. if (!is_dir($imagesDir)) {
  35. mkdir($imagesDir, 0755, true);
  36. }
  37. $safeBaseName = preg_replace('/[^a-zA-Z0-9_-]/', '-', pathinfo($originalName, PATHINFO_FILENAME));
  38. $safeBaseName = trim((string) $safeBaseName, '-');
  39. if ($safeBaseName === '') {
  40. $safeBaseName = 'bild';
  41. }
  42. $targetFilename = $safeBaseName . '.' . $extension;
  43. $targetPath = $imagesDir . '/' . $targetFilename;
  44. $counter = 1;
  45. while (file_exists($targetPath)) {
  46. $targetFilename = $safeBaseName . '-' . $counter . '.' . $extension;
  47. $targetPath = $imagesDir . '/' . $targetFilename;
  48. $counter++;
  49. }
  50. if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
  51. return ['success' => false, 'message' => 'Bild konnte nicht gespeichert werden.'];
  52. }
  53. return ['success' => true, 'filename' => $targetFilename];
  54. }
  55. function isValidProductCategoryInput($categoryId) {
  56. return getCategoryById($categoryId) !== null;
  57. }
  58. function getSubmittedProductCategoryIds($submittedValues) {
  59. $selectedCategoryIds = normalizeProductCategoryIds($submittedValues['categories'] ?? []);
  60. $validCategoryIds = [];
  61. foreach ($selectedCategoryIds as $categoryId) {
  62. if (isValidProductCategoryInput($categoryId)) {
  63. $validCategoryIds[] = $categoryId;
  64. }
  65. }
  66. return $validCategoryIds;
  67. }
  68. function buildProductSizeStock($sizesInput, $submittedValues = [], $existingValues = []) {
  69. $sizes = getProductSizes(['sizes' => (string) $sizesInput]);
  70. $stockBySize = [];
  71. foreach ($sizes as $size) {
  72. $stockKey = 'stock_' . str_replace([' ', ','], '_', $size);
  73. if (isset($submittedValues[$stockKey])) {
  74. $stockBySize[$size] = max(0, (int) $submittedValues[$stockKey]);
  75. } elseif (isset($existingValues[$size])) {
  76. $stockBySize[$size] = max(0, (int) $existingValues[$size]);
  77. } else {
  78. $stockBySize[$size] = 0;
  79. }
  80. }
  81. return [
  82. 'sizes' => implode(',', $sizes),
  83. 'stock_by_size' => $stockBySize
  84. ];
  85. }
  86. // Handle product operations
  87. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  88. $products = getProducts();
  89. if (empty($categories)) {
  90. $message = 'Es ist keine Kategorie vorhanden. Bitte zuerst Kategorien anlegen.';
  91. $messageType = 'error';
  92. } elseif (isset($_POST['add_product'])) {
  93. $uploadResult = handleImageUpload();
  94. if (!$uploadResult['success']) {
  95. $message = $uploadResult['message'];
  96. $messageType = 'error';
  97. } else {
  98. $categoryIds = getSubmittedProductCategoryIds($_POST);
  99. $sizeData = buildProductSizeStock($_POST['sizes'] ?? '', $_POST);
  100. if (empty($categoryIds)) {
  101. $message = 'Bitte wählen Sie mindestens eine gültige Kategorie aus.';
  102. $messageType = 'error';
  103. } elseif ($sizeData['sizes'] === '') {
  104. $message = 'Bitte geben Sie mindestens eine Größe ein.';
  105. $messageType = 'error';
  106. } else {
  107. $newId = 1;
  108. if (!empty($products)) {
  109. $ids = array_column($products, 'id');
  110. $newId = max($ids) + 1;
  111. }
  112. $products[] = [
  113. 'id' => $newId,
  114. 'name' => sanitize($_POST['name']),
  115. 'description' => sanitize($_POST['description']),
  116. 'price' => (float) ($_POST['price'] ?? 0),
  117. 'categories' => $categoryIds,
  118. 'image' => $uploadResult['filename'] !== null ? $uploadResult['filename'] : sanitize($_POST['image']),
  119. 'sizes' => $sizeData['sizes'],
  120. 'stock_by_size' => $sizeData['stock_by_size']
  121. ];
  122. saveProducts($products);
  123. $message = 'Produkt erfolgreich hinzugefügt.';
  124. $messageType = 'success';
  125. }
  126. }
  127. }
  128. if (isset($_POST['update_product'])) {
  129. $uploadResult = handleImageUpload();
  130. if (!$uploadResult['success']) {
  131. $message = $uploadResult['message'];
  132. $messageType = 'error';
  133. } else {
  134. $productId = (int) ($_POST['product_id'] ?? 0);
  135. $categoryIds = getSubmittedProductCategoryIds($_POST);
  136. $existingProduct = null;
  137. foreach ($products as $product) {
  138. if ($product['id'] === $productId) {
  139. $existingProduct = $product;
  140. break;
  141. }
  142. }
  143. $existingStockBySize = isset($existingProduct['stock_by_size']) && is_array($existingProduct['stock_by_size'])
  144. ? $existingProduct['stock_by_size']
  145. : [];
  146. $sizeData = buildProductSizeStock($_POST['sizes'] ?? '', $_POST, $existingStockBySize);
  147. if (empty($categoryIds)) {
  148. $message = 'Bitte wählen Sie mindestens eine gültige Kategorie aus.';
  149. $messageType = 'error';
  150. } elseif ($existingProduct === null) {
  151. $message = 'Produkt nicht gefunden.';
  152. $messageType = 'error';
  153. } elseif ($sizeData['sizes'] === '') {
  154. $message = 'Bitte geben Sie mindestens eine Größe ein.';
  155. $messageType = 'error';
  156. } else {
  157. foreach ($products as &$product) {
  158. if ($product['id'] === $productId) {
  159. $product['name'] = sanitize($_POST['name']);
  160. $product['description'] = sanitize($_POST['description']);
  161. $product['price'] = (float) ($_POST['price'] ?? 0);
  162. $product['categories'] = $categoryIds;
  163. $product['image'] = $uploadResult['filename'] !== null ? $uploadResult['filename'] : sanitize($_POST['image']);
  164. $product['sizes'] = $sizeData['sizes'];
  165. $product['stock_by_size'] = $sizeData['stock_by_size'];
  166. unset($product['stock']);
  167. break;
  168. }
  169. }
  170. unset($product);
  171. saveProducts($products);
  172. $message = 'Produkt erfolgreich aktualisiert.';
  173. $messageType = 'success';
  174. }
  175. }
  176. }
  177. if (isset($_POST['delete_product'])) {
  178. $productId = (int) ($_POST['product_id'] ?? 0);
  179. $products = array_filter($products, function ($product) use ($productId) {
  180. return $product['id'] !== $productId;
  181. });
  182. $products = array_values($products);
  183. saveProducts($products);
  184. $message = 'Produkt erfolgreich gelöscht.';
  185. $messageType = 'success';
  186. }
  187. }
  188. $products = getProducts();
  189. $editingProduct = null;
  190. if (isset($_GET['edit'])) {
  191. $editingProduct = getProductById((int) $_GET['edit']);
  192. }
  193. $bodyClass = 'admin-page';
  194. include __DIR__ . '/../includes/header.php';
  195. ?>
  196. <div class="admin-header">
  197. <h2>Produkte verwalten</h2>
  198. <div>
  199. <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
  200. </div>
  201. </div>
  202. <?php if ($message !== ''): ?>
  203. <div class="alert alert-<?php echo $messageType; ?>">
  204. <?php echo htmlspecialchars($message); ?>
  205. </div>
  206. <?php endif; ?>
  207. <?php if ($editingProduct): ?>
  208. <div class="panel" style="padding: 2rem;">
  209. <h3>Produkt bearbeiten</h3>
  210. <form method="POST" enctype="multipart/form-data">
  211. <input type="hidden" name="product_id" value="<?php echo $editingProduct['id']; ?>">
  212. <div class="form-group">
  213. <label for="name">Name *</label>
  214. <input type="text" id="name" name="name" required value="<?php echo htmlspecialchars($editingProduct['name']); ?>">
  215. </div>
  216. <div class="form-group">
  217. <label for="description">Beschreibung</label>
  218. <textarea id="description" name="description" rows="4"><?php echo htmlspecialchars($editingProduct['description']); ?></textarea>
  219. </div>
  220. <div class="form-group">
  221. <label for="price">Preis (€) *</label>
  222. <input type="number" id="price" name="price" step="0.01" min="0" required value="<?php echo $editingProduct['price']; ?>">
  223. </div>
  224. <div class="form-group">
  225. <label for="categories">Kategorien *</label>
  226. <select id="categories" name="categories[]" multiple size="<?php echo max(3, min(8, count($categories))); ?>" required>
  227. <?php foreach ($categories as $category): ?>
  228. <option value="<?php echo htmlspecialchars($category['id']); ?>" <?php echo in_array($category['id'], getProductCategoryIds($editingProduct), true) ? 'selected' : ''; ?>>
  229. <?php echo htmlspecialchars($category['label']); ?>
  230. </option>
  231. <?php endforeach; ?>
  232. </select>
  233. <small>Mehrfachauswahl mit Strg/Cmd oder Umschalt. Auf Touch-Geräten können mehrere Einträge nacheinander markiert werden.</small>
  234. </div>
  235. <div class="form-group">
  236. <label for="sizes">Größen (kommagetrennt, z.B. Standard oder S,M,L,XL) *</label>
  237. <input type="text" id="sizes" name="sizes" required value="<?php echo htmlspecialchars($editingProduct['sizes'] ?? ''); ?>" placeholder="Standard" oninput="updateSizeStockFields()">
  238. <small>Alle Produkte nutzen größenbasierten Bestand. Für Artikel ohne Varianten z.B. <code>Standard</code> oder <code>Einheitsgröße</code> verwenden.</small>
  239. </div>
  240. <div id="size-stock-group">
  241. <?php
  242. $sizes = getProductSizes($editingProduct);
  243. $stockBySize = isset($editingProduct['stock_by_size']) && is_array($editingProduct['stock_by_size']) ? $editingProduct['stock_by_size'] : [];
  244. foreach ($sizes as $size):
  245. ?>
  246. <div class="form-group">
  247. <label>Lagerbestand für Größe "<?php echo htmlspecialchars($size); ?>" *</label>
  248. <input type="number" name="stock_<?php echo htmlspecialchars(str_replace([' ', ','], '_', $size)); ?>" min="0" value="<?php echo isset($stockBySize[$size]) ? (int) $stockBySize[$size] : 0; ?>" required>
  249. </div>
  250. <?php endforeach; ?>
  251. </div>
  252. <div class="form-group">
  253. <label for="image">Bilddateiname (z.B. tshirt.jpg)</label>
  254. <input type="text" id="image" name="image" value="<?php echo htmlspecialchars($editingProduct['image']); ?>">
  255. </div>
  256. <div class="form-group">
  257. <label for="image_file">Oder neues Bild hochladen</label>
  258. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  259. <small>Upload nach <code>assets/images</code>; ersetzt den Dateinamen oben automatisch.</small>
  260. </div>
  261. <script>
  262. function updateSizeStockFields() {
  263. const sizesInput = document.getElementById('sizes');
  264. const sizeStockGroup = document.getElementById('size-stock-group');
  265. const currentValues = {};
  266. sizeStockGroup.querySelectorAll('input[type="number"]').forEach((input) => {
  267. currentValues[input.name] = input.value;
  268. });
  269. const sizes = sizesInput.value.split(',').map((size) => size.trim()).filter((size, index, all) => size && all.indexOf(size) === index);
  270. let html = '';
  271. sizes.forEach((size) => {
  272. const safeName = size.replace(/[ ,]/g, '_');
  273. const fieldName = 'stock_' + safeName;
  274. const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '0';
  275. html += '<div class="form-group">';
  276. html += '<label>Lagerbestand für Größe "' + size.replace(/"/g, '&quot;') + '" *</label>';
  277. html += '<input type="number" name="' + fieldName + '" min="0" value="' + currentValue + '" required>';
  278. html += '</div>';
  279. });
  280. sizeStockGroup.innerHTML = html;
  281. }
  282. </script>
  283. <button type="submit" name="update_product" class="btn">Produkt aktualisieren</button>
  284. <a href="products.php" class="btn btn-secondary">Abbrechen</a>
  285. </form>
  286. </div>
  287. <?php else: ?>
  288. <div class="panel" style="padding: 2rem;">
  289. <h3>Neues Produkt hinzufügen</h3>
  290. <form method="POST" enctype="multipart/form-data">
  291. <div class="form-group">
  292. <label for="name">Name *</label>
  293. <input type="text" id="name" name="name" required>
  294. </div>
  295. <div class="form-group">
  296. <label for="description">Beschreibung</label>
  297. <textarea id="description" name="description" rows="4"></textarea>
  298. </div>
  299. <div class="form-group">
  300. <label for="price">Preis (€) *</label>
  301. <input type="number" id="price" name="price" step="0.01" min="0" required>
  302. </div>
  303. <div class="form-group">
  304. <label for="categories">Kategorien *</label>
  305. <select id="categories" name="categories[]" multiple size="<?php echo max(3, min(8, count($categories))); ?>" required>
  306. <?php foreach ($categories as $category): ?>
  307. <option value="<?php echo htmlspecialchars($category['id']); ?>">
  308. <?php echo htmlspecialchars($category['label']); ?>
  309. </option>
  310. <?php endforeach; ?>
  311. </select>
  312. <small>Mehrfachauswahl mit Strg/Cmd oder Umschalt. Auf Touch-Geräten können mehrere Einträge nacheinander markiert werden.</small>
  313. </div>
  314. <div class="form-group">
  315. <label for="sizes">Größen (kommagetrennt, z.B. Standard oder S,M,L,XL) *</label>
  316. <input type="text" id="sizes" name="sizes" required placeholder="Standard" oninput="updateSizeStockFields()">
  317. <small>Alle Produkte nutzen größenbasierten Bestand. Für Artikel ohne Varianten z.B. <code>Standard</code> oder <code>Einheitsgröße</code> verwenden.</small>
  318. </div>
  319. <div id="size-stock-group"></div>
  320. <div class="form-group">
  321. <label for="image">Bilddateiname (z.B. tshirt.jpg)</label>
  322. <input type="text" id="image" name="image">
  323. </div>
  324. <div class="form-group">
  325. <label for="image_file">Oder Bild hochladen</label>
  326. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  327. <small>Upload nach <code>assets/images</code>; Dateiname wird automatisch übernommen.</small>
  328. </div>
  329. <script>
  330. function updateSizeStockFields() {
  331. const sizesInput = document.getElementById('sizes');
  332. const sizeStockGroup = document.getElementById('size-stock-group');
  333. const currentValues = {};
  334. sizeStockGroup.querySelectorAll('input[type="number"]').forEach((input) => {
  335. currentValues[input.name] = input.value;
  336. });
  337. const sizes = sizesInput.value.split(',').map((size) => size.trim()).filter((size, index, all) => size && all.indexOf(size) === index);
  338. let html = '';
  339. sizes.forEach((size) => {
  340. const safeName = size.replace(/[ ,]/g, '_');
  341. const fieldName = 'stock_' + safeName;
  342. const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '0';
  343. html += '<div class="form-group">';
  344. html += '<label>Lagerbestand für Größe "' + size.replace(/"/g, '&quot;') + '" *</label>';
  345. html += '<input type="number" name="' + fieldName + '" min="0" value="' + currentValue + '" required>';
  346. html += '</div>';
  347. });
  348. sizeStockGroup.innerHTML = html;
  349. }
  350. </script>
  351. <button type="submit" name="add_product" class="btn">Produkt hinzufügen</button>
  352. </form>
  353. </div>
  354. <?php endif; ?>
  355. <h3>Alle Produkte</h3>
  356. <?php if (empty($products)): ?>
  357. <p>Keine Produkte vorhanden.</p>
  358. <?php else: ?>
  359. <div class="table-responsive">
  360. <table class="responsive-table">
  361. <thead>
  362. <tr>
  363. <th>ID</th>
  364. <th>Name</th>
  365. <th>Kategorien</th>
  366. <th>Preis</th>
  367. <th>Lagerbestand</th>
  368. <th>Aktionen</th>
  369. </tr>
  370. </thead>
  371. <tbody>
  372. <?php foreach ($products as $product): ?>
  373. <tr>
  374. <td data-label="ID"><?php echo $product['id']; ?></td>
  375. <td data-label="Name"><?php echo htmlspecialchars($product['name']); ?></td>
  376. <td data-label="Kategorien"><?php echo htmlspecialchars(implode(', ', getCategoryLabels(getProductCategoryIds($product)))); ?></td>
  377. <td data-label="Preis"><?php echo formatPrice($product['price']); ?></td>
  378. <td data-label="Lagerbestand">
  379. <?php
  380. $stockInfo = [];
  381. foreach (($product['stock_by_size'] ?? []) as $size => $stock) {
  382. $stockInfo[] = $size . ': ' . (int) $stock;
  383. }
  384. echo !empty($stockInfo) ? htmlspecialchars(implode(', ', $stockInfo)) : '0';
  385. ?>
  386. </td>
  387. <td data-label="Aktionen">
  388. <a href="?edit=<?php echo $product['id']; ?>" class="btn btn-small">Bearbeiten</a>
  389. <form method="POST" style="display: inline;" onsubmit="return confirm('Möchten Sie dieses Produkt wirklich löschen?');">
  390. <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
  391. <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
  392. </form>
  393. </td>
  394. </tr>
  395. <?php endforeach; ?>
  396. </tbody>
  397. </table>
  398. </div>
  399. <?php endif; ?>
  400. <?php include __DIR__ . '/../includes/footer.php'; ?>