<?php

// inc_sendReq.inc.php


include_once ("../include/inc_job.inc.php");


// Generic request
// $rca <=>  $requestConfigArray cointains url, request, protocol, etc.
// - reqMode        => Mode of the request ("PUT", "POST", "GET", default "PUT")
// - reqProtocol    => Protocol of the request (default "HTTPS")
// - urlTarget      => Target URL (example "https://sb.assecutor.de/tools/order_request.php/tools/order_request.php") with or without "https...."
// - reqHeaders     => Array of request headers (example "array('Content-Type: application/json', 'API-Key: ' . $apiKey)")
// - reqContent     => Full request content
// - reqUsrPwd      => Authenticate the user using basic auth
// - urlEncode      => Per default urlencode
// - returnResponse => Per default send back the delivered response
// - connectTimeout => Timeout (Default 300 seconds)
// - sslHost        => SSL verify host
// - sslPeer        => SSL verify peer
// - logFile        => If specified the do log request and response
function sendRequestGeneric ($rca) {
	global $db, $PHP_SELF;
  global $hq_id, $usr_id, $emp_id;

  $retVal = "NO_DATA";
  if ($rca["urlTarget"] != "" && $rca["reqContent"] != "") :
print_r($rca); echo "<br><br>";
     $retVal = "NOT_SENT";     
     if ($rca["reqMode"] == "") : $rca["reqMode"] = "PUT"; endif;
     if ($rca["reqProtocol"] == "") : $rca["reqProtocol"] = "https"; endif;
     if ($rca["urlEncode"] == "") : $rca["urlEncode"] = "1"; endif;
     if ($rca["returnResponse"] == "") : $rca["returnResponse"] = "1"; endif;
     if ($rca["sslHost"] == "") : $rca["sslHost"] = "1"; endif;
     if ($rca["sslPeer"] == "") : $rca["sslPeer"] = "1"; endif;
     if ($rca["connectTimeout"] == "" || !is_numeric($rca["connectTimeout"])) : $rca["connectTimeout"] = 300; endif;

     $rca["reqMode"] == strtoupper($rca["reqMode"]);
     if (strtolower(substr($rca["urlTarget"], 0, 4)) != "http") : $rca["urlTarget"] = "https://" . $rca["urlTarget"]; endif;
     if ($rca["urlEncode"] == "1") : $rca["reqContent"] = urlencode($rca["reqContent"]); endif;

     if ($rca["logFile"] != "") :
echo "HIER! <br>";
        writeToFile($logFile, "URL:");
        writeToFile($logFile, $rca["urlTarget"]);
        writeToFile($logFile, "REQUEST:");
        if ($rca["reqHeaders"] != "") :
           writeToFile($logFile, $rca["reqHeaders"][0]);
           writeToFile($logFile, $rca["reqHeaders"][1]);
           writeToFile($logFile, $rca["reqHeaders"][2]);
        endif;
        writeToFile($logFile, $rca["reqContent"]);
        // writeToFile($logFile, $requestConfigArray["CURLOPT_INFILE"]);
     endif;

     if ($rca["reqMode"] == "PUT") :

        $ch = curl_init();
        $fh = tmpfile();
        fwrite($fh, $rca["reqContent"]);
        fseek($fh, 0);
        if ($rca["reqHeaders"] != "") :
           curl_setopt($ch, CURLOPT_HTTPHEADER, $rca["reqHeaders"]);
        endif;
        // curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_HEADER, true);  // Do you want CURL to output the headers? Set to FALSE to hide them
        curl_setopt($ch, CURLOPT_URL, $rca["urlTarget"]);
        curl_setopt($ch, CURLOPT_PUT, true);
        if ($rca["reqUsrPwd"] != "") :
           curl_setopt($ch, CURLOPT_USERPWD, $rca["reqUsrPwd"]);
        endif;
        curl_setopt($ch, CURLOPT_INFILE, $fh);
        curl_setopt($ch, CURLOPT_INFILESIZE, strlen($rca["reqContent"]));
die();
        $result = curl_exec($ch);
        $errNo = curl_errno($ch);
        $errMsg = curl_error($ch);
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
   
        fclose($fh);
        curl_close($ch);

     elseif ($rca["reqMode"] == "POST") :

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $rca["sslPeer"]);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $rca["sslHost"]);
        curl_setopt($ch, CURLOPT_URL, $rca["urlTarget"]);
        if ($rca["returnResponse"] == "1") :
           curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
        endif;
        if ($rca["reqUsrPwd"] != "") :
           curl_setopt($ch, CURLOPT_USERPWD, $rca["reqUsrPwd"]);
        endif;
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $rca["connectTimeout"]);
        curl_setopt($ch, CURLOPT_TIMEOUT, $rca["connectTimeout"]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rca["reqContent"]);
        if ($rca["reqHeaders"] != "") :
           curl_setopt($ch, CURLOPT_HTTPHEADER, $rca["reqHeaders"]);
        endif;
        if ($rca["logFile"] != "") :
           // curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        endif;
die();
        $result = curl_exec($ch);
        $errNo = curl_errno($ch);
        $errMsg = curl_error($ch);
        $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);     

        curl_close($ch);

     elseif ($rca["reqMode"] == "GET") :


     endif;

     if ($rca["logFile"] != "") :
        writeToFile($logFile, "RESPONSE:");
        writeToFile($logFile, $result);
        writeToFile($logFile, "HTTP-STATUS: " . $httpStatus);
        writeToFile($logFile, "------------------------------------------------------------------------------------");
     endif;

     if (!($result === false)) :
        if ($returnResponse == "") :
           $retVal = "SENT_OK";
        else :
           $retVal = $result;
        endif;
     endif;
  endif;

  return $retVal;
}


// Specific request to Stadtbote
function sendReqSTB ($jbId, $cscName = "") {
	global $db, $PHP_SELF;
  global $jobData, $hq_id, $usr_id, $emp_id;

  $retVal = "NO_DATA";
  
  // Get job data
  getDBData("job", $jbId);
  getDBData("tour", $jbId);


  if (count($jobData["job"]) != 0) :

     // Returns the (XML-)response from remote server
     $returnResponse = getParameterValue("0", "SEND_REQUEST_TO_STB_RETURN_RESPONSE", $hq_id);
     if ($returnResponse == "") : $returnResponse = getParameterValue("0", "SEND_REQUEST_TO_STB_RETURN_RESPONSE", "0"); endif;

     // Specify requested vehicle type (vht_id)
     $requestedVhtId = $jobData["job"]["vht_id"];
     if ($requestedVhtId == "" || $requestedVhtId == "0") :
        $requestedVhtId = getParameterValue("0", "SEND_REQUEST_TO_STB_VHT_ID", $hq_id);
        if ($requestedVhtId == "") : $requestedVhtId = getParameterValue("0", "SEND_REQUEST_TO_STB_VHT_ID", "0"); endif;
        if ($requestedVhtId == "") : $requestedVhtId = "5"; endif;
     endif;

     $retVal = "NOT_SENT";

     $req = "";
     $req .= "<xml>";
     $req .= "  <order>";    
     $req .= "    <auth>";
     $req .= "      <customer>STHH932660</customer>";
     $req .= "      <account>hh_ikea</account>";
     $req .= "      <password>12345678a</password>";
     $req .= "      <session_id>e9805948cfc6e12c29b13ecc8c345ba440bc87e4b5ce2fe28308fd9f2a7baf32eea31499fd11d8b61f4459ef0998ecf8427e9dbd34ed41d8cd98f00b20fc40dd</session_id>";
     $req .= "      <costcenter_name>" . $cscName . "</costcenter_name>";
     $req .= "    </auth>";
     $req .= "    <no>" . $jobData["job"]["jb_id"] . "</no>";
     $req .= "    <hq>HH</hq>";
     $req .= "    <vehicle>";
     $req .= "      <type_no>" . $requestedVhtId . "</type_no>";
     $req .= "      <type_name></type_name>";
     $req .= "      <length></length>";
     $req .= "      <width></width>";
     $req .= "      <height></height>";
     $req .= "      <position></position>";
     $req .= "    </vehicle>";
     $req .= "    <ordertime>" . $jobData["job"]["jb_ordertime"] . "</ordertime>";
     $req .= "    <ordertimeUTC></ordertimeUTC>";
     $req .= "    <courier></courier>";
     $req .= "    <filter></filter>";
     $req .= "    <remark>IKEA</remark>";
     $req .= "    <courier_remark></courier_remark>";
     $req .= "    <gdc>";
     $req .= "      <val></val>";
     $req .= "      <val></val>";
     $req .= "    </gdc>";
     $req .= "    <stations>";
     $req .= "      <station>";
     $req .= "        <ware_from_to>0</ware_from_to>";
     $req .= "        <costcenter></costcenter>";
     $req .= "        <company>" . $jobData["tour"]["1"]["tr_comp"] . "</company>";
     $req .= "        <company2></company2>";
     $req .= "        <street>" . $jobData["tour"]["1"]["ad_street"] . "</street>";
     $req .= "        <houseno>" . $jobData["tour"]["1"]["tr_hsno"] . "</houseno>";
     $req .= "        <zipcode>" . $jobData["tour"]["1"]["ad_zipcode"] . "</zipcode>";
     $req .= "        <city>" . $jobData["tour"]["1"]["ad_city"] . "</city>";
     $req .= "        <special_remark><![CDATA[]]></special_remark>";
     $req .= "        <person></person>";
     $req .= "        <phone></phone>";
     $req .= "        <email></email>";
     $req .= "      </station>";
     $req .= "      <station>";
     $req .= "        <ware_from_to>1</ware_from_to>";
     $req .= "        <costcenter></costcenter>";
     $req .= "        <company>" . $jobData["tour"]["2"]["tr_comp"] . "</company>";
     $req .= "        <company2></company2>";
     $req .= "        <street>" . $jobData["tour"]["2"]["ad_street"] . "</street>";
     $req .= "        <houseno>" . $jobData["tour"]["2"]["tr_hsno"] . "</houseno>";
     $req .= "        <zipcode>" . $jobData["tour"]["2"]["ad_zipcode"] . "</zipcode>";
     $req .= "        <city>" . $jobData["tour"]["2"]["ad_city"] . "</city>";
     $req .= "        <special_remark><![CDATA[]]></special_remark>";
     $req .= "        <person></person>";
     $req .= "        <phone></phone>";
     $req .= "        <email></email>";
     $req .= "      </station>";
     $req .= "    </stations>";
     $req .= "  </order>";
     $req .= "</xml>";

     $req = urlencode($req);

     $url = 'https://sb.assecutor.de/tools/order_request.php/tools/order_request.php';
     $fields = array('orderReq' => urlencode($req));     
     foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
     rtrim($fields_string, '&');
     $ch = curl_init();
     curl_setopt($ch,CURLOPT_URL, $url);
     curl_setopt($ch,CURLOPT_POST, count($fields));
     curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
     if ($returnResponse != "") :
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, "1");
     endif;
     $result = curl_exec($ch);
     curl_close($ch);

     if (!($result === false)) :
        if ($returnResponse == "") :
           $retVal = "SENT_OK";
        else :
           $retVal = $result;
        endif;
     endif;
  endif;

  return $retVal;
}


function sendPushGoogle ($deviceToken, $data, $apiKey) {
	global $db, $PHP_SELF;
  global $jobData, $hq_id, $usr_id, $emp_id;

  $retVal = "NO_DATA";

  if ($deviceToken != "" && $data != "") :

     $curl = curl_init();

     if ($apiKey == "") :
        $apiKey = "AAAAjmkxUDc:APA91bELqVZT_HOBlBybhffDcVD_3qJPXLwTkMNQLsbh-GkU4oNTsNcwElP5XS112YGFs_cjieSnmShUlLx4JDoGoB85ygenXmVVJ3MU0G7sAMyXlmVmW1br7fq1RZvJz9IVbQf2kJ2k";
     endif;

     curl_setopt_array($curl, array(
       CURLOPT_URL => "https://fcm.googleapis.com/fcm/send",
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_ENCODING => "UTF-8",
       CURLOPT_MAXREDIRS => 10,
       CURLOPT_TIMEOUT => 30,
       CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
       CURLOPT_CUSTOMREQUEST => "POST",
       CURLOPT_POSTFIELDS =>
     "{ 
         \"data\": " . $data . ",
         \"to\" : \"$deviceToken\"
     }",
       CURLOPT_HTTPHEADER => array(
         "authorization: key=$apiKey",
         "content-type: application/json"
       ),
     ));
     
     $response = curl_exec($curl);
     $err = curl_error($curl);
     
     $info = curl_getinfo($curl);
     $statusCode = $info["http_code"];
     
     curl_close($curl);
     
     if ($err) :
       $retVal =  "cURL Error #:" . $err;
       // $retVal = "SENT_OK";
     else :
       $retVal = $statusCode . "\n" .$response;
     endif;
  endif;

  return $retVal;
}
?>
