<?php
/**
 * controllers/animalTestSubmit.php
 *
 * Handles POST submission of animal dietary balance test data.
 * Replaces dashboard/crop-analysis/animal-dietary-balance/animal-submit.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/animal-dietary-balance/');
    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] ?? '');
$num = fn($key) => is_numeric($_POST[$key] ?? '') ? (float) $_POST[$key] : null;

// Collect POST fields
$email          = $str('email');
$clientName     = $str('name');
$siteAddress    = $str('site_address');
$statePostcode  = $str('state_postcode');
$analysisType   = $str('analysis_type');
$labNo          = $str('lab_no');
$dateSampled    = $str('date_sampled') ?: null;
$sampleId       = $str('sample_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');
$mo = $str('mo'); $co = $str('co'); $se = $str('se');
$cl = $str('cl');

// meq/100g calculations
$kNum  = (float) $k;
$sNum  = (float) $s;
$caNum = (float) $ca;
$mgNum = (float) $mg;
$naNum = (float) $na;
$clNum = (float) $cl;

$kMeq  = $kNum  / 390;
$sMeq  = $sNum  / 100000 * 33333 * 1.11;
$caMeq = $caNum / 200;
$mgMeq = $mgNum / 120;
$naMeq = $naNum / 230;
$clMeq = $clNum / 100000 * 448.34 * 1.11;

$stmt = $pdo->prepare('
    INSERT INTO animal_records
        (client_records_id, modx_user_id, date, email, client_name, site_address,
         state_postcode, analysis_type, lab_no, date_sampled, sample_id, crop_type,
         n, p, k, s, mg, ca, na, fe, mn, zn, cu, b, mo, co, se, cl,
         k_meq, s_meq, ca_meq, mg_meq, na_meq, cl_meq, rand)
    VALUES
        (0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
         ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
         ?, ?, ?, ?, ?, ?, ?)
');

$stmt->execute([
    $userId, $date, $email, $clientName, $siteAddress,
    $statePostcode, $analysisType, $labNo, $dateSampled, $sampleId, $cropType,
    $n, $p, $k, $s, $mg, $ca, $na, $fe, $mn, $zn, $cu, $b, $mo, $co, $se, $cl,
    $kMeq, $sMeq, $caMeq, $mgMeq, $naMeq, $clMeq, $rand,
]);

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

header('Location: /dashboard/crop-analysis/animal-dietary-balance/?rand=' . $rand
    . '&cid=' . urlencode($sampleId)
    . '&rid=' . $insertId
    . '&stid=' . urlencode($cropType));
exit;
