plant-report-save.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 = trim( $_GET['rand'] ?? '');
  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. 'ai_interpretation' => trim($_POST['ai_interpretation'] ?? ''),
  44. 'recommended_details' => trim($_POST['recommended_details'] ?? ''),
  45. 'foliar_details' => trim($_POST['foliar_details'] ?? ''),
  46. ];
  47. $comment = json_encode($data, JSON_UNESCAPED_UNICODE);
  48. $stmt = $pdo->prepare('
  49. INSERT INTO reports (modx_user_id, record_id, rand, comment, dateTime)
  50. VALUES (?, ?, ?, ?, CURDATE())
  51. ON DUPLICATE KEY UPDATE comment = VALUES(comment), dateTime = CURDATE()
  52. ');
  53. $stmt->execute([$userId, $recordId, $randId, $comment]);
  54. echo json_encode(['success' => true, 'saved' => date('H:i:s')]);