<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class ResultCalcv2 {
   public function auto($id)
   {
       $CI =& get_instance();
       $this->db = $CI->load->database("onedev",true);
       $sql = "select 
          T_TestCalculationID,T_TestCalculationFormula,
          T_OrderDetailID, T_OrderDetailT_TestID, T_TestNat_TestID Nat_TestID,
          T_TestCalculationID,T_OrderDetailResult, 
          fn_global_age_count_day(M_PatientDOB, date(T_OrderHeaderDate)) / 365 AgeInYear,
          T_TestCalculationNat_SexID
       from t_orderdetail
       join t_orderheader on T_OrderDetailT_OrderHeaderID = T_OrderHeaderID 
            and T_OrderHeaderID = ?
       join m_patient on T_OrderHeaderM_PatientID = M_PatientID 
       join t_test on T_OrderDetailT_TestID = T_TestID 
         and T_OrderDetailIsActive = 'Y' and T_TestIsActive = 'Y'
       join t_testcalculation on T_TestNat_TestID  = T_TestCalculationNat_TestID 
         and T_TestCalculationIsActive = 'Y'
         and (
            T_TestCalculationNat_SexID = M_PatientM_SexID
            or 
            T_TestCalculationNat_SexID = 0
         )
       ";

       $sql_det = "select T_TestCalculationDetailCode, T_OrderDetailResult
          from 
         t_testcalculation_detail td 
         join t_testcalculation on T_TestCalculationID = T_TestCalculationDetailT_TestCalculationID
            and T_TestCalculationID = ?
         join t_test t on td.T_TestCalculationDetailNat_TestID = T_TestNat_TestID 
         left join t_orderdetail on T_TestID = T_OrderDetailT_TestID and T_OrderDetailIsActive = 'Y'
            and T_OrderDetailT_OrderHeaderID = ?
         where T_OrderDetailID is not null";
      

       $qry = $this->db->query($sql, array($id));
       $rows = $qry->result_array();
       if ( count($rows) > 0 ) {
          foreach($rows as $r) {
             $tc_id = $r["T_TestCalculationID"];
             $qry_det = $this->db->query($sql_det, array($tc_id, $id));
             $drows = $qry_det->result_array();
             $formula = $r["T_TestCalculationFormula"];
             $have_all = true;
             $have_one = false;
             $formula = str_replace("AGE",$r["AgeInYear"], $formula);
             $flag_recursive = false;
             if (strpos($formula,"[REC]") > -1 ) {
                $flag_recursive = true;
             }
             echo "$formula " . $r["T_OrderDetailResult"] . "\n";
             if ( ! $flag_recursive ) {
                if( trim($r["T_OrderDetailResult"]) != "") continue;
             }

             $formula = str_replace("[REC]","", $formula);
             foreach($drows as $dr) {
                $code = $dr["T_TestCalculationDetailCode"];
                $value = $dr["T_OrderDetailResult"];
                echo "$code , $value , $formula \n";
                if($dr["T_OrderDetailResult"] == "" ) {
                   $have_all = false;
                   break;
                }
                $have_one = true;
                $formula = str_replace($code, $value,$formula);
             }
             if ($have_all && $have_one) {

                eval("\$f_value = $formula;");
                //formating 
                echo "\n$f_value ..";
                $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
                if (is_numeric($f_value)) {
                   $f_value = $this->format_value($f_value,$r["Nat_TestID"]);
                }
                $od_id = $r["T_OrderDetailID"]; 
                $sql = "update t_orderdetail set T_OrderDetailResult = ?
                where T_OrderDetailID = ?";
                $this->db->query($sql, array($f_value,$od_id));
                $sql = "insert into t_order_calc(T_OrderCalcT_OrderDetailID,
                   T_OrderCalcFormula,T_OrderCalcResult) values(?,?,?)";
                $this->db->query($sql, array($od_id,$formula,$f_value));
             } 
         } 
       }
   }
   function format_value($f_value, $nat_test_id){
       $CI =& get_instance();
       $this->db = $CI->load->database("onedev",true);
       $sql = "select * from m_instrumentmethode
            where M_InstrumentMethodeIsActive = 'Y'
           and M_InstrumentMethodeNat_TestID = ?
           limit 0,1";
       $qry = $this->db->query($sql, array($nat_test_id) ); 
       if ($qry) {
         $rows = $qry->result_array();
         if (count($rows) > 0 ) {
            if ($f_value > 0 ) {
               $fmt = $rows[0]["M_InstrumentMethodeResultFormatAboveSF"];
            } else {
               $fmt = $rows[0]["M_InstrumentMethodeResultFormatSF"];
            }
            $idx = strpos($fmt,".");
            $dec = strlen($fmt) - $idx;
            if ($dec > 0 ) $dec = $dec -1;
            return number_format($f_value,$dec);
         }
       }
       return number_format($f_value,0,".",",");
   }
}
