products.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. 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. $updated = false;
  201. foreach ($products as &$product) {
  202. if ((int) $product["id"] === $productId) {
  203. $record["id"] = $productId;
  204. $product = $record;
  205. $updated = true;
  206. break;
  207. }
  208. }
  209. unset($product);
  210. if ($updated) {
  211. saveProducts($products);
  212. logAccess("Admin updated product", [
  213. "product_id" => $productId,
  214. "product_name" => $record["name"],
  215. ]);
  216. $message = "Produkt wurde aktualisiert.";
  217. $messageType = "success";
  218. } else {
  219. $message = "Produkt nicht gefunden.";
  220. $messageType = "error";
  221. }
  222. }
  223. }
  224. }
  225. }
  226. if (isset($_POST["delete_product"])) {
  227. $productId = (int) ($_POST["product_id"] ?? 0);
  228. $productName = "";
  229. foreach ($products as $product) {
  230. if ((int) $product["id"] === $productId) {
  231. $productName = $product["name"];
  232. break;
  233. }
  234. }
  235. $products = array_values(
  236. array_filter($products, function ($product) use ($productId) {
  237. return (int) $product["id"] !== $productId;
  238. }),
  239. );
  240. saveProducts($products);
  241. logAccess("Admin deleted product", [
  242. "product_id" => $productId,
  243. "product_name" => $productName,
  244. ]);
  245. $message = "Produkt wurde gelöscht.";
  246. $messageType = "success";
  247. }
  248. }
  249. }
  250. $products = getProducts();
  251. $editingProduct = isset($_GET["edit"])
  252. ? getProductById((int) $_GET["edit"])
  253. : null;
  254. $bodyClass = "admin-page";
  255. include __DIR__ . "/../includes/header.php";
  256. ?>
  257. <div class="admin-header">
  258. <h2>Produkte verwalten</h2>
  259. <div>
  260. <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
  261. </div>
  262. </div>
  263. <?php if ($message !== ""): ?>
  264. <div class="alert alert-<?php echo escape($messageType); ?>">
  265. <?php echo escape($message); ?>
  266. </div>
  267. <?php endif; ?>
  268. <?php
  269. $currentProduct = $editingProduct ?: [
  270. "id" => "",
  271. "name" => "",
  272. "description" => "",
  273. "categories" => [],
  274. "sizes" => "Standard",
  275. "availability_labels" => ["Standard" => ""],
  276. "image" => "",
  277. ];
  278. $currentSizes = getProductSizes($currentProduct);
  279. if (empty($currentSizes)) {
  280. $currentSizes = ["Standard"];
  281. }
  282. ?>
  283. <div class="panel panel-lg">
  284. <h3><?php echo $editingProduct
  285. ? "Produkt bearbeiten"
  286. : "Neues Produkt anlegen"; ?></h3>
  287. <form method="POST" enctype="multipart/form-data">
  288. <?php echo csrfField(); ?>
  289. <?php if ($editingProduct): ?>
  290. <input type="hidden" name="product_id" value="<?php echo (int) $editingProduct[
  291. "id"
  292. ]; ?>">
  293. <?php endif; ?>
  294. <div class="form-group">
  295. <label for="name">Name *</label>
  296. <input type="text" id="name" name="name" required value="<?php echo escape(
  297. $currentProduct["name"],
  298. ); ?>">
  299. </div>
  300. <div class="form-group">
  301. <label for="description">Beschreibung</label>
  302. <textarea id="description" name="description" rows="4"><?php echo escape(
  303. $currentProduct["description"],
  304. ); ?></textarea>
  305. </div>
  306. <div class="form-group">
  307. <label for="categories">Kategorien *</label>
  308. <select id="categories" name="categories[]" multiple size="<?php echo max(
  309. 3,
  310. min(8, count($categories)),
  311. ); ?>" required>
  312. <?php foreach ($categories as $category): ?>
  313. <option value="<?php echo escape(
  314. $category["id"],
  315. ); ?>" <?php echo in_array(
  316. $category["id"],
  317. getProductCategoryIds($currentProduct),
  318. true,
  319. )
  320. ? "selected"
  321. : ""; ?>>
  322. <?php echo escape($category["label"]); ?>
  323. </option>
  324. <?php endforeach; ?>
  325. </select>
  326. </div>
  327. <div class="form-group">
  328. <label for="sizes">Größen (kommagetrennt) *</label>
  329. <input type="text" id="sizes" name="sizes" required value="<?php echo escape(
  330. $currentProduct["sizes"],
  331. ); ?>" placeholder="Standard" oninput="updateAvailabilityFields()">
  332. <small>Für Artikel ohne Varianten z. B. <code>Standard</code> oder <code>Einheitsgröße</code>.</small>
  333. </div>
  334. <div id="availability-group">
  335. <?php foreach ($currentSizes as $size): ?>
  336. <div class="form-group">
  337. <label>Lieferhinweis für Größe "<?php echo escape(
  338. $size,
  339. ); ?>"</label>
  340. <textarea name="availability_<?php echo escape(
  341. str_replace([" ", ","], "_", $size),
  342. ); ?>" rows="2" placeholder="Optionaler Hinweis"><?php echo escape(
  343. $currentProduct["availability_labels"][$size] ?? "",
  344. ); ?></textarea>
  345. </div>
  346. <?php endforeach; ?>
  347. </div>
  348. <div class="form-group">
  349. <label for="image">Bilddateiname</label>
  350. <input type="text" id="image" name="image" value="<?php echo escape(
  351. $currentProduct["image"],
  352. ); ?>">
  353. </div>
  354. <div class="form-group">
  355. <label for="image_file">Oder Bild hochladen</label>
  356. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  357. </div>
  358. <button type="submit" name="<?php echo $editingProduct
  359. ? "update_product"
  360. : "add_product"; ?>" class="btn">
  361. <?php echo $editingProduct
  362. ? "Produkt aktualisieren"
  363. : "Produkt anlegen"; ?>
  364. </button>
  365. <?php if ($editingProduct): ?>
  366. <a href="products.php" class="btn btn-secondary">Abbrechen</a>
  367. <?php endif; ?>
  368. </form>
  369. </div>
  370. <script>
  371. function updateAvailabilityFields() {
  372. const sizesInput = document.getElementById('sizes');
  373. const group = document.getElementById('availability-group');
  374. const currentValues = {};
  375. group.querySelectorAll('textarea').forEach((textarea) => {
  376. currentValues[textarea.name] = textarea.value;
  377. });
  378. const sizes = sizesInput.value
  379. .split(',')
  380. .map((size) => size.trim())
  381. .filter((size, index, all) => size && all.indexOf(size) === index);
  382. const finalSizes = sizes.length > 0 ? sizes : ['Standard'];
  383. let html = '';
  384. finalSizes.forEach((size) => {
  385. const safeName = size.replace(/[ ,]/g, '_');
  386. const fieldName = 'availability_' + safeName;
  387. const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '';
  388. html += '<div class="form-group">';
  389. html += '<label>Lieferhinweis für Größe "' + size.replace(/"/g, '&quot;') + '"</label>';
  390. html += '<textarea name="' + fieldName + '" rows="2" placeholder="Optionaler Hinweis">' + currentValue.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
  391. html += '</div>';
  392. });
  393. group.innerHTML = html;
  394. }
  395. </script>
  396. <h3>Alle Produkte</h3>
  397. <?php if (empty($products)): ?>
  398. <p>Keine Produkte vorhanden.</p>
  399. <?php else: ?>
  400. <div class="table-responsive">
  401. <table class="responsive-table">
  402. <thead>
  403. <tr>
  404. <th>ID</th>
  405. <th>Name</th>
  406. <th>Kategorien</th>
  407. <th>Größen</th>
  408. <th>Lieferhinweise</th>
  409. <th>Aktionen</th>
  410. </tr>
  411. </thead>
  412. <tbody>
  413. <?php foreach ($products as $product): ?>
  414. <tr>
  415. <td data-label="ID"><?php echo (int) $product[
  416. "id"
  417. ]; ?></td>
  418. <td data-label="Name"><?php echo escape(
  419. $product["name"],
  420. ); ?></td>
  421. <td data-label="Kategorien"><?php echo escape(
  422. implode(
  423. ", ",
  424. getCategoryLabels(
  425. getProductCategoryIds($product),
  426. ),
  427. ),
  428. ); ?></td>
  429. <td data-label="Größen"><?php echo escape(
  430. implode(", ", getProductSizes($product)),
  431. ); ?></td>
  432. <td data-label="Lieferhinweise">
  433. <?php
  434. $labels = [];
  435. foreach (
  436. $product["availability_labels"] ?? []
  437. as $size => $label
  438. ) {
  439. if (trim((string) $label) !== "") {
  440. $labels[] = $size . ": " . $label;
  441. }
  442. }
  443. echo empty($labels)
  444. ? "Keine"
  445. : escape(implode(" | ", $labels));
  446. ?>
  447. </td>
  448. <td data-label="Aktionen">
  449. <a href="?edit=<?php echo (int) $product[
  450. "id"
  451. ]; ?>" class="btn btn-small">Bearbeiten</a>
  452. <form method="POST" class="inline-form" onsubmit="return confirm('Produkt wirklich löschen?');">
  453. <?php echo csrfField(); ?>
  454. <input type="hidden" name="product_id" value="<?php echo (int) $product[
  455. "id"
  456. ]; ?>">
  457. <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
  458. </form>
  459. </td>
  460. </tr>
  461. <?php endforeach; ?>
  462. </tbody>
  463. </table>
  464. </div>
  465. <?php endif; ?>
  466. <?php include __DIR__ . "/../includes/footer.php"; ?>