products.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. {
  14. if (
  15. !isset($_FILES[$fileInputName]) ||
  16. $_FILES[$fileInputName]["error"] === UPLOAD_ERR_NO_FILE
  17. ) {
  18. return ["success" => true, "filename" => null];
  19. }
  20. $file = $_FILES[$fileInputName];
  21. if ($file["error"] !== UPLOAD_ERR_OK) {
  22. return ["success" => false, "message" => "Upload fehlgeschlagen."];
  23. }
  24. $allowedExtensions = ["jpg", "jpeg", "png", "webp", "gif"];
  25. $originalName = basename($file["name"]);
  26. $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
  27. if (!in_array($extension, $allowedExtensions, true)) {
  28. return ["success" => false, "message" => "Ungültiger Dateityp."];
  29. }
  30. $finfo = new finfo(FILEINFO_MIME_TYPE);
  31. $mimeType = $finfo->file($file["tmp_name"]);
  32. $allowedMimes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
  33. if (!in_array($mimeType, $allowedMimes, true)) {
  34. return [
  35. "success" => false,
  36. "message" => "Die Datei ist kein gültiges Bild.",
  37. ];
  38. }
  39. $uploadsDir = rtrim(UPLOADS_DIR, "/\\");
  40. if (
  41. !is_dir($uploadsDir) &&
  42. !mkdir($uploadsDir, 02775, true) &&
  43. !is_dir($uploadsDir)
  44. ) {
  45. return [
  46. "success" => false,
  47. "message" => "Upload-Verzeichnis konnte nicht erstellt werden.",
  48. ];
  49. }
  50. if (is_dir($uploadsDir)) {
  51. @chmod($uploadsDir, 02775);
  52. }
  53. if (!is_writable($uploadsDir)) {
  54. return [
  55. "success" => false,
  56. "message" =>
  57. "Upload-Verzeichnis ist nicht beschreibbar: " . $uploadsDir,
  58. ];
  59. }
  60. $safeBaseName = preg_replace(
  61. "/[^a-zA-Z0-9_-]/",
  62. "-",
  63. pathinfo($originalName, PATHINFO_FILENAME),
  64. );
  65. $safeBaseName = trim((string) $safeBaseName, "-");
  66. if ($safeBaseName === "") {
  67. $safeBaseName = "bild";
  68. }
  69. $targetFilename = $safeBaseName . "." . $extension;
  70. $targetPath = $uploadsDir . "/" . $targetFilename;
  71. $counter = 1;
  72. while (file_exists($targetPath)) {
  73. $targetFilename = $safeBaseName . "-" . $counter . "." . $extension;
  74. $targetPath = $uploadsDir . "/" . $targetFilename;
  75. $counter++;
  76. }
  77. if (!move_uploaded_file($file["tmp_name"], $targetPath)) {
  78. return [
  79. "success" => false,
  80. "message" => "Bild konnte nicht gespeichert werden.",
  81. ];
  82. }
  83. return ["success" => true, "filename" => $targetFilename];
  84. }
  85. function buildProductAvailabilityFields(
  86. $sizesInput,
  87. $submittedValues = [],
  88. $existingValues = [],
  89. ) {
  90. $sizes = getProductSizes(["sizes" => (string) $sizesInput]);
  91. if (empty($sizes)) {
  92. $sizes = ["Standard"];
  93. }
  94. $availabilityLabels = [];
  95. foreach ($sizes as $size) {
  96. $fieldName = "availability_" . str_replace([" ", ","], "_", $size);
  97. if (isset($submittedValues[$fieldName])) {
  98. $availabilityLabels[$size] = trim(
  99. (string) $submittedValues[$fieldName],
  100. );
  101. } else {
  102. $availabilityLabels[$size] = trim(
  103. (string) ($existingValues[$size] ?? ""),
  104. );
  105. }
  106. }
  107. return [
  108. "sizes" => implode(",", $sizes),
  109. "availability_labels" => $availabilityLabels,
  110. ];
  111. }
  112. function getSubmittedProductCategoryIds($submittedValues)
  113. {
  114. $selectedCategoryIds = normalizeProductCategoryIds(
  115. $submittedValues["categories"] ?? [],
  116. );
  117. $validCategoryIds = [];
  118. foreach ($selectedCategoryIds as $categoryId) {
  119. if (getCategoryById($categoryId) !== null) {
  120. $validCategoryIds[] = $categoryId;
  121. }
  122. }
  123. return $validCategoryIds;
  124. }
  125. if ($_SERVER['REQUEST_METHOD'] === "POST") {
  126. // Validate CSRF token
  127. if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
  128. $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
  129. $messageType = "error";
  130. } else {
  131. $products = getProducts();
  132. if (empty($categories)) {
  133. $message = "Bitte zuerst mindestens eine Kategorie anlegen.";
  134. $messageType = "error";
  135. } elseif (
  136. isset($_POST['add_product']) ||
  137. isset($_POST['update_product'])
  138. ) {
  139. $uploadResult = handleImageUpload();
  140. if (!$uploadResult["success"]) {
  141. $message = $uploadResult["message"];
  142. $messageType = "error";
  143. } else {
  144. $categoryIds = getSubmittedProductCategoryIds($_POST);
  145. $existingLabels = [];
  146. $productId = isset($_POST['product_id'])
  147. ? (int) $_POST['product_id']
  148. : 0;
  149. foreach ($products as $product) {
  150. if ((int) $product["id"] === $productId) {
  151. $existingLabels = $product["availability_labels"] ?? [];
  152. break;
  153. }
  154. }
  155. $sizeData = buildProductAvailabilityFields(
  156. $_POST['sizes'] ?? "",
  157. $_POST,
  158. $existingLabels,
  159. );
  160. if (empty($categoryIds)) {
  161. $message =
  162. "Bitte mindestens eine gültige Kategorie auswählen.";
  163. $messageType = "error";
  164. } else {
  165. $record = [
  166. "name" => sanitize($_POST['name'] ?? ""),
  167. "description" => trim(
  168. (string) ($_POST['description'] ?? ""),
  169. ),
  170. "categories" => $categoryIds,
  171. "image" =>
  172. $uploadResult["filename"] !== null
  173. ? $uploadResult["filename"]
  174. : trim((string) ($_POST['image'] ?? "")),
  175. "sizes" => $sizeData["sizes"],
  176. "availability_labels" =>
  177. $sizeData["availability_labels"],
  178. ];
  179. if ($record["name"] === "") {
  180. $message = "Bitte einen Produktnamen eingeben.";
  181. $messageType = "error";
  182. } elseif (isset($_POST['add_product'])) {
  183. $newId = empty($products)
  184. ? 1
  185. : max(
  186. array_map(function ($product) {
  187. return (int) $product["id"];
  188. }, $products),
  189. ) + 1;
  190. $record["id"] = $newId;
  191. $products[] = $record;
  192. if (saveProducts($products)) {
  193. logAccess("Admin added product", [
  194. "product_id" => $newId,
  195. "product_name" => $record["name"],
  196. ]);
  197. $message = "Produkt wurde angelegt.";
  198. $messageType = "success";
  199. } else {
  200. $message =
  201. "Produkt konnte nicht gespeichert werden.";
  202. $messageType = "error";
  203. }
  204. } else {
  205. $updated = false;
  206. foreach ($products as &$product) {
  207. if ((int) $product["id"] === $productId) {
  208. $record["id"] = $productId;
  209. $product = $record;
  210. $updated = true;
  211. break;
  212. }
  213. }
  214. unset($product);
  215. if ($updated) {
  216. if (saveProducts($products)) {
  217. logAccess("Admin updated product", [
  218. "product_id" => $productId,
  219. "product_name" => $record["name"],
  220. ]);
  221. $message = "Produkt wurde aktualisiert.";
  222. $messageType = "success";
  223. } else {
  224. $message =
  225. "Produkt konnte nicht gespeichert werden.";
  226. $messageType = "error";
  227. }
  228. } else {
  229. $message = "Produkt nicht gefunden.";
  230. $messageType = "error";
  231. }
  232. }
  233. }
  234. }
  235. }
  236. if (isset($_POST['delete_product'])) {
  237. $productId = (int) ($_POST['product_id'] ?? 0);
  238. $productName = "";
  239. foreach ($products as $product) {
  240. if ((int) $product["id"] === $productId) {
  241. $productName = $product["name"];
  242. break;
  243. }
  244. }
  245. $products = array_values(
  246. array_filter($products, function ($product) use ($productId) {
  247. return (int) $product["id"] !== $productId;
  248. }),
  249. );
  250. if (saveProducts($products)) {
  251. logAccess("Admin deleted product", [
  252. "product_id" => $productId,
  253. "product_name" => $productName,
  254. ]);
  255. $message = "Produkt wurde gelöscht.";
  256. $messageType = "success";
  257. } else {
  258. $message = "Produkt konnte nicht gelöscht werden.";
  259. $messageType = "error";
  260. }
  261. }
  262. }
  263. }
  264. $products = getProducts();
  265. $editingProduct = isset($_GET['edit'])
  266. ? getProductById((int) $_GET['edit'])
  267. : null;
  268. $bodyClass = "admin-page";
  269. include __DIR__ . "/../includes/header.php";
  270. ?>
  271. <div class="admin-header">
  272. <h2>Produkte verwalten</h2>
  273. <div>
  274. <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
  275. </div>
  276. </div>
  277. <?php if ($message !== ""): ?>
  278. <div class="alert alert-<?php echo escape($messageType); ?>">
  279. <?php echo escape($message); ?>
  280. </div>
  281. <?php endif; ?>
  282. <?php
  283. $currentProduct = $editingProduct ?: [
  284. "id" => "",
  285. "name" => "",
  286. "description" => "",
  287. "categories" => [],
  288. "sizes" => "Standard",
  289. "availability_labels" => ["Standard" => ""],
  290. "image" => "",
  291. ];
  292. $currentSizes = getProductSizes($currentProduct);
  293. if (empty($currentSizes)) {
  294. $currentSizes = ["Standard"];
  295. }
  296. ?>
  297. <div class="panel panel-lg">
  298. <h3><?php echo $editingProduct
  299. ? "Produkt bearbeiten"
  300. : "Neues Produkt anlegen"; ?></h3>
  301. <form method="POST" enctype="multipart/form-data">
  302. <?php echo csrfField(); ?>
  303. <?php if ($editingProduct): ?>
  304. <input type="hidden" name="product_id" value="<?php echo (int) $editingProduct[
  305. "id"
  306. ]; ?>">
  307. <?php endif; ?>
  308. <div class="form-group">
  309. <label for="name">Name *</label>
  310. <input type="text" id="name" name="name" required value="<?php echo escape(
  311. $currentProduct["name"],
  312. ); ?>">
  313. </div>
  314. <div class="form-group">
  315. <label for="description">Beschreibung</label>
  316. <textarea id="description" name="description" rows="4"><?php echo escape(
  317. $currentProduct["description"],
  318. ); ?></textarea>
  319. </div>
  320. <div class="form-group">
  321. <label for="categories">Kategorien *</label>
  322. <select id="categories" name="categories[]" multiple size="<?php echo max(
  323. 3,
  324. min(8, count($categories)),
  325. ); ?>" required>
  326. <?php foreach ($categories as $category): ?>
  327. <option value="<?php echo escape(
  328. $category["id"],
  329. ); ?>" <?php echo in_array(
  330. $category["id"],
  331. getProductCategoryIds($currentProduct),
  332. true,
  333. )
  334. ? "selected"
  335. : ""; ?>>
  336. <?php echo escape($category["label"]); ?>
  337. </option>
  338. <?php endforeach; ?>
  339. </select>
  340. </div>
  341. <div class="form-group">
  342. <label for="sizes">Größen (kommagetrennt) *</label>
  343. <input type="text" id="sizes" name="sizes" required value="<?php echo escape(
  344. $currentProduct["sizes"],
  345. ); ?>" placeholder="Standard" oninput="updateAvailabilityFields()">
  346. <small>Für Artikel ohne Varianten z. B. <code>Standard</code> oder <code>Einheitsgröße</code>.</small>
  347. </div>
  348. <div id="availability-group">
  349. <?php foreach ($currentSizes as $size): ?>
  350. <div class="form-group">
  351. <label>Lieferhinweis für Größe "<?php echo escape(
  352. $size,
  353. ); ?>"</label>
  354. <textarea name="availability_<?php echo escape(
  355. str_replace([" ", ","], "_", $size),
  356. ); ?>" rows="2" placeholder="Optionaler Hinweis"><?php echo escape(
  357. $currentProduct["availability_labels"][$size] ?? "",
  358. ); ?></textarea>
  359. </div>
  360. <?php endforeach; ?>
  361. </div>
  362. <div class="form-group">
  363. <label for="image">Bilddateiname</label>
  364. <input type="text" id="image" name="image" value="<?php echo escape(
  365. $currentProduct["image"],
  366. ); ?>">
  367. </div>
  368. <div class="form-group">
  369. <label for="image_file">Oder Bild hochladen</label>
  370. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  371. </div>
  372. <button type="submit" name="<?php echo $editingProduct
  373. ? "update_product"
  374. : "add_product"; ?>" class="btn">
  375. <?php echo $editingProduct
  376. ? "Produkt aktualisieren"
  377. : "Produkt anlegen"; ?>
  378. </button>
  379. <?php if ($editingProduct): ?>
  380. <a href="products.php" class="btn btn-secondary">Abbrechen</a>
  381. <?php endif; ?>
  382. </form>
  383. </div>
  384. <script>
  385. function updateAvailabilityFields() {
  386. const sizesInput = document.getElementById('sizes');
  387. const group = document.getElementById('availability-group');
  388. const currentValues = {};
  389. group.querySelectorAll('textarea').forEach((textarea) => {
  390. currentValues[textarea.name] = textarea.value;
  391. });
  392. const sizes = sizesInput.value
  393. .split(',')
  394. .map((size) => size.trim())
  395. .filter((size, index, all) => size && all.indexOf(size) === index);
  396. const finalSizes = sizes.length > 0 ? sizes : ['Standard'];
  397. let html = '';
  398. finalSizes.forEach((size) => {
  399. const safeName = size.replace(/[ ,]/g, '_');
  400. const fieldName = 'availability_' + safeName;
  401. const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '';
  402. html += '<div class="form-group">';
  403. html += '<label>Lieferhinweis für Größe "' + size.replace(/"/g, '&quot;') + '"</label>';
  404. html += '<textarea name="' + fieldName + '" rows="2" placeholder="Optionaler Hinweis">' + currentValue.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
  405. html += '</div>';
  406. });
  407. group.innerHTML = html;
  408. }
  409. </script>
  410. <h3>Alle Produkte</h3>
  411. <?php if (empty($products)): ?>
  412. <p>Keine Produkte vorhanden.</p>
  413. <?php else: ?>
  414. <div class="table-responsive">
  415. <table class="responsive-table">
  416. <thead>
  417. <tr>
  418. <th class="product-id-column">ID</th>
  419. <th>Name</th>
  420. <th>Kategorien</th>
  421. <th>Größen</th>
  422. <th>Lieferhinweise</th>
  423. <th>Aktionen</th>
  424. </tr>
  425. </thead>
  426. <tbody>
  427. <?php foreach ($products as $product): ?>
  428. <tr>
  429. <td data-label="ID" class="product-id-column"><?php echo (int) $product[
  430. "id"
  431. ]; ?></td>
  432. <td data-label="Name"><?php echo escape(
  433. $product["name"],
  434. ); ?></td>
  435. <td data-label="Kategorien"><?php echo escape(
  436. implode(
  437. ", ",
  438. getCategoryLabels(
  439. getProductCategoryIds($product),
  440. ),
  441. ),
  442. ); ?></td>
  443. <td data-label="Größen"><?php echo escape(
  444. implode(", ", getProductSizes($product)),
  445. ); ?></td>
  446. <td data-label="Lieferhinweise">
  447. <?php
  448. $labels = [];
  449. foreach (
  450. $product["availability_labels"] ?? []
  451. as $size => $label
  452. ) {
  453. if (trim((string) $label) !== "") {
  454. $labels[] = $size . ": " . $label;
  455. }
  456. }
  457. echo empty($labels)
  458. ? "Keine"
  459. : escape(implode(" | ", $labels));
  460. ?>
  461. </td>
  462. <td data-label="Aktionen">
  463. <a href="?edit=<?php echo (int) $product[
  464. "id"
  465. ]; ?>" class="btn btn-small">Bearbeiten</a>
  466. <form method="POST" class="inline-form" onsubmit="return confirm('Produkt wirklich löschen?');">
  467. <?php echo csrfField(); ?>
  468. <input type="hidden" name="product_id" value="<?php echo (int) $product[
  469. "id"
  470. ]; ?>">
  471. <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
  472. </form>
  473. </td>
  474. </tr>
  475. <?php endforeach; ?>
  476. </tbody>
  477. </table>
  478. </div>
  479. <?php endif; ?>
  480. <?php include __DIR__ . "/../includes/footer.php"; ?>