animal-report-save.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * animal-report-save.php
  4. *
  5. * AJAX endpoint: auto-saves animal dietary report consultant notes to the reports table.
  6. * Called by the auto-save JS in animal-report.php via POST.
  7. *
  8. * GET params: rid (animal_records.id), rand (animal_records.rand)
  9. * POST params: general_details, ai_interpretation, recommended_details, foliar_details
  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. $check = $pdo->prepare(
  32. 'SELECT id FROM animal_records WHERE id = ? AND rand = ? AND modx_user_id = ? LIMIT 1'
  33. );
  34. $check->execute([$recordId, $randId, $userId]);
  35. if (!$check->fetch()) {
  36. http_response_code(403);
  37. echo json_encode(['success' => false, 'message' => 'Record not found or access denied']);
  38. exit;
  39. }
  40. $data = [
  41. 'general_details' => trim($_POST['general_details'] ?? ''),
  42. 'ai_interpretation' => trim($_POST['ai_interpretation'] ?? ''),
  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, $randId, $comment]);
  53. echo json_encode(['success' => true, 'saved' => date('H:i:s')]);