updatecomment.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * dashboard/crop-analysis/updatecomment.php
  4. *
  5. * AJAX endpoint: auto-saves soil report comments to the reports table.
  6. * Called by the auto-save JS in soil-report-pdf.php via POST.
  7. *
  8. * POST params: overview, foliar_Details, microbe_Program, header1
  9. * GET params: rid (soil_records.id), rand (soil_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 soil record belongs to this user (ownership check)
  32. $check = $pdo->prepare(
  33. 'SELECT id FROM soil_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. // Collect and sanitise comment fields
  42. $data = [
  43. 'overview' => trim($_POST['overview'] ?? ''),
  44. 'ai_interpretation' => trim($_POST['ai_interpretation'] ?? ''),
  45. 'foliar_details' => trim($_POST['foliar_Details'] ?? ''),
  46. 'microbe_program' => trim($_POST['microbe_Program'] ?? ''),
  47. 'header1' => trim($_POST['header1'] ?? 'Foliar Program'),
  48. ];
  49. $comment = json_encode($data, JSON_UNESCAPED_UNICODE);
  50. // Upsert: update if record exists for this soil record + user, else insert
  51. $stmt = $pdo->prepare('
  52. INSERT INTO reports (modx_user_id, record_id, rand, comment, dateTime)
  53. VALUES (?, ?, ?, ?, CURDATE())
  54. ON DUPLICATE KEY UPDATE comment = VALUES(comment), dateTime = CURDATE()
  55. ');
  56. $stmt->execute([$userId, $recordId, (int) $randId, $comment]);
  57. echo json_encode(['success' => true, 'saved' => date('H:i:s')]);