plant-report-save.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * plant-report-save.php
  4. *
  5. * AJAX endpoint: auto-saves plant report consultant notes to the reports table.
  6. * Called by the auto-save JS in plant-report.php via POST.
  7. *
  8. * POST params: general_details, recommended_details, foliar_details
  9. * GET params: rid (plant_records.id), rand (plant_records.rand)
  10. */
  11. if (session_status() === PHP_SESSION_NONE) {
  12. session_start();
  13. }
  14. require_once __DIR__ . '/../../../config/database.php';
  15. require_once __DIR__ . '/../../../lib/auth.php';
  16. if (!isLoggedIn()) {
  17. http_response_code(403);
  18. echo json_encode(['success' => false, 'message' => 'Unauthorised']);
  19. exit;
  20. }
  21. header('Content-Type: application/json');
  22. $pdo = getDBConnection();
  23. $userId = getCurrentUserId();
  24. $recordId = (int) ($_GET['rid'] ?? 0);
  25. $randId = (float) ($_GET['rand'] ?? 0);
  26. if ($recordId <= 0) {
  27. http_response_code(400);
  28. echo json_encode(['success' => false, 'message' => 'Missing record ID']);
  29. exit;
  30. }
  31. // Verify the plant record belongs to this user
  32. $check = $pdo->prepare(
  33. 'SELECT id FROM plant_records WHERE id = ? AND rand = ? AND modx_user_id = ? LIMIT 1'
  34. );
  35. $check->execute([$recordId, $randId, $userId]);
  36. if (!$check->fetch()) {
  37. http_response_code(403);
  38. echo json_encode(['success' => false, 'message' => 'Record not found or access denied']);
  39. exit;
  40. }
  41. $data = [
  42. 'general_details' => trim($_POST['general_details'] ?? ''),
  43. 'recommended_details' => trim($_POST['recommended_details'] ?? ''),
  44. 'foliar_details' => trim($_POST['foliar_details'] ?? ''),
  45. ];
  46. $comment = json_encode($data, JSON_UNESCAPED_UNICODE);
  47. $stmt = $pdo->prepare('
  48. INSERT INTO reports (modx_user_id, record_id, rand, comment, dateTime)
  49. VALUES (?, ?, ?, ?, CURDATE())
  50. ON DUPLICATE KEY UPDATE comment = VALUES(comment), dateTime = CURDATE()
  51. ');
  52. $stmt->execute([$userId, $recordId, (int) $randId, $comment]);
  53. echo json_encode(['success' => true, 'saved' => date('H:i:s')]);