<?php
/**
 * controllers/waterTestSubmit.php
 *
 * POST handler for water test analysis entry.
 * Inserts a new record into water_records.
 */

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/water-test-data/water-test-data.php');
    exit;
}

if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    $_SESSION['flash_error'] = 'Invalid CSRF token. Please try again.';
    header('Location: /dashboard/crop-analysis/water-test-data/water-test-data.php');
    exit;
}

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

$clientId = (int) ($_POST['client_id'] ?? 0);
if ($clientId > 0) {
    $stmt = $pdo->prepare('SELECT id FROM client_records WHERE id = ? AND modx_user_id = ?');
    $stmt->execute([$clientId, $userId]);
    if (!$stmt->fetch()) {
        $clientId = 0;
    }
}

$rand = mt_rand(10000, 99999);

$fields = [
    'lab_no', 'batch_no', 'date_sampled', 'sample_id', 'site_id',
    'ph', 'cond_dsm', 'hco3',
    'n', 'p', 'k', 's', 'mg', 'ca',
    'na', 'fe', 'mn', 'zn', 'cu', 'b',
    'm', 'co', 'se', 'ch',
];

$colList = 'modx_user_id, client_records_id, rand, ' . implode(', ', array_map(fn($c) => "`$c`", $fields));
$placeholders = implode(', ', array_fill(0, count($fields) + 3, '?'));

$values = [$userId, $clientId ?: null, $rand];
foreach ($fields as $field) {
    $val = trim((string) ($_POST[$field] ?? ''));
    $values[] = ($val === '') ? null : $val;
}

try {
    $stmt = $pdo->prepare("INSERT INTO water_records ($colList) VALUES ($placeholders)");
    $stmt->execute($values);
    $newId  = (int) $pdo->lastInsertId();
    $_SESSION['flash_success'] = 'Water test record saved successfully.';
    header("Location: /dashboard/inbox.php");
} catch (\PDOException $e) {
    $_SESSION['flash_error'] = 'Failed to save record. Please try again.';
    header('Location: /dashboard/crop-analysis/water-test-data/water-test-data.php');
}
exit;
