animal-report.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. /**
  3. * dashboard/crop-analysis/animal-dietary-balance/animal-report.php
  4. *
  5. * Animal dietary balance report — editable sections with auto-save and Ollama AI interpretation.
  6. */
  7. require_once __DIR__ . '/../../../config/database.php';
  8. require_once __DIR__ . '/../../../lib/auth.php';
  9. require_once __DIR__ . '/../../../lib/csrf.php';
  10. require_once __DIR__ . '/../../../vendor/autoload.php';
  11. requireLogin();
  12. $recordId = (int) ($_GET['rid'] ?? 0);
  13. $randId = trim( $_GET['rand'] ?? '');
  14. $clientId = (int) ($_GET['cid'] ?? 0);
  15. if (!$recordId || $randId === '') {
  16. http_response_code(400);
  17. die('Invalid request parameters');
  18. }
  19. try {
  20. $pdo = getDBConnection();
  21. $userId = getCurrentUserId();
  22. $stmt = $pdo->prepare('SELECT * FROM animal_records WHERE id = ? AND rand = ?');
  23. $stmt->execute([$recordId, $randId]);
  24. $row = $stmt->fetch(PDO::FETCH_ASSOC);
  25. if (!$row) {
  26. http_response_code(404);
  27. die('Animal record not found');
  28. }
  29. // Load saved report comments
  30. $savedComments = [
  31. 'general_details' => '',
  32. 'ai_interpretation' => '',
  33. 'recommended_details' => '',
  34. 'foliar_details' => '',
  35. ];
  36. $stmtRpt = $pdo->prepare(
  37. 'SELECT comment FROM reports WHERE record_id = ? AND modx_user_id = ? ORDER BY id DESC LIMIT 1'
  38. );
  39. $stmtRpt->execute([$recordId, $userId]);
  40. $savedRow = $stmtRpt->fetchColumn();
  41. if ($savedRow) {
  42. $decoded = json_decode($savedRow, true);
  43. if (is_array($decoded)) {
  44. $savedComments = array_merge($savedComments, $decoded);
  45. }
  46. }
  47. } catch (PDOException $e) {
  48. error_log('DB error in animal-report.php: ' . $e->getMessage());
  49. die('Database error occurred');
  50. }
  51. $h = fn($v) => htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
  52. $today = date('jS F Y');
  53. $pageTitle = 'Animal Dietary Report' . (!empty($row['client_name']) ? ' — ' . $row['client_name'] : '');
  54. $siteName = 'Crop Monitor';
  55. function formatReportText(string $text): string
  56. {
  57. if (trim($text) === '') {
  58. return '<p class="text-muted fst-italic">No content saved.</p>';
  59. }
  60. $parsedown = new Parsedown();
  61. $parsedown->setSafeMode(true);
  62. return $parsedown->text($text);
  63. }
  64. include __DIR__ . '/../../../layouts/header.php';
  65. ?>
  66. <link rel="stylesheet" href="/client-assets/home/css/graphPrint.css" media="print">
  67. <style>
  68. @media print {
  69. .report-textarea { display: none; }
  70. .report-print-preview { display: block !important; }
  71. }
  72. .report-print-preview { display: none; }
  73. .report-textarea { overflow: hidden; resize: none; overflow-y: auto; }
  74. </style>
  75. <div class="container-fluid px-4" id="content">
  76. <!-- ── Page heading ─────────────────────────────────────────── -->
  77. <div class="d-flex align-items-center justify-content-between mt-4 mb-3">
  78. <h1 class="h3 mb-0">Animal Dietary Balance Report</h1>
  79. <div class="d-flex gap-2 d-print-none">
  80. <a href="/dashboard/crop-analysis/animal-dietary-balance/animal-dietary-balance.php?rid=<?= $recordId ?>&rand=<?= urlencode($randId) ?>&cid=<?= $clientId ?>"
  81. class="btn btn-outline-secondary btn-sm">
  82. &larr; Analysis
  83. </a>
  84. <a href="/dashboard/crop-analysis/animal-dietary-balance/animal-report-pdf.php?rid=<?= $recordId ?>&rand=<?= urlencode($randId) ?>&cid=<?= $clientId ?>"
  85. class="btn btn-outline-success btn-sm" target="_blank">
  86. <i class="fas fa-file-pdf me-1"></i>PDF — Report
  87. </a>
  88. <a href="/pdf-files/headlessChrome_pdf.php?type=animal&rid=<?= $recordId ?>&rand=<?= urlencode($randId) ?>&cid=<?= $clientId ?>"
  89. class="btn btn-success btn-sm">
  90. <i class="fas fa-file-pdf me-1"></i>PDF — Analysis &amp; Report
  91. </a>
  92. <button type="button" class="btn btn-primary btn-sm" id="btn-generate-all">
  93. <i class="fas fa-robot me-1"></i>Interpret All with AI
  94. </button>
  95. </div>
  96. </div>
  97. <!-- ── Client info card ──────────────────────────────────────── -->
  98. <div class="card mb-4">
  99. <div class="card-body py-2">
  100. <div class="row row-cols-2 row-cols-md-3 g-1 small">
  101. <div><strong>Client:</strong> <?= $h($row['client_name']) ?></div>
  102. <div><strong>Sample ID:</strong> <?= $h($row['sample_id']) ?></div>
  103. <div><strong>Date Sampled:</strong> <?= $h($row['date_sampled']) ?></div>
  104. <div><strong>Analysis Type:</strong> <?= $h($row['analysis_type'] ?? '') ?></div>
  105. <div><strong>Lab No:</strong> <?= $h($row['lab_no']) ?></div>
  106. <div><strong>Site ID:</strong> <?= $h($row['site_id']) ?></div>
  107. <div><strong>Report Date:</strong> <?= $h($today) ?></div>
  108. </div>
  109. </div>
  110. </div>
  111. <div id="save-status" class="text-muted small mb-2" style="min-height:1.2rem;"></div>
  112. <form class="report-form" method="post">
  113. <input type="hidden" name="csrf_token"
  114. value="<?= htmlspecialchars(generateCsrfToken(), ENT_QUOTES, 'UTF-8') ?>">
  115. <input type="hidden" name="rid" value="<?= $recordId ?>">
  116. <input type="hidden" name="rand" value="<?= $h($randId) ?>">
  117. <!-- ── 1. General Comment ─────────────────────────────────── -->
  118. <div class="card mb-4">
  119. <div class="card-header d-flex justify-content-between align-items-center fw-bold">
  120. <span>General Comment</span>
  121. <div class="d-flex d-print-none">
  122. <button type="button" class="btn btn-outline-primary btn-sm ai-generate-btn"
  123. data-section="general" data-target="#general_details">
  124. <i class="fas fa-robot me-1"></i>Generate with AI
  125. </button>
  126. </div>
  127. </div>
  128. <div class="card-body">
  129. <textarea id="general_details" name="general_details"
  130. class="form-control report-textarea" rows="6"
  131. placeholder="Enter a general comment on this dietary balance analysis..."
  132. ><?= $h($savedComments['general_details']) ?></textarea>
  133. <div class="report-print-preview"><?= formatReportText($savedComments['general_details']) ?></div>
  134. </div>
  135. </div>
  136. <!-- ── 2. AI Interpretation ───────────────────────────────── -->
  137. <div class="card mb-4">
  138. <div class="card-header d-flex justify-content-between align-items-center fw-bold">
  139. <span>AI Dietary Interpretation</span>
  140. <div class="d-flex d-print-none">
  141. <button type="button" class="btn btn-outline-primary btn-sm ai-generate-btn"
  142. data-section="ai_interpretation" data-target="#ai_interpretation">
  143. <i class="fas fa-robot me-1"></i>Interpret with AI
  144. </button>
  145. </div>
  146. </div>
  147. <div class="card-body">
  148. <p class="text-muted small mb-2">
  149. AI-generated agronomic interpretation. Review and edit before including in the final report.
  150. </p>
  151. <textarea id="ai_interpretation" name="ai_interpretation"
  152. class="form-control report-textarea" rows="10"
  153. placeholder="Click 'Interpret with AI' to generate an interpretation, or type manually..."
  154. ><?= $h($savedComments['ai_interpretation']) ?></textarea>
  155. <div class="report-print-preview"><?= formatReportText($savedComments['ai_interpretation']) ?></div>
  156. </div>
  157. </div>
  158. <!-- ── 3. Recommended Supplementation Program ───────────────────── -->
  159. <div class="card mb-4">
  160. <div class="card-header d-flex justify-content-between align-items-center fw-bold">
  161. <span>Recommended Supplementation Program</span>
  162. <div class="d-flex d-print-none">
  163. <button type="button" class="btn btn-outline-primary btn-sm ai-generate-btn"
  164. data-section="recommended" data-target="#recommended_details">
  165. <i class="fas fa-robot me-1"></i>Generate with AI
  166. </button>
  167. </div>
  168. </div>
  169. <div class="card-body">
  170. <textarea id="recommended_details" name="recommended_details"
  171. class="form-control report-textarea" rows="6"
  172. placeholder="Enter recommended supplementation program details..."
  173. ><?= $h($savedComments['recommended_details']) ?></textarea>
  174. <div class="report-print-preview"><?= formatReportText($savedComments['recommended_details']) ?></div>
  175. </div>
  176. </div>
  177. <!-- ── 4. Ongoing Management Program ──────────────────────────────────────── -->
  178. <div class="card mb-4">
  179. <div class="card-header d-flex justify-content-between align-items-center fw-bold">
  180. <span>Ongoing Management Program</span>
  181. <div class="d-flex d-print-none">
  182. <button type="button" class="btn btn-outline-primary btn-sm ai-generate-btn"
  183. data-section="foliar" data-target="#foliar_details">
  184. <i class="fas fa-robot me-1"></i>Generate with AI
  185. </button>
  186. </div>
  187. </div>
  188. <div class="card-body">
  189. <textarea id="foliar_details" name="foliar_details"
  190. class="form-control report-textarea" rows="6"
  191. placeholder="Enter ongoing management and monitoring program details..."
  192. ><?= $h($savedComments['foliar_details']) ?></textarea>
  193. <div class="report-print-preview"><?= formatReportText($savedComments['foliar_details']) ?></div>
  194. </div>
  195. </div>
  196. <!-- ── Disclaimer ─────────────────────────────────────────── -->
  197. <div class="card mb-4 border-0 bg-light">
  198. <div class="card-body">
  199. <p class="text-muted mb-0 fst-italic" style="font-size:0.75rem;">
  200. Any recommendations provided by Crop Monitor are advice only. We are not paid consultants
  201. and accept no responsibility for any of our suggestions.
  202. </p>
  203. </div>
  204. </div>
  205. </form>
  206. </div><!-- /.container-fluid -->
  207. <script>
  208. (function () {
  209. 'use strict';
  210. var saveTimer = null;
  211. var statusEl = document.getElementById('save-status');
  212. var SAVE_URL = '/dashboard/crop-analysis/animal-dietary-balance/animal-report-save.php'
  213. + '?rid=<?= $recordId ?>&rand=<?= urlencode($randId) ?>';
  214. var AI_URL = '/controllers/ollamaGenerate.php';
  215. var CSRF_TOKEN = <?= json_encode(generateCsrfToken()) ?>;
  216. function setStatus(msg, cls) {
  217. statusEl.textContent = msg;
  218. statusEl.className = 'small mb-2 text-' + (cls || 'secondary');
  219. }
  220. function autoResize(el) {
  221. el.style.height = 'auto';
  222. el.style.height = el.scrollHeight + 'px';
  223. }
  224. document.querySelectorAll('.report-textarea').forEach(function (el) {
  225. setTimeout(function () { autoResize(el); }, 0);
  226. el.addEventListener('input', function () {
  227. autoResize(el);
  228. clearTimeout(saveTimer);
  229. saveTimer = setTimeout(saveReport, 1200);
  230. });
  231. });
  232. function saveReport() {
  233. var form = document.querySelector('.report-form');
  234. var data = new URLSearchParams(new FormData(form));
  235. setStatus('Saving…', 'secondary');
  236. fetch(SAVE_URL, { method: 'POST', body: data })
  237. .then(function (r) { return r.json(); })
  238. .then(function (d) {
  239. if (d.success) {
  240. setStatus('Saved — ' + new Date().toLocaleTimeString(), 'success');
  241. } else {
  242. setStatus('Save failed: ' + (d.message || 'unknown error'), 'danger');
  243. }
  244. })
  245. .catch(function () { setStatus('Network error — not saved', 'danger'); });
  246. }
  247. document.querySelector('.report-form').addEventListener('submit', function (e) {
  248. e.preventDefault();
  249. saveReport();
  250. });
  251. function generateSection(btn, section, targetSelector) {
  252. var textarea = document.querySelector(targetSelector);
  253. if (!textarea) return;
  254. var origHTML = btn.innerHTML;
  255. btn.disabled = true;
  256. btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Generating…';
  257. setStatus('Requesting AI interpretation…', 'secondary');
  258. fetch(AI_URL, {
  259. method: 'POST',
  260. headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  261. body: new URLSearchParams({
  262. csrf_token: CSRF_TOKEN,
  263. rid: <?= $recordId ?>,
  264. rand: <?= json_encode($randId) ?>,
  265. section: section,
  266. record_type: 'animal',
  267. }),
  268. })
  269. .then(function (r) { return r.json(); })
  270. .then(function (d) {
  271. if (d.success && d.text) {
  272. textarea.value = d.text;
  273. textarea.dispatchEvent(new Event('input'));
  274. setStatus('AI text generated — review before publishing', 'success');
  275. } else {
  276. setStatus('AI error: ' + (d.error || 'no response returned'), 'danger');
  277. }
  278. })
  279. .catch(function () {
  280. setStatus('Could not reach AI service. Is Ollama running on port 11434?', 'danger');
  281. })
  282. .finally(function () {
  283. btn.disabled = false;
  284. btn.innerHTML = origHTML;
  285. });
  286. }
  287. document.querySelectorAll('.ai-generate-btn').forEach(function (btn) {
  288. btn.addEventListener('click', function () {
  289. generateSection(btn, btn.dataset.section, btn.dataset.target);
  290. });
  291. });
  292. document.getElementById('btn-generate-all').addEventListener('click', function () {
  293. var sections = [
  294. { section: 'general', target: '#general_details' },
  295. { section: 'ai_interpretation', target: '#ai_interpretation' },
  296. { section: 'recommended', target: '#recommended_details' },
  297. { section: 'foliar', target: '#foliar_details' },
  298. ];
  299. sections.forEach(function (s, i) {
  300. setTimeout(function () {
  301. var sectionBtn = document.querySelector('.ai-generate-btn[data-section="' + s.section + '"]');
  302. generateSection(
  303. sectionBtn || document.getElementById('btn-generate-all'),
  304. s.section, s.target
  305. );
  306. }, i * 4000);
  307. });
  308. });
  309. })();
  310. </script>
  311. <?php include __DIR__ . '/../../../layouts/footer.php'; ?>