<?php
/**
 * plant-report-save.php
 *
 * AJAX endpoint: auto-saves plant report consultant notes to the reports table.
 * Called by the auto-save JS in plant-report.php via POST.
 *
 * POST params: general_details, recommended_details, foliar_details
 * GET params:  rid (plant_records.id), rand (plant_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 plant record belongs to this user
$check = $pdo->prepare(
    'SELECT id FROM plant_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;
}

$data = [
    'general_details'     => trim($_POST['general_details']     ?? ''),
    'recommended_details' => trim($_POST['recommended_details'] ?? ''),
    'foliar_details'      => trim($_POST['foliar_details']      ?? ''),
];

$comment = json_encode($data, JSON_UNESCAPED_UNICODE);

$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')]);
