<?php
session_start();
ini_set('display_errors', 0);
error_reporting(0);

header('Content-Type: application/json; charset=utf-8');

// Relative anchor up to structural includes mapping
require_once __DIR__ . '/../../includes/db.php';

$response = ['status' => 'error', 'message' => 'An unrecognized database transaction anomaly occurred.'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $response['message'] = 'Invalid request configuration context.';
    echo json_encode($response);
    exit;
}

try {
    // Sanitize parameters to safely align with schema constraints
    $sample_name     = isset($_POST['sample_name']) ? trim($_POST['sample_name']) : '';
    $container_type  = isset($_POST['container_type']) ? trim($_POST['container_type']) : null;
    $container_color = isset($_POST['container_color']) ? trim($_POST['container_color']) : '#cbd5e1';
    $required_volume = isset($_POST['required_volume']) ? trim($_POST['required_volume']) : 'Standard';
    $default_source  = isset($_POST['default_source']) ? trim($_POST['default_source']) : null;

    // Enforce domain validations
    if (empty($sample_name)) {
        throw new Exception("Sample Type Name (e.g., Whole Blood) cannot be left empty.");
    }

    // Integrity Check: Prevent duplicate registration rows
    $check_stmt = $conn->prepare("SELECT id FROM lab_sample_types WHERE sample_name = ?");
    $check_stmt->bind_param("s", $sample_name);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows > 0) {
        throw new Exception("A laboratory specimen configuration for '$sample_name' is already active inside the system.");
    }
    $check_stmt->close();

    // Prepare robust insertion query matching schema specifications
    $sql = "INSERT INTO lab_sample_types (
                sample_name, container_type, container_color, required_volume, default_source, is_active
            ) VALUES (?, ?, ?, ?, ?, 1)";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Database Preparation Structural Failure: " . $conn->error);
    }

    // 5 parameters matching the 'sssss' format string perfectly
    $stmt->bind_param(
        "sssss",
        $sample_name,
        $container_type,
        $container_color,
        $required_volume,
        $default_source
    );

    if ($stmt->execute()) {
        $response['status'] = 'success';
        $response['message'] = 'Laboratory specimen matrix configuration added successfully.';
    } else {
        throw new Exception("Execution pipeline failed to commit updates: " . $stmt->error);
    }
    $stmt->close();

} catch (Throwable $e) {
    $response['status'] = 'error';
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
exit;