<?php
/**
 * RiMax Health Suite - Lab Reference Ranges API Endpoint
 * Handles fetching parameters, loading configured rules, and saving new metrics.
 */

header('Content-Type: application/json; charset=utf-8');
error_reporting(0);
ini_set('display_errors', 0);

ob_start();

try {
    // Correct absolute relative navigation back up to core drip-end application configurations
    require_once __DIR__ . '/../../includes/db.php'; 
    
    if (!isset($conn) || !($conn instanceof mysqli)) {
        throw new Exception("Database application environment instance (\$conn) missing or invalid.");
    }

    $response = [
        'status' => 'error',
        'message' => 'Unknown request dispatch transaction step.',
        'unit_of_measure' => '-',
        'data' => []
    ];

    $action = $_GET['action'] ?? $_POST['action'] ?? '';

    switch ($action) {

        // ==========================================
        // ACTION 1: FETCH CONFIGURED RANGES FOR A SELECTED PARAMETER
        // ==========================================
        case 'fetch':
            $parameter_id = intval($_GET['param_id'] ?? $_GET['parameter_id'] ?? 0);
            if ($parameter_id <= 0) {
                throw new Exception("Invalid structural parameter context key reference ID.");
            }

            // Capture base parameter context details to return the tracking unit of measure
            $stmtParam = $conn->prepare("SELECT unit_of_measure FROM lab_parameters WHERE id = ?");
            $stmtParam->bind_param("i", $parameter_id);
            $stmtParam->execute();
            $paramMeta = $stmtParam->get_result()->fetch_assoc();
            $stmtParam->close();

            if ($paramMeta) {
                $response['unit_of_measure'] = $paramMeta['unit_of_measure'] ?? '-';
            }

            // Pull reference configurations matching target context matrices
            $stmtRanges = $conn->prepare("SELECT id, gender_target, min_age_years, max_age_years, min_value, max_value, critical_low, critical_high, is_active FROM lab_reference_ranges WHERE parameter_id = ? ORDER BY gender_target ASC, min_age_years ASC");
            $stmtRanges->bind_param("i", $parameter_id);
            $stmtRanges->execute();
            $res = $stmtRanges->get_result();
            
            $ranges = [];
            while ($row = $res->fetch_assoc()) {
                $ranges[] = $row;
            }
            $stmtRanges->close();

            $response['status'] = 'success';
            $response['message'] = 'Parameter reference ranges loaded successfully.';
            $response['data'] = $ranges;
            break;

        // ==========================================
        // ACTION 2: SAVE A NEW REFERENCE RANGE RULE
        // ==========================================
        case 'add':
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                throw new Exception("Invalid stream protocol mechanism. POST submission required.");
            }

            $parameter_id   = intval($_POST['parameter_id'] ?? 0);
            $gender_target  = trim($_POST['gender_target'] ?? 'All');
            $min_age_years  = isset($_POST['min_age_years']) ? intval($_POST['min_age_years']) : 0;
            $max_age_years  = isset($_POST['max_age_years']) ? intval($_POST['max_age_years']) : 150;
            
            // Clean dynamic decimal bounds and correctly parse blank entries as programmatic NULL values
            $min_value     = ($_POST['min_value'] !== '') ? floatval($_POST['min_value']) : null;
            $max_value     = ($_POST['max_value'] !== '') ? floatval($_POST['max_value']) : null;
            $critical_low  = ($_POST['critical_low'] !== '') ? floatval($_POST['critical_low']) : null;
            $critical_high = ($_POST['critical_high'] !== '') ? floatval($_POST['critical_high']) : null;

            if (strcasecmp($gender_target, 'Universal') === 0) {
                $gender_target = 'All';
            }

            if ($parameter_id <= 0) {
                throw new Exception("Target key parameter tracking parent scope required.");
            }
            if ($min_value === null || $max_value === null) {
                throw new Exception("Baseline reference ranges (Min/Max values) are mandatory metrics.");
            }
            if ($min_value > $max_value) {
                throw new Exception("Boundary conflict. Minimum value cannot exceed the Maximum value.");
            }

            $insert_query = "INSERT INTO lab_reference_ranges 
                             (parameter_id, gender_target, min_age_years, max_age_years, min_value, max_value, critical_low, critical_high, is_active) 
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)";
            
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("isiidddd", $parameter_id, $gender_target, $min_age_years, $max_age_years, $min_value, $max_value, $critical_low, $critical_high);
            $execution_status = $stmt->execute();
            $stmt->close();

            if ($execution_status) {
                $response['status'] = 'success';
                $response['message'] = 'Reference range metric configured and synchronized successfully.';
            } else {
                throw new Exception("Database failed to execute the layout commit operation schema sequence.");
            }
            break;

        // ==========================================
        // ACTION 3: TOGGLE THE VISIBILITY/STATUS OF A RULE
        // ==========================================
        case 'toggle':
            $rule_id = intval($_POST['id'] ?? 0);
            $current_status = intval($_POST['current_status'] ?? 0);
            $new_status = ($current_status === 1) ? 0 : 1;

            if ($rule_id <= 0) {
                throw new Exception("Invalid target rule parameter tracker ID.");
            }

            $stmtToggle = $conn->prepare("UPDATE lab_reference_ranges SET is_active = ? WHERE id = ?");
            $stmtToggle->bind_param("ii", $new_status, $rule_id);
            $status = $stmtToggle->execute();
            $stmtToggle->close();

            if ($status) {
                $response['status'] = 'success';
                $response['message'] = 'Status visibility updated safely.';
            } else {
                throw new Exception("Failed to modify target row operational matrix status.");
            }
            break;

        // ==========================================
        // ACTION 4: DELETE A REFERENCE RANGE RULE
        // ==========================================
        case 'delete':
            $rule_id = intval($_POST['id'] ?? 0);

            if ($rule_id <= 0) {
                throw new Exception("Invalid operational action rule reference sequence reference ID.");
            }

            $stmtDel = $conn->prepare("DELETE FROM lab_reference_ranges WHERE id = ?");
            $stmtDel->bind_param("i", $rule_id);
            $status = $stmtDel->execute();
            $stmtDel->close();

            if ($status) {
                $response['status'] = 'success';
                $response['message'] = 'Reference layout criteria string permanently truncated from dataset config.';
            } else {
                throw new Exception("Database routine constraint error preventing rule record extraction.");
            }
            break;

        default:
            throw new Exception("No valid functional routine processor matched operational command: '$action'.");
    }

    ob_end_clean();
    echo json_encode($response);
    exit;

} catch (Exception $e) {
    ob_end_clean();
    echo json_encode([
        'status' => 'error',
        'message' => 'Backend Core Exception: ' . $e->getMessage(),
        'unit_of_measure' => '-',
        'data' => []
    ]);
    exit;
}