<?php
/**
 * dashboard/crop-analysis/updatecomment.php
 *
 * AJAX endpoint: auto-saves soil report comments to the reports table.
 * Called by the auto-save JS in soil-report-pdf.php via POST.
 *
 * POST params: overview, foliar_Details, microbe_Program, header1
 * GET params:  rid (soil_records.id), rand (soil_records.rand)
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../lib/auth.php';

if (!isLoggedIn()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorised']);
    exit;
}

header('Content-Type: application/json');

$pdo    = getDBConnection();
$userId = getCurrentUserId();

$recordId = (int)   ($_GET['rid']  ?? 0);
$randId   = (float) ($_GET['rand'] ?? 0);

if ($recordId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing record ID']);
    exit;
}

// Verify the soil record belongs to this user (ownership check)
$check = $pdo->prepare(
    'SELECT id FROM soil_records WHERE id = ? AND rand = ? AND modx_user_id = ? LIMIT 1'
);
$check->execute([$recordId, $randId, $userId]);
if (!$check->fetch()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Record not found or access denied']);
    exit;
}

// Collect and sanitise comment fields
$data = [
    'overview'           => trim($_POST['overview']           ?? ''),
    'ai_interpretation'  => trim($_POST['ai_interpretation']  ?? ''),
    'foliar_details'     => trim($_POST['foliar_Details']      ?? ''),
    'microbe_program'    => trim($_POST['microbe_Program']     ?? ''),
    'header1'            => trim($_POST['header1']             ?? 'Foliar Program'),
];

$comment = json_encode($data, JSON_UNESCAPED_UNICODE);

// Upsert: update if record exists for this soil record + user, else insert
$stmt = $pdo->prepare('
    INSERT INTO reports (modx_user_id, record_id, rand, comment, dateTime)
    VALUES (?, ?, ?, ?, CURDATE())
    ON DUPLICATE KEY UPDATE comment = VALUES(comment), dateTime = CURDATE()
');
$stmt->execute([$userId, $recordId, (int) $randId, $comment]);

echo json_encode(['success' => true, 'saved' => date('H:i:s')]);
