<?php     

include_once ("../include/mcglobal.inc.php");
include_once ("../include/inc_dbdata.inc.php");
include_once ("../include/inc_sendReq.inc.php");


// **** [(T * L * KM * MLP * U) / TF] ****
function sendReqCO2 ($jbId) {
  global $dbData, $hq_id, $usr_id;

  $rca = array();
  $errMsg = "";

  if ($jbId != "" && is_numeric($jbId) && $jbId > 0) :

     getDBData("job", $jbId);
     $jbArr = $dbData["job"];

     if ($jbArr["jb_status"] != "") :

        if ($jbArr["cr_sid"] != "") :

           $crvhId = getFieldValueFromId("couriervehicle", "crvh_sid", $jbArr["cr_sid"], "crvh_id");
           getDBData("couriervehicle", $crvhId);
           $crvhArr = $dbData["couriervehicle"];
           $co2_KG = $crvhArr["crvh_payload"];

           if ($jbArr["jb_weight"] > 0) :
              $co2_T = $jbArr["jb_weight"];
           else :
              $co2_T  = ($co2_KG * 0.5);
           endif;              

           if ($co2_T != "" && is_numeric($co2_T) && $co2_T > 0) :

              $jbHqId = getFieldValueFromId("job", "jb_id", $jbId, "hq_id");

              // Leerfahrtsfaktor
              $co2_L = getParameterValue("0", "CO2_FORMULAR_L", $jbHqId);
              if ($co2_L == "" || !is_numeric($co2_L)) : $co2_L = getParameterValue("0", "CO2_FORMULAR_L", "0"); endif;
              if ($co2_L == "" || !is_numeric($co2_L)) : $co2_L = 1.2; endif;
              // Umrechnungsfaktor
              $co2_U = getParameterValue("0", "CO2_FORMULAR_U", $jbHqId);
              if ($co2_U == "" || !is_numeric($co2_U)) : $co2_U = getParameterValue("0", "CO2_FORMULAR_U", "0"); endif;
              if ($co2_U == "" || !is_numeric($co2_U)) : $co2_U = 3.15; endif;
              // Teilungsfaktor
              $co2_TF = getParameterValue("0", "CO2_FORMULAR_TF", $jbHqId);
              if ($co2_TF == "" || !is_numeric($co2_U)) : $co2_TF = getParameterValue("0", "CO2_FORMULAR_TF", "0"); endif;
              if ($co2_TF == "" || !is_numeric($co2_U)) : $co2_TF = 1000; endif;

              // MLP
              $co2_MLP = "0.13";  // Default
              if ($crvhArr["vht_id"] <= "7") :
                 switch ($crvhArr["crvh_env_badge_level"]) {
                     case 1:
                         $co2_MLP = "0.13";
                         break;
                     case 2:
                         $co2_MLP = "0.1255";
                         break;
                     case 3:
                         $co2_MLP = "0.133";
                         break;
                     case 4:
                         $co2_MLP = "0.134";
                         break;
                     case 5:
                         $co2_MLP = "0.1285";
                         break;
                     case 6:
                         $co2_MLP = "0.13";
                         break;
                 }
              else :
                 switch ($crvhArr["crvh_env_badge_level"]) {
                     case 1:
                         $co2_MLP = "0.1755";
                         break;
                     case 2:
                         $co2_MLP = "0.17";
                         break;
                     case 3:
                         $co2_MLP = "0.181";
                         break;
                     case 4:
                         $co2_MLP = "0.1795";
                         break;
                     case 5:
                         $co2_MLP = "0.1715";
                         break;
                     case 6:
                         $co2_MLP = "0.1755";
                         break;
                 }
              endif;

              $co2_KM = getFieldValueFromClause("jobprice","jbprc_price","jb_id = '" . $jbId . "' AND mt_sort = '11'");

              if ($co2_KM != "" && is_numeric($co2_KM) && $co2_KM > 0) :

                 $request_data = array(
                  "referenz" => $jbId,
                  "mlp" => $co2_MLP,
                  "gewicht" => $co2_T,
                  "gefahreneKm" => $co2_KM
                 );

                 $json_request_data = json_encode($request_data);
                 $json_request_data = '{"data" : [' . $json_request_data . ']}';

                 $isProductive = true;

                 $rca["reqMode"] = "POST";
                 $rca["reqProtocol"] = "";
                 $username = "co2";
                 if ($isProductive) :
                    $password = "?P\+NW5\&4M+";
                    $rca["urlTarget"] = "https://co2-calc.hansetrans.de/api/v1/co2-emission/evaluate";         // LIVE
                    // $rca["reqHeaders"] = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("$username:$password"));
                    $rca["reqHeaders"] = array('Content-Type: application/json', 'Authorization: Basic Y28yOj9QXCtOVzVcJjRNKw==');  // LIVE
                 else :
                    $password = "x:(dMRR5JH\3";
                    // $rca["urlTarget"] = "https://httpbin.org/post";   // REQUEST CHECKER
                    $rca["urlTarget"] = "https://stage-co2-calc.hansetrans.de/api/v1/co2-emission/evaluate";   // TEST
                    // $rca["reqHeaders"] = array('Content-Type: application/json', 'Authorization: Basic ' . base64_encode("$username:$password"));
                    $rca["reqHeaders"] = array('Content-Type: application/json', 'Authorization: Basic Y28yOng6KGRNUlI1SkhcMw==');  // TEST
                 endif;
                 $rca["reqContent"] = $json_request_data;
                 $rca["reqUsrPwd"] = $username . ":" . $password;
                 $rca["urlEncode"] = "0";
                 $rca["returnResponse"] = "1";
                 $rca["connectTimeout"] = "";
                 $rca["getCurlInfo"] = "";
                 $rca["verbose"] = "";
                 $rca["logFile"] = "";

                 $jbprcRemark = "T=" . $co2_T . "|" . "L=" . $co2_L . "|" . "KM=" . $co2_KM . "|" . "MLP=" . $co2_MLP . "|" . "U=" . $co2_U . "|" . "TF=" . $co2_TF;

                 $response = sendRequestCO2e($rca, "1");

// echo "jb_weight = " . $jbArr["jb_weight"] . "<br>";
// echo "crvh_payload = " . $co2_KG . "<br>";
// echo "co2_weight = " . $co2_T . "<br>";
// echo "<br><br><br>RESPONSE: <br><br>";
// echo $response;
// echo "<br><br><br>";
// $jbprcPriceExpected = ($co2_T * $co2_L * $co2_KM * $co2_MLP * $co2_U) / $co2_TF;
// echo $jbprcPriceExpected . "<br><br>";
// echo $jbprcRemark . "<br><br>";
// print_r($dbData); die();

                 $rspArr = json_decode($response, true);
// print_r($rspArr);
// echo "<br>";
                 // Error handling
                 $errRspStatus = $rspArr["errors"]["0"]["status"];

                 if ($errRspStatus == "") :
                 
                    $jbIdRef    = $rspArr["data"]["0"]["referenz"];
                    $jbprcPrice = $rspArr["data"]["0"]["co2"];

                    // Insert "CO2e" value in "jobprice" (mt_sort = 12)
                    if (existsEntry("jobprice", array("jb_id", $jbId, "mt_sort", "12"))) :
                       updateStmt("jobprice","jb_id",$jbId,array("jbprc_price", $jbprcPrice, "jbprc_remark", $jbprcRemark),"mt_sort = '12'");
                    else :
                       insertStmt("jobprice", array("jb_id", $jbId, "mt_sort", "12", "jbprc_price", $jbprcPrice, "jbprc_remark ", $jbprcRemark));
                    endif;

                    // Write logdata into log database [STATE=OK]
                    $logDescription = $jbprcRemark . "|REQ_STATE=OK|RSP_STATE=OK|RSP_REF=" . $jbIdRef . "|RSP_CO2=" . $jbprcPrice;                    
                 else :

                    // ATTENTION: The field jobprice.jbprc_price will not be written => NEW TRIAL BY CRON....!!!!
                    $errRspDescription = $rspArr["errors"]["0"]["errorDescription"];
                    
                    // Write logdata into log database [STATE=NOK]
                    $logDescription = $jbprcRemark . "|REQ_STATE=OK|RSP_STATE=NOK|RSP_ERR_STATE=" . $errRspStatus . "|RSP_ERR_DESC=" . $errRspDescription;
                 endif;

              else :
                 $errMsg = getLngt("Das Ergebnis der KM-Berechnung scheint nicht valide!") . " [" . $jbId . " :: " . $co2_KM . "]";
                 $logDescription = $jbprcRemark . "|REQ_STATE=NOK|REQ_ERR_MSG=" . $errMsg;
              endif;
           else :
              $errMsg = getLngt("Das Fahrzeuggewicht fehlt!") . " [" . $jbId . " :: " . $co2_T . "]";
              $logDescription = $jbprcRemark . "|REQ_STATE=NOK|REQ_ERR_MSG=" . $errMsg;
           endif;
           
           // *******************************
           // * !!!! SPECIAL TREATMENT !!!! *
           insertJobpriceByVehicleFieldvalue($jbId, "crvh_partner_commission", "14");
           // insertJobpriceByVehicleFieldvalue($jbId, "crvh_system_fee_amount", "15");
           // *******************************           
        else :
           $errMsg = getLngt("Kein Fahrzeug eingetragen!") . " [" . $jbId . "]";
           $logDescription = $jbprcRemark . "|REQ_STATE=NOK|REQ_ERR_MSG=" . $errMsg;
        endif;
     else :
        $errMsg = getLngt("Der Auftrag ist noch nicht erledigt!") . " [" . $jbId . "]";
        $logDescription = $jbprcRemark . "|REQ_STATE=NOK|REQ_ERR_MSG=" . $errMsg;
     endif;
     
     // Write logdata into log database
     writeToLogDB("165",$jbHqId,$jbId,$usr_id,"","","",$logDescription);
  endif;

  return array($jbprcPrice, $response, $rspArr, $jbId, $logDescription);
}

?>



