<?php
/**
 * controllers/plantTestSubmit.php
 *
 * Handles POST submission of plant tissue analysis test data.
 * Replaces dashboard/crop-analysis/plant-test-data/generating-plant-analysis.php
 */

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

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

requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /dashboard/crop-analysis/plant-test-data/');
    exit;
}

if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    http_response_code(403);
    exit('Invalid security token.');
}

$pdo    = getDBConnection();
$userId = getCurrentUserId();
$date   = date('Y-m-d');
$rand   = mt_rand(10000, 99999);

$str = fn($key) => trim($_POST[$key] ?? '');

$email         = $str('email');
$clientName    = $str('name');
$siteAddress   = $str('site_address');
$statePostcode = $str('state_postcode');
$analysisType  = $str('analysis_type');
$labNo         = $str('lab_no');
$batchNo       = $str('batch_no');
$dateSampled   = $str('date_sampled') ?: null;
$sampleId      = $str('sample_id');
$siteId        = $str('site_id');
$cropType      = $str('crop_type');

$n  = $str('n');  $p  = $str('p');  $k  = $str('k');
$s  = $str('s');  $mg = $str('mg'); $ca = $str('ca');
$na = $str('na'); $fe = $str('fe'); $mn = $str('mn');
$zn = $str('zn'); $cu = $str('cu'); $b  = $str('b');
$m  = $str('m') ?: null;
$co = $str('co') ?: null;
$se = $str('se') ?: null;
$cl = $str('cl') ?: null;

$stmt = $pdo->prepare('
    INSERT INTO plant_records
        (client_records_id, modx_user_id, date, email, client_name, site_address,
         state_postcode, analysis_type, lab_no, batch_no, date_sampled, sample_id,
         site_id, crop_type, n, p, k, s, mg, ca, na, fe, mn, zn, cu, b,
         m, co, se, cl, rand)
    VALUES
        (0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
         ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
         ?, ?, ?, ?, ?)
');

$stmt->execute([
    $userId, $date, $email, $clientName, $siteAddress,
    $statePostcode, $analysisType, $labNo, $batchNo, $dateSampled, $sampleId,
    $siteId, $cropType,
    $n, $p, $k, $s, $mg, $ca, $na, $fe, $mn, $zn, $cu, $b,
    $m, $co, $se, $cl, $rand,
]);

$insertId = (int) $pdo->lastInsertId();

header('Location: /dashboard/crop-analysis/plant-test-data/plant-analysis.php?rand=' . $rand
    . '&cid=' . urlencode($sampleId)
    . '&rid=' . $insertId
    . '&stid=' . urlencode($cropType));
exit;
