products.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. </div>
  354. <div class="form-group">
  355. <label for="sizes">Größen (kommagetrennt) *</label>
  356. <input type="text" id="sizes" name="sizes" required value="<?php echo escape(
  357. $currentProduct["sizes"],
  358. ); ?>" placeholder="Standard" oninput="updateAvailabilityFields()">
  359. <small>Für Artikel ohne Varianten z. B. <code>Standard</code> oder <code>Einheitsgröße</code>.</small>
  360. </div>
  361. <div id="availability-group">
  362. <?php foreach ($currentSizes as $size): ?>
  363. <div class="form-group">
  364. <label>Lieferhinweis für Größe "<?php echo escape(
  365. $size,
  366. ); ?>"</label>
  367. <textarea name="availability_<?php echo escape(
  368. str_replace([" ", ","], "_", $size),
  369. ); ?>" rows="2" placeholder="Optionaler Hinweis"><?php echo escape(
  370. $currentProduct["availability_labels"][$size] ?? "",
  371. ); ?></textarea>
  372. </div>
  373. <?php endforeach; ?>
  374. </div>
  375. <div class="form-group">
  376. <label for="image">Bilddateiname</label>
  377. <input type="text" id="image" name="image" value="<?php echo escape(
  378. $currentProduct["image"],
  379. ); ?>">
  380. </div>
  381. <div class="form-group">
  382. <label for="image_file">Oder Bild hochladen</label>
  383. <input type="file" id="image_file" name="image_file" accept=".jpg,.jpeg,.png,.webp,.gif,image/*">
  384. </div>
  385. <button type="submit" name="<?php echo $editingProduct
  386. ? "update_product"
  387. : "add_product"; ?>" class="btn">
  388. <?php echo $editingProduct
  389. ? "Produkt aktualisieren"
  390. : "Produkt anlegen"; ?>
  391. </button>
  392. <?php if ($editingProduct): ?>
  393. <a href="products.php" class="btn btn-secondary">Abbrechen</a>
  394. <?php endif; ?>
  395. </form>
  396. </div>
  397. <script>
  398. function updateAvailabilityFields() {
  399. const sizesInput = document.getElementById('sizes');
  400. const group = document.getElementById('availability-group');
  401. const currentValues = {};
  402. group.querySelectorAll('textarea').forEach((textarea) => {
  403. currentValues[textarea.name] = textarea.value;
  404. });
  405. const sizes = sizesInput.value
  406. .split(',')
  407. .map((size) => size.trim())
  408. .filter((size, index, all) => size && all.indexOf(size) === index);
  409. const finalSizes = sizes.length > 0 ? sizes : ['Standard'];
  410. let html = '';
  411. finalSizes.forEach((size) => {
  412. const safeName = size.replace(/[ ,]/g, '_');
  413. const fieldName = 'availability_' + safeName;
  414. const currentValue = Object.prototype.hasOwnProperty.call(currentValues, fieldName) ? currentValues[fieldName] : '';
  415. html += '<div class="form-group">';
  416. html += '<label>Lieferhinweis für Größe "' + size.replace(/"/g, '&quot;') + '"</label>';
  417. html += '<textarea name="' + fieldName + '" rows="2" placeholder="Optionaler Hinweis">' + currentValue.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</textarea>';
  418. html += '</div>';
  419. });
  420. group.innerHTML = html;
  421. }
  422. </script>
  423. <h3>Alle Produkte</h3>
  424. <?php if (empty($products)): ?>
  425. <p>Keine Produkte vorhanden.</p>
  426. <?php else: ?>
  427. <div class="table-responsive">
  428. <table class="responsive-table">
  429. <thead>
  430. <tr>
  431. <th class="product-id-column">ID</th>
  432. <th>Name</th>
  433. <th>Kategorien</th>
  434. <th>Größen</th>
  435. <th>Lieferhinweise</th>
  436. <th>Aktionen</th>
  437. </tr>
  438. </thead>
  439. <tbody>
  440. <?php foreach ($products as $product): ?>
  441. <tr>
  442. <td data-label="ID" class="product-id-column"><?php echo (int) $product[
  443. "id"
  444. ]; ?></td>
  445. <td data-label="Name"><?php echo escape(
  446. $product["name"],
  447. ); ?></td>
  448. <td data-label="Kategorien"><?php echo escape(
  449. implode(
  450. ", ",
  451. getCategoryLabels(
  452. getProductCategoryIds($product),
  453. ),
  454. ),
  455. ); ?></td>
  456. <td data-label="Größen"><?php echo escape(
  457. implode(", ", getProductSizes($product)),
  458. ); ?></td>
  459. <td data-label="Lieferhinweise">
  460. <?php
  461. $labels = [];
  462. foreach (
  463. $product["availability_labels"] ?? []
  464. as $size => $label
  465. ) {
  466. if (trim((string) $label) !== "") {
  467. $labels[] = $size . ": " . $label;
  468. }
  469. }
  470. echo empty($labels)
  471. ? "Keine"
  472. : escape(implode(" | ", $labels));
  473. ?>
  474. </td>
  475. <td data-label="Aktionen">
  476. <a href="?edit=<?php echo (int) $product[
  477. "id"
  478. ]; ?>" class="btn btn-small">Bearbeiten</a>
  479. <form method="POST" class="inline-form" onsubmit="return confirm('Produkt wirklich löschen?');">
  480. <?php echo csrfField(); ?>
  481. <input type="hidden" name="product_id" value="<?php echo (int) $product[
  482. "id"
  483. ]; ?>">
  484. <button type="submit" name="delete_product" class="btn btn-secondary btn-small">Löschen</button>
  485. </form>
  486. </td>
  487. </tr>
  488. <?php endforeach; ?>
  489. </tbody>
  490. </table>
  491. </div>
  492. <?php endif; ?>
  493. <?php include __DIR__ . "/../includes/footer.php"; ?>