<?php
require_once __DIR__ . "/../../../vendor/autoload.php";





function EGetData($data,$PayID){
  global $dbo;
  $dataarr = $dbo->DataArray($data,"`",$keyItem = "~");
  if(isset($dataarr[''.$PayID]))return $dataarr[''.$PayID];
  if(isset($dataarr['-1']))return $dataarr['-1'];
  return "";
}

function EInit($param){
 
  global $dbo;
  $transnums = generateTransInfoOnly();
  return ["Ref"=>$transnums[1]];



}

function ICurlPost($url,$data){
  $datastr = http_build_query($data);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_POST, count($data));
  curl_setopt($ch, CURLOPT_POSTFIELDS, $datastr);
  // Disable SSL verification
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  // Will return the response, if false it print the response
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Set the url
  curl_setopt($ch, CURLOPT_URL, $url);
  // Execute
  $rst = curl_exec($ch);
  //return ["Status"=>0,"DateTime"=>$params['RegDate'],"Ref"=>$params['Ref'],"Amt"=>$params['Amt'],"Message"=>$rst];			
  $rst = rtrim($rst, "</html>");
  $rst = trim($rst);
  curl_close($ch);

  return $rst;
}

function InitPayment($param = [])
{
 
  /* $publicKey =  "1PUB0277sNo9K94gCEZG49OJ4xv94beYazib67";
$secretKey = "1PRI0277B2G1Fju4DT8YtmeSzPLIxyY9Rlfqe6";
  // creating the transaction object
$Transaction = new Transaction( $publicKey );
$data = [
  "amount"=> (float)$param['Amt'],
  "currency"=> "NGN",
  "redirectUrl"=> $param['CALLBACKURL'],
  "transRef"=> $param['Ref'], //you can send your transaction ref or allow Credo generate for you
  "paymentOptions"=> "CARD",
  "customerEmail"=> $param['Email'],
  "customerName"=> $param["Name"],
  "customerPhoneNo"=> $param['Phone']
];
 $response = $Transaction->initiate($data, true); 
if(isset($response->redirectUrl)){
  $transRef = $response->transRef;
// redirect
// Http::redirect($response->redirectUrl);
$mk = '<script language="javascript">window.location = "'.$response->redirectUrl.'"</script>';
return ["Markup"=>$mk,"Data"=>$data,"Url"=>$response->redirectUrl];
} 
*/

$nmarr = explode(' ',$param["Name"]);
$inkobo = (float)$param['Amt'] * 100;
$body = [
  "amount" => $inkobo,
  "bearer" => 0,
  "currency" => "NGN",
  "callbackUrl" => $param['CALLBACKURL'],
  "channels"=> ["card", "bank"],
  "reference" => $param['Ref'],
  "paymentOptions" => "CARD,BANK",
  "customerFirstName" => $nmarr[0],
  "customerLastName" => isset($nmarr[1])?$nmarr[1]:"",
  "email" => $param['Email'],
  "customerPhoneNumber" =>$param['Phone']
];

// return ["Markup"=>json_encode($body),"Data"=>"","Url"=>""];
//return ["Error"=>$param['Amt']." - ".(float)$param['Amt']];

/* {
"amount": 15000,
"bearer": 0,
"callbackUrl": "https://example.com/",
"channels": [“card”, “bank”],
"currency": "NGN",
"customerFirstName": "John",
"customerLastName": "Wick",
"customerPhoneNumber": "2348032132100",
"email": "john.wick@credocentral.com",
"metadata": {
"bankAccount": "0114877128",
"customFields":[ {"variable_name": "gender", "value": "Male", "display_name": "Gender" } ]
},
"//reference": "mTL022NzzQ0 - This must be Unique, if not present we will generate one",
"//serviceCode": "201220045mG7mTL022zQ09 - If you have dynamic settlement service setup"
} */

$headers = [
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    'Authorization' => '0PUB0268AyMUfdlg21f14OmXTy025Dns',
    // 'Authorization' => '1PUB0277sNo9K94gCEZG49OJ4xv94beYazib67',
];

$client = new \GuzzleHttp\Client();

$response = $client->request('POST','https://api.public.credodemo.com/transaction/initialize', [
    'headers' => $headers,
    'json' => $body,
]);

$resbody = json_decode($response->getBody()->getContents(),true);

//return ["Markup"=>$resbody,"Data"=>["res"=>$response->getBody()->getContents()],"Url"=>""];
// return ["Markup"=>'<div>AAA JAJAJAJ</div>',"Data"=>$body,"Url"=>''];
 if(isset($resbody['status']) && $resbody['status'] == 200){
  
  $responsed = $resbody['data'];
// redirect
// Http::redirect($response->redirectUrl);
$mk = "<script language='javascript'>window.location = '".$responsed['authorizationUrl']."'</script>";
return ["Markup"=>$mk,"Data"=>$body,"Url"=>$responsed['authorizationUrl']];
}else{
  return ["Error"=>$resbody['message']];
} 
// return ["Markup"=>'<div>AAA JAJAJAJ</div>',"Data"=>json_encode($response),"Url"=>''];
  

  /* $data = [];
  $email = $data['email'] = $param['Email'];
  $accountCode = $data['accountCode'] = $param["ACCOUNTCODE"];
  $secretKey = $param['SECRETKEY'];
  $phone = $data['phone'] = $param['Phone'];
  $amount = $data['amount'] = $param['Amt'];
  $ref = $data['ref'] = $param['Ref'];
  $callbackUrl = $data['callbackUrl'] = $param['CALLBACKURL'];
  $checkSum = $data['checkSum'] = md5($email.$ref.$accountCode.$amount.$callbackUrl.$secretKey);
  $initUrl = $param['GATEWAYINITPAYMENTURL'];
  //print_r($param);exit();
  // die(json_encode($data));
  $curl = ICurlPost($initUrl, $data);
   //print_r($param);
   //die($curl);

  $res = json_decode($curl, true);
  if ($res['status'] == false) {
    return ["Error"=>$res['message']];
  }

  // $mk = $res['data']['payUrl'];

  $mk = '<script language="javascript">window.location = "'.$res['data']['payUrl'].'"</script>';
  return ["Markup"=>$mk,"Data"=>$data,"Url"=>$initUrl]; */
  
}

function FinishPayment($param = [])
{
//   exit(json_encode($param));
  return [1,$param['Ref'],"Successful",0,["DateTime"=>date("Y-m-d")]];
}

function RequeryPayment($param = [])
{
  $data = [];

  $ref = $data['ref'] = $param['REF'];
  $accountCode = $data['accountCode'] = EGetData($param["ACCOUNTCODE"],$param["PayID"]);
  $secretKey = $data['secretKey'] = $param['SECRETKEY'];
  $checkSum = $data['checkSum'] = md5($ref.$accountCode.$secretKey);
  $requeryUrl = $data['requeryUrl'] = $param['GATEWAYREQUERYURL'];

  $form =  "<form method='POST' action='".$requeryUrl."'>
  <input type='hidden' name = 'accountCode' value='".$accountCode."'>
  <input type='hidden' name = 'ref' value='".$ref."'>
  <input type='hidden' name = 'checkSum' value='".$checkSum."'>
  </form>
  <script language='javascript'>
  var form = document.forms[0];
  form.submit()</script>";

  return ["Markup"=>$form,"Data"=>$data,"Url"=>$requeryUrl];
}

?>