products.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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. 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. Bitte erneut versuchen.'];
  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. Erlaubt: JPG, PNG, WEBP, GIF.'];
  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 hochgeladene 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($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. // Handle product operations
  55. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  56. $products = getProducts();
  57. if (isset($_POST['add_product'])) {
  58. $uploadResult = handleImageUpload();
  59. if (!$uploadResult['success']) {
  60. $message = $uploadResult['message'];
  61. $messageType = 'error';
  62. } else {
  63. // Generate new ID
  64. $newId = 1;
  65. if (!empty($products)) {
  66. $ids = array_column($products, 'id');
  67. $newId = max($ids) + 1;
  68. }
  69. $newProduct = [
  70. 'id' => $newId,
  71. 'name' => sanitize($_POST['name']),
  72. 'description' => sanitize($_POST['description']),
  73. 'price' => (float)$_POST['price'],
  74. 'category' => sanitize($_POST['category']),
  75. 'image' => $uploadResult['filename'] !== null ? $uploadResult['filename'] : sanitize($_POST['image'])
  76. ];
  77. // Handle stock - per size for apparel, general for merch
  78. if ($newProduct['category'] === 'apparel' && !empty($_POST['sizes'])) {
  79. $sizes = sanitize($_POST['sizes']);
  80. $newProduct['sizes'] = $sizes; // Store as comma-separated string
  81. // Initialize stock_by_size
  82. $sizeArray = array_map('trim', explode(',', $sizes));
  83. $newProduct['stock_by_size'] = [];
  84. foreach ($sizeArray as $size) {
  85. $stockKey = 'stock_' . str_replace([' ', ','], '_', $size);
  86. $newProduct['stock_by_size'][$size] = isset($_POST[$stockKey]) ? (int)$_POST[$stockKey] : 0;
  87. }
  88. } else {
  89. $newProduct['stock'] = (int)$_POST['stock'];
  90. }
  91. $products[] = $newProduct;
  92. saveProducts($products);
  93. $message = 'Produkt erfolgreich hinzugefügt.';
  94. $messageType = 'success';
  95. }
  96. }
  97. if (isset($_POST['update_product'])) {
  98. $uploadResult = handleImageUpload();
  99. if (!$uploadResult['success']) {
  100. $message = $uploadResult['message'];
  101. $messageType = 'error';
  102. } else {
  103. $productId = (int)$_POST['product_id'];
  104. foreach ($products as &$product) {
  105. if ($product['id'] == $productId) {
  106. $product['name'] = sanitize($_POST['name']);
  107. $product['description'] = sanitize($_POST['description']);
  108. $product['price'] = (float)$_POST['price'];
  109. $product['category'] = sanitize($_POST['category']);
  110. $product['image'] = $uploadResult['filename'] !== null ? $uploadResult['filename'] : sanitize($_POST['image']);
  111. // Update stock - per size for apparel, general for merch
  112. if ($product['category'] === 'apparel') {
  113. if (!empty($_POST['sizes'])) {
  114. $product['sizes'] = sanitize($_POST['sizes']);
  115. // Update stock_by_size
  116. $sizeArray = array_map('trim', explode(',', $product['sizes']));
  117. if (!isset($product['stock_by_size']) || !is_array($product['stock_by_size'])) {
  118. $product['stock_by_size'] = [];
  119. }
  120. foreach ($sizeArray as $size) {
  121. $stockKey = 'stock_' . str_replace([' ', ','], '_', $size);
  122. $product['stock_by_size'][$size] = isset($_POST[$stockKey]) ? (int)$_POST[$stockKey] : (isset($product['stock_by_size'][$size]) ? $product['stock_by_size'][$size] : 0);
  123. }
  124. // Remove sizes that are no longer in the list
  125. $product['stock_by_size'] = array_intersect_key($product['stock_by_size'], array_flip($sizeArray));
  126. unset($product['stock']); // Remove general stock for apparel
  127. } else {
  128. unset($product['sizes']);
  129. unset($product['stock_by_size']);
  130. }
  131. } else {
  132. $product['stock'] = (int)$_POST['stock'];
  133. unset($product['sizes']);
  134. unset($product['stock_by_size']);
  135. }
  136. break;
  137. }
  138. }
  139. saveProducts($products);
  140. $message = 'Produkt erfolgreich aktualisiert.';
  141. $messageType = 'success';
  142. }
  143. }
  144. if (isset($_POST['delete_product'])) {
  145. $productId = (int)$_POST['product_id'];
  146. $products = array_filter($products, function($product) use ($productId) {
  147. return $product['id'] != $productId;
  148. });
  149. $products = array_values($products); // Re-index
  150. saveProducts($products);
  151. $message = 'Produkt erfolgreich gelöscht.';
  152. $messageType = 'success';
  153. }
  154. }
  155. $products = getProducts();
  156. $editingProduct = null;
  157. if (isset($_GET['edit'])) {
  158. $editingProduct = getProductById((int)$_GET['edit']);
  159. }
  160. $bodyClass = 'admin-page';
  161. include __DIR__ . '/../includes/header.php';
  162. ?>
  163. <div class="admin-header">
  164. <h2>Produkte verwalten</h2>
  165. <div>
  166. <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
  167. </div>
  168. </div>
  169. <?php if ($message): ?>
  170. <div class="alert alert-<?php echo $messageType; ?>">
  171. <?php echo htmlspecialchars($message); ?>
  172. </div>
  173. <?php endif; ?>
  174. <?php if ($editingProduct): ?>
  175. <div class="panel" style="padding: 2rem;">
  176. <h3>Produkt bearbeiten</h3>
  177. <form method="POST" enctype="multipart/form-data">
  178. <input type="hidden" name="product_id" value="<?php echo $editingProduct['id']; ?>">
  179. <div class="form-group">
  180. <label for="name">Name *</label>
  181. <input type="text" id="name" name="name" required value="<?php echo htmlspecialchars($editingProduct['name']); ?>">
  182. </div>
  183. <div class="form-group">
  184. <label for="description">Beschreibung</label>
  185. <textarea id="description" name="description" rows="4"><?php echo htmlspecialchars($editingProduct['description']); ?></textarea>
  186. </div>
  187. <div class="form-group">
  188. <label for="price">Preis (€) *</label>
  189. <input type="number" id="price" name="price" step="0.01" min="0" required value="<?php echo $editingProduct['price']; ?>">
  190. </div>
  191. <div class="form-group">
  192. <label for="category">Kategorie *</label>
  193. <select id="category" name="category" required onchange="toggleStockFields()">
  194. <option value="apparel" <?php echo $editingProduct['category'] === 'apparel' ? 'selected' : ''; ?>>Bekleidung</option>
  195. <option value="merch" <?php echo $editingProduct['category'] === 'merch' ? 'selected' : ''; ?>>Merchandise</option>
  196. </select>
  197. </div>
  198. <div class="form-group" id="stock-group" style="<?php echo $editingProduct['category'] === 'merch' ? '' : 'display: none;'; ?>">
  199. <label for="stock">Lagerbestand *</label>
  200. <input type="number" id="stock" name="stock" min="0" value="<?php echo isset($editingProduct['stock']) ? (int)$editingProduct['stock'] : 0; ?>">
  201. </div>
  202. <div class="form-group" id="sizes-group" style="<?php echo $editingProduct['category'] === 'apparel' ? '' : 'display: none;'; ?>">
  203. <label for="sizes">Größen (kommagetrennt, z.B. S,M,L,XL,XXL)</label>
  204. <input type="text" id="sizes" name="sizes" value="<?php echo isset($editingProduct['sizes']) ? htmlspecialchars($editingProduct['sizes']) : ''; ?>" placeholder="S,M,L,XL" onchange="updateSizeStockFields()">
  205. </div>
  206. <div id="size-stock-group" style="<?php echo $editingProduct['category'] === 'apparel' ? '' : 'display: none;'; ?>">
  207. <?php if ($editingProduct['category'] === 'apparel' && !empty($editingProduct['sizes'])): ?>
  208. <?php
  209. $sizes = array_map('trim', explode(',', $editingProduct['sizes']));
  210. $stockBySize = isset($editingProduct['stock_by_size']) && is_array($editingProduct['stock_by_size']) ? $editingProduct['stock_by_size'] : [];
  211. foreach ($sizes as $size):
  212. ?>
  213. <div class="form-group">
  214. <label>Lagerbestand für Größe "<?php echo htmlspecialchars($size); ?>" *</label>
  215. <input type="number" name="stock_<?php echo htmlspecialchars(str_replace([' ', ','], '_', $size)); ?>" min="0" value="<?php echo isset($stockBySize[$size]) ? (int)$stockBySize[$size] : 0; ?>" required>
  216. </div>
  217. <?php endforeach; ?>
  218. <?php endif; ?>
  219. </div>
  220. <div class="form-group">
  221. <label for="image">Bilddateiname (z.B. tshirt.jpg)</label>
  222. <input type="text" id="image" name="image" value="<?php echo htmlspecialchars($editingProduct['image']); ?>">
  223. </div>
  224. <div class="form-group">
  225. <label for="image_file">Oder neues Bild hochladen</label>
  226. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  227. <small>Upload nach <code>assets/images</code>; ersetzt den Dateinamen oben automatisch.</small>
  228. </div>
  229. <script>
  230. function toggleStockFields() {
  231. const category = document.getElementById('category').value;
  232. const stockGroup = document.getElementById('stock-group');
  233. const sizesGroup = document.getElementById('sizes-group');
  234. const sizeStockGroup = document.getElementById('size-stock-group');
  235. if (category === 'apparel') {
  236. stockGroup.style.display = 'none';
  237. sizesGroup.style.display = 'block';
  238. sizeStockGroup.style.display = 'block';
  239. updateSizeStockFields();
  240. } else {
  241. stockGroup.style.display = 'block';
  242. sizesGroup.style.display = 'none';
  243. sizeStockGroup.style.display = 'none';
  244. }
  245. }
  246. function updateSizeStockFields() {
  247. const sizesInput = document.getElementById('sizes');
  248. const sizeStockGroup = document.getElementById('size-stock-group');
  249. const sizes = sizesInput.value.split(',').map(s => s.trim()).filter(s => s);
  250. let html = '';
  251. sizes.forEach(size => {
  252. const safeName = size.replace(/[ ,]/g, '_');
  253. html += '<div class="form-group">';
  254. html += '<label>Lagerbestand für Größe "' + size + '" *</label>';
  255. html += '<input type="number" name="stock_' + safeName + '" min="0" value="0" required>';
  256. html += '</div>';
  257. });
  258. sizeStockGroup.innerHTML = html;
  259. }
  260. </script>
  261. <button type="submit" name="update_product" class="btn">Produkt aktualisieren</button>
  262. <a href="products.php" class="btn btn-secondary">Abbrechen</a>
  263. </form>
  264. </div>
  265. <?php else: ?>
  266. <div class="panel" style="padding: 2rem;">
  267. <h3>Neues Produkt hinzufügen</h3>
  268. <form method="POST" enctype="multipart/form-data">
  269. <div class="form-group">
  270. <label for="name">Name *</label>
  271. <input type="text" id="name" name="name" required>
  272. </div>
  273. <div class="form-group">
  274. <label for="description">Beschreibung</label>
  275. <textarea id="description" name="description" rows="4"></textarea>
  276. </div>
  277. <div class="form-group">
  278. <label for="price">Preis (€) *</label>
  279. <input type="number" id="price" name="price" step="0.01" min="0" required>
  280. </div>
  281. <div class="form-group">
  282. <label for="category">Kategorie *</label>
  283. <select id="category" name="category" required onchange="toggleStockFields()">
  284. <option value="apparel">Bekleidung</option>
  285. <option value="merch">Merchandise</option>
  286. </select>
  287. </div>
  288. <div class="form-group" id="stock-group" style="display: none;">
  289. <label for="stock">Lagerbestand *</label>
  290. <input type="number" id="stock" name="stock" min="0" value="0">
  291. </div>
  292. <div class="form-group" id="sizes-group" style="display: none;">
  293. <label for="sizes">Größen (kommagetrennt, z.B. S,M,L,XL,XXL)</label>
  294. <input type="text" id="sizes" name="sizes" placeholder="S,M,L,XL" onchange="updateSizeStockFields()">
  295. </div>
  296. <div id="size-stock-group" style="display: none;"></div>
  297. <div class="form-group">
  298. <label for="image">Bilddateiname (z.B. tshirt.jpg)</label>
  299. <input type="text" id="image" name="image">
  300. </div>
  301. <div class="form-group">
  302. <label for="image_file">Oder Bild hochladen</label>
  303. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  304. <small>Upload nach <code>assets/images</code>; Dateiname wird automatisch übernommen.</small>
  305. </div>
  306. <script>
  307. function toggleStockFields() {
  308. const category = document.getElementById('category').value;
  309. const stockGroup = document.getElementById('stock-group');
  310. const sizesGroup = document.getElementById('sizes-group');
  311. const sizeStockGroup = document.getElementById('size-stock-group');
  312. if (category === 'apparel') {
  313. stockGroup.style.display = 'none';
  314. sizesGroup.style.display = 'block';
  315. sizeStockGroup.style.display = 'block';
  316. updateSizeStockFields();
  317. } else {
  318. stockGroup.style.display = 'block';
  319. sizesGroup.style.display = 'none';
  320. sizeStockGroup.style.display = 'none';
  321. }
  322. }
  323. function updateSizeStockFields() {
  324. const sizesInput = document.getElementById('sizes');
  325. const sizeStockGroup = document.getElementById('size-stock-group');
  326. const sizes = sizesInput.value.split(',').map(s => s.trim()).filter(s => s);
  327. let html = '';
  328. sizes.forEach(size => {
  329. const safeName = size.replace(/[ ,]/g, '_');
  330. html += '<div class="form-group">';
  331. html += '<label>Lagerbestand für Größe "' + size + '" *</label>';
  332. html += '<input type="number" name="stock_' + safeName + '" min="0" value="0" required>';
  333. html += '</div>';
  334. });
  335. sizeStockGroup.innerHTML = html;
  336. }
  337. </script>
  338. <button type="submit" name="add_product" class="btn">Produkt hinzufügen</button>
  339. </form>
  340. </div>
  341. <?php endif; ?>
  342. <h3>Alle Produkte</h3>
  343. <?php if (empty($products)): ?>
  344. <p>Keine Produkte vorhanden.</p>
  345. <?php else: ?>
  346. <table class="responsive-table">
  347. <thead>
  348. <tr>
  349. <th>ID</th>
  350. <th>Name</th>
  351. <th>Kategorie</th>
  352. <th>Preis</th>
  353. <th>Lagerbestand</th>
  354. <th>Aktionen</th>
  355. </tr>
  356. </thead>
  357. <tbody>
  358. <?php foreach ($products as $product): ?>
  359. <tr>
  360. <td data-label="ID"><?php echo $product['id']; ?></td>
  361. <td data-label="Name"><?php echo htmlspecialchars($product['name']); ?></td>
  362. <td data-label="Kategorie"><?php echo $product['category'] === 'apparel' ? 'Bekleidung' : 'Merchandise'; ?></td>
  363. <td data-label="Preis"><?php echo formatPrice($product['price']); ?></td>
  364. <td data-label="Lagerbestand">
  365. <?php
  366. if ($product['category'] === 'apparel' && isset($product['stock_by_size']) && is_array($product['stock_by_size'])) {
  367. $stockInfo = [];
  368. foreach ($product['stock_by_size'] as $size => $stock) {
  369. $stockInfo[] = "$size: $stock";
  370. }
  371. echo implode(', ', $stockInfo) ?: '0';
  372. } else {
  373. echo isset($product['stock']) ? (int)$product['stock'] : 0;
  374. }
  375. ?>
  376. </td>
  377. <td data-label="Aktionen">
  378. <a href="?edit=<?php echo $product['id']; ?>" class="btn btn-small">Bearbeiten</a>
  379. <form method="POST" style="display: inline;" onsubmit="return confirm('Möchten Sie dieses Produkt wirklich löschen?');">
  380. <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
  381. <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
  382. </form>
  383. </td>
  384. </tr>
  385. <?php endforeach; ?>
  386. </tbody>
  387. </table>
  388. <?php endif; ?>
  389. <?php include __DIR__ . '/../includes/footer.php'; ?>