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

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

require_once __DIR__ . '/../../includes/db.php';

$response = ['status' => 'error', 'message' => 'An unrecognized system execution error occurred.'];

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

try {
    // Collect Core Inputs
    $param_name  = isset($_POST['parameter_name']) ? trim($_POST['parameter_name']) : '';
    $result_type = isset($_POST['result_type']) ? trim($_POST['result_type']) : 'Numeric';
    $unit        = isset($_POST['unit_of_measure']) ? trim($_POST['unit_of_measure']) : null;
    $technique   = isset($_POST['default_technique']) ? trim($_POST['default_technique']) : null;
    $description = isset($_POST['description']) ? trim($_POST['description']) : null;
    $instructions= isset($_POST['lab_instructions']) ? trim($_POST['lab_instructions']) : null;
    $show_in_phr = isset($_POST['show_in_phr']) ? 1 : 0;

    // Enforce business rules
    if (empty($param_name)) {
        throw new Exception("Parameter Name / Label is mandatory.");
    }
    if (!in_array($result_type, ['Numeric', 'Options', 'Text'])) {
        throw new Exception("Selected Result Input Format is invalid.");
    }

    // Contextual Variable Assignments
    $min_male     = null; $max_male     = null;
    $min_female   = null; $max_female   = null;
    $min_child    = null; $max_child    = null;
    $options_list = null; $expected_val = null;

    if ($result_type === 'Numeric') {
        $min_male   = (isset($_POST['min_male'])   && $_POST['min_male']   !== '') ? floatval($_POST['min_male'])   : null;
        $max_male   = (isset($_POST['max_male'])   && $_POST['max_male']   !== '') ? floatval($_POST['max_male'])   : null;
        $min_female = (isset($_POST['min_female']) && $_POST['min_female'] !== '') ? floatval($_POST['min_female']) : null;
        $max_female = (isset($_POST['max_female']) && $_POST['max_female'] !== '') ? floatval($_POST['max_female']) : null;
        $min_child  = (isset($_POST['min_child'])  && $_POST['min_child']  !== '') ? floatval($_POST['min_child'])  : null;
        $max_child  = (isset($_POST['max_child'])  && $_POST['max_child']  !== '') ? floatval($_POST['max_child'])  : null;
    } elseif ($result_type === 'Options') {
        $options_list = isset($_POST['options_list']) ? trim($_POST['options_list']) : '';
        $expected_val = isset($_POST['expected_value']) ? trim($_POST['expected_value']) : null;
        
        if (empty($options_list)) {
            throw new Exception("Please specify comma-separated dropdown items for option format.");
        }
        // Dropdown rows do not utilize units of measure
        $unit = null;
    }

    // Verify system constraints for duplication
    $check_stmt = $conn->prepare("SELECT id FROM lab_parameters WHERE parameter_name = ?");
    $check_stmt->bind_param("s", $param_name);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows > 0) {
        throw new Exception("A lab parameter with the exact label '$param_name' already exists.");
    }
    $check_stmt->close();

    // Prepare robust insert mapping directly to your schema design
    // 16 dynamic parameters (represented by ?) are used here
    $sql = "INSERT INTO lab_parameters (
                service_id, parameter_name, unit_of_measure, unit, 
                min_male, max_male, min_female, max_female, min_child, max_child, 
                is_active, description, result_type, options_list, expected_value, 
                default_technique, lab_instructions, show_in_phr
            ) VALUES (0, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?)";

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

    // FIXED: Changed type string definition from "ssssddddddssssssi" to "sssddddddssssssi" (exactly 16 elements)
    $stmt->bind_param(
        "sssddddddssssssi",
        $param_name,   // 1 (s)
        $unit,         // 2 (s)
        $unit,         // 3 (s)
        $min_male,     // 4 (d)
        $max_male,     // 5 (d)
        $min_female,   // 6 (d)
        $max_female,   // 7 (d)
        $min_child,    // 8 (d)
        $max_child,    // 9 (d)
        $description,  // 10 (s)
        $result_type,  // 11 (s)
        $options_list, // 12 (s)
        $expected_val, // 13 (s)
        $technique,    // 14 (s)
        $instructions, // 15 (s)
        $show_in_phr   // 16 (i)
    );

    if ($stmt->execute()) {
        $response['status'] = 'success';
        $response['message'] = 'Laboratory parameter configuration updated successfully.';
    } else {
        throw new Exception("Database Writing Failure: " . $stmt->error);
    }
    $stmt->close();

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

echo json_encode($response);
exit;