newProductSubmit.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * controllers/newProductSubmit.php
  4. *
  5. * POST handler: inserts a new product into fertiliser_specifications.
  6. */
  7. if (session_status() === PHP_SESSION_NONE) {
  8. session_start();
  9. }
  10. require_once __DIR__ . '/../config/database.php';
  11. require_once __DIR__ . '/../lib/auth.php';
  12. require_once __DIR__ . '/../lib/csrf.php';
  13. requireLogin();
  14. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  15. header('Location: /dashboard/client-settings/product-list.php');
  16. exit;
  17. }
  18. if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
  19. $_SESSION['flash_error'] = 'Invalid CSRF token. Please try again.';
  20. header('Location: /dashboard/client-settings/product-list.php');
  21. exit;
  22. }
  23. $name = trim($_POST['name'] ?? '');
  24. $chemical = trim($_POST['chemical'] ?? '');
  25. if ($name === '') {
  26. $_SESSION['flash_error'] = 'Product name is required.';
  27. header('Location: /dashboard/client-settings/product-list.php');
  28. exit;
  29. }
  30. $pdo = getDBConnection();
  31. $userId = getCurrentUserId();
  32. $nutrients = ['N', 'P', 'K', 'Na', 'Ca', 'Mg', 'B', 'Zn', 'Cu', 'Mn', 'Fe', 'Co', 'Mo'];
  33. $colList = 'modx_user_id, name, chemical, ' . implode(', ', array_map(fn($c) => "`$c`", $nutrients));
  34. $placeholders = implode(', ', array_fill(0, count($nutrients) + 3, '?'));
  35. $values = [$userId, $name, $chemical];
  36. foreach ($nutrients as $col) {
  37. $val = trim((string) ($_POST[$col] ?? '0'));
  38. $values[] = is_numeric($val) ? $val : '0';
  39. }
  40. try {
  41. $stmt = $pdo->prepare("INSERT INTO fertiliser_specifications ($colList) VALUES ($placeholders)");
  42. $stmt->execute($values);
  43. $_SESSION['flash_success'] = 'Product "' . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . '" added successfully.';
  44. } catch (\PDOException $e) {
  45. $_SESSION['flash_error'] = 'Failed to add product. Please try again.';
  46. }
  47. header('Location: /dashboard/client-settings/product-list.php');
  48. exit;