<?php
// ini_set('MAX_EXECUTION_TIME', 3600);
include('includes/config/config.php');
include('includes/auth/auth.php');
include('includes/functions.php');
include('access.php');
error_reporting(E_ERROR | E_PARSE);
begin();
$response = array();
// taking unique checkup ids where data is not processed
$query = "select b.checkup_id from device_result a left join device_order b on a.accession_number = b.accession_number where a.is_processed = 'N' group by b.checkup_id;";

error_log("query " . $query);
if ($result = mysqli_query($conn, $query)) {
    while ($row = mysqli_fetch_assoc($result)) {

        $highlighted_color = [];

        $risk = [];

        $advices = [];

        $checkup_id = $row['checkup_id'];

        error_log("for checkup id " . $checkup_id);

        $checkup_section_ids = getFieldFromTable('checkup_section_ids', 'checkup_form', 'checkup_id', $checkup_id);

        $section_arr = explode(",", $checkup_section_ids);

        error_log("checkup section ids " . print_r($section_arr, true));

        $query_param = "select b.online_testcode,b.device_id,b.accession_number,b.device_name,a.test_result,b.checkup_id from device_result a left join device_order b on a.accession_number = b.accession_number and a.online_testcode = b.online_testcode  where b.checkup_id='" . $checkup_id . "'";

        error_log("query to get code and result from device result " . $query_param);

        $result_param = mysqli_query($conn, $query_param);

        while ($row_param = mysqli_fetch_assoc($result_param)) {

            foreach ($section_arr as $section_id) {

                $param_id_sql="SELECT a.checkup_parameter_id FROM checkup_parameter a LEFT JOIN device_param_map b ON a.checkup_parameter_id=b.checkup_parameter_id 
                LEFT JOIN checkup_form_section c ON a.checkup_form_section_id=c.section_id WHERE  c.section_id = '".$section_id."' AND b.device_param_code='".trim($row_param['online_testcode'])."' AND b.device_id='".$row_param['device_id']."'";

                error_log("query to get data from checkup_parameter and device param map ".$param_id_sql);

                $result_id_sql = mysqli_query($conn,$param_id_sql);

                $row_id_sql = mysqli_fetch_assoc($result_id_sql);

                $param_id = $row_id_sql['checkup_parameter_id'];

                // $param_id = getTableFieldValue('device_param_map', 'checkup_parameter_id', 'device_param_code', "'" . trim($row_param['online_testcode']) . "'", 'device_id', $row_param['device_id']);

                $actual_param_name = getTableFieldValue('checkup_parameter', 'column_name', 'checkup_parameter_id', $param_id);

                error_log("actual param name in our table " . $actual_param_name);
                // check if data exist in checkup form key value

                if ($actual_param_name != '') {

                    $device_name = $row_param['device_name'];

                    $test_result = $row_param['test_result'];

                    checkRangeData($test_result, $checkup_id, $actual_param_name, $section_id, $highlighted_color, $risk, $advices);

                    $isExist = "select * from checkup_form_key_value where checkup_form_id='" . $checkup_id . "' and checkup_form_key = '" . $actual_param_name . "'";

                    error_log("exist or not already " . $isExist);

                    $resultExist = mysqli_query($conn, $isExist);
                    $numRowsExist = mysqli_num_rows($resultExist);

                    // update case it is 
                    if ($numRowsExist > 0) {
                        updateInsertEntry($test_result, $checkup_id, $actual_param_name, "update ", " where checkup_form_id='" . $checkup_id . "' and checkup_form_key = '" . $actual_param_name . "'");
                    }
                    // insert case it is
                    else {
                        updateInsertEntry($test_result, $checkup_id, $actual_param_name, "insert into ", ", checkup_form_key='" . $actual_param_name . "',checkup_form_id='".$checkup_id."'");
                    }

                    $accession_number = $row_param['accession_number'];
                    $online_testcode = $row_param['online_testcode'];
                    $device_name = $row_param['device_name'];

                    updateDeviceEntry($accession_number, $online_testcode, $device_name);
                }
            }
        }

        error_log("color array " . print_r($highlighted_color, true));
        error_log("keys in array " . print_r(array_keys($highlighted_color), true));
        saveHighlightedParams($checkup_id, $highlighted_color, '');

        updateRiskAdvice($checkup_id, $risk, $advices);
    }

    $response['success'] = true;
    $response['message'] = "Processing completed successfully.";
}

function updateDeviceEntry($accession_number, $online_testcode, $device_name)
{
    $query = "update device_result set is_processed='Y' where accession_number='" . $accession_number . "' and online_testcode='" . $online_testcode . "' and device_name='" . $device_name . "'";

    error_log("device result update query " . $query);

    if (!$result = mysqli_query($GLOBALS['conn'], $query)) {
        $response['success'] = false;
        $response['message'] = "Something went wrong while updating the device result.";
        error_log("error " . mysqli_error($GLOBALS['conn']));
        rollback();
    }
}

function updateInsertEntry($param_val, $checkup_id, $actual_param_name, $part, $last)
{
    $query = $part . " checkup_form_key_value set checkup_form_value='" . $param_val . "' " . $last;
    error_log("insert/update query " . $query);
    if (!$result = mysqli_query($GLOBALS['conn'], $query)) {
        $response['success'] = false;
        $response['message'] = "Something went wrong while updating the data.";
        error_log("error " . mysqli_error($GLOBALS['conn']) . "   " . $query);
        rollback();
    }
}

function checkRangeData($val, $checkup_id, $param_name, $section_id, &$highlight_color, &$risk, &$advices)
{
    $patient_id = getFieldFromTable('emp_id', 'checkup_form', 'checkup_id', $checkup_id);

    error_log("patient id " . $patient_id);
    $pat_dob = getFieldFromTable('dob', 'patient_master', 'id', $patient_id);

    $today = date("Y-m-d");
    error_log("pat_dob " . $pat_dob);
    $age = ($today - $pat_dob);
    error_log("age " . $age);

    $pat_gender = getFieldFromTable('gender', 'patient_master', 'id', $patient_id);
    error_log("patient gender " . $pat_gender);

    $rule_id_sql = "select * from checkup_parameter where column_name='" . trim($param_name) . "' and checkup_form_section_id='" . $section_id . "' ";

    $rule_result = mysqli_query($GLOBALS['conn'], $rule_id_sql);

    while ($rule_row = mysqli_fetch_assoc($rule_result)) {
        $key = getFieldFromTable('key_param_name', 'key_health_reportable_parameter_master', 'key_param_id', $rule_row['key_health_map_name']);

        $rule_ids = explode(",", $rule_row['rule_ids']);

        foreach ($rule_ids as $id) {
            $query = "select * from rule_equation where rule_eq_id='" . $id . "'";

            error_log("rule equation getting query " . $query);

            $result = mysqli_query($GLOBALS['conn'], $query);

            $row = mysqli_fetch_assoc($result);

            $rule_age_start = $row['rule_age_start'];
            $rule_age_end = $row['rule_age_end'];
            $rule_gender = $row['rule_gender'];

            error_log("equation age gender data " . $rule_age_start . " " . $rule_age_end . " " . $rule_gender);

            if (intval($rule_age_end) != 0) {
                if (intval($rule_age_start) > intval($age)) {
                    error_log("got here and continue for age mismatch" . $rule_age_start . " " . $age);
                    continue;
                } else if (intval($rule_age_end) < intval($age)) {
                    error_log("got here and continue for age mismatch" . $rule_age_end . " " . $age);
                    continue;
                }
            }
            if (($rule_gender != "" || $rule_gender != null) && strtolower($rule_gender) != strtolower($pat_gender)) {
                error_log("got here and continue for gender mismatch");
                continue;
            }

            $equation = $row['rule_equation'];

            error_log("before equation " . $equation);

            if ($row['is_string_rule'] == 0) {
                if ($val != '' && $val != null) {
                    $equation = str_replace($key, $val, $equation);

                    error_log("after placing values in  equation " . $equation);

                    $ans = solveMathExpression($equation);

                    error_log("ans is " . $ans);

                    if ($ans == 1) {
                        error_log("got inside the if and data is " . print_r($row, true));

                        $highlight_color[$param_name] = $row['color'];
                        error_log("color array " . print_r($highlight_color, true));
                        error_log("keys in array " . print_r(array_keys($highlight_color), true));
                        array_push($risk, $row['risks']);
                        array_push($advices, $row['advices']);

                        error_log("risk array " . print_r($risk, true) . "  advice " . print_r($advices, true));
                    }
                }
            } else if ($row['is_string_rule'] == 1 && $val != '' && $val != null) {
                $rule_val = getFieldFromTable('rule_s_val', 'rule_save', 'equation_rule_id', $row['rule_eq_id']);

                $rule_values = explode(",", $rule_val);

                for ($i = 0; $i < sizeof($rule_values); $i++) {
                    if (strcmp(strtolower(trim($rule_values[$i])), strtolower(trim($val))) == 0) {
                        error_log("got inside the string rule if");
                        $highlight_color[$param_name] = $row['color'];
                        array_push($risk, $row['risks']);
                        array_push($advices, $row['advices']);
                    }
                }
            }
        }
    }
}



function solveMathExpression($expression)
{
    // Check if the math expression matches the pattern
    // if (preg_match($pattern, $expression)) {
    try {
        return round(eval("return ($expression);"), 2);
    } catch (ParseError $e) {
        error_log("getting exception in this " . $e->getMessage());
    }
}

function updateRiskAdvice($checkup_id, &$risk, &$advices)
{

    error_log("risk " . print_r($risk, true));
    error_log("advice " . print_r($advices, true));

    $risk = implode(",", array_unique($risk));
    $advices = implode(",", array_unique($advices));

    $query = "update checkup_form set health_risk_id = '" . $risk . "' and health_advice_id='" . $advices . "' where checkup_id='" . $checkup_id . "'";

    error_log("update risk advice " . $query);

    if (!$result = mysqli_query($GLOBALS['conn'], $query)) {
        $response['success'] = false;
        $response['message'] = "Something went wrong while updating the risk and advice based on result.";
        error_log("error " . mysqli_error($GLOBALS['conn']) . " query" . $query);
    }
}

commit();

echo json_encode($response);