waterTestSubmit.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * controllers/waterTestSubmit.php
  4. *
  5. * POST handler for water test analysis entry.
  6. * Inserts a new record into water_records.
  7. */
  8. if (session_status() === PHP_SESSION_NONE) {
  9. session_start();
  10. }
  11. require_once __DIR__ . '/../config/database.php';
  12. require_once __DIR__ . '/../lib/auth.php';
  13. require_once __DIR__ . '/../lib/csrf.php';
  14. requireLogin();
  15. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  16. header('Location: /dashboard/crop-analysis/water-test-data/water-test-data.php');
  17. exit;
  18. }
  19. if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
  20. $_SESSION['flash_error'] = 'Invalid CSRF token. Please try again.';
  21. header('Location: /dashboard/crop-analysis/water-test-data/water-test-data.php');
  22. exit;
  23. }
  24. $pdo = getDBConnection();
  25. $userId = getCurrentUserId();
  26. $clientId = (int) ($_POST['client_id'] ?? 0);
  27. if ($clientId > 0) {
  28. $stmt = $pdo->prepare('SELECT id FROM client_records WHERE id = ? AND modx_user_id = ?');
  29. $stmt->execute([$clientId, $userId]);
  30. if (!$stmt->fetch()) {
  31. $clientId = 0;
  32. }
  33. }
  34. $rand = mt_rand(10000, 99999);
  35. $fields = [
  36. 'lab_no', 'batch_no', 'date_sampled', 'sample_id', 'site_id',
  37. 'ph', 'cond_dsm', 'hco3',
  38. 'n', 'p', 'k', 's', 'mg', 'ca',
  39. 'na', 'fe', 'mn', 'zn', 'cu', 'b',
  40. 'm', 'co', 'se', 'ch',
  41. ];
  42. $colList = 'modx_user_id, client_records_id, rand, ' . implode(', ', array_map(fn($c) => "`$c`", $fields));
  43. $placeholders = implode(', ', array_fill(0, count($fields) + 3, '?'));
  44. $values = [$userId, $clientId ?: null, $rand];
  45. foreach ($fields as $field) {
  46. $val = trim((string) ($_POST[$field] ?? ''));
  47. $values[] = ($val === '') ? null : $val;
  48. }
  49. try {
  50. $stmt = $pdo->prepare("INSERT INTO water_records ($colList) VALUES ($placeholders)");
  51. $stmt->execute($values);
  52. $newId = (int) $pdo->lastInsertId();
  53. $_SESSION['flash_success'] = 'Water test record saved successfully.';
  54. header("Location: /dashboard/inbox.php");
  55. } catch (\PDOException $e) {
  56. $_SESSION['flash_error'] = 'Failed to save record. Please try again.';
  57. header('Location: /dashboard/crop-analysis/water-test-data/water-test-data.php');
  58. }
  59. exit;