products.php 19 KB

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