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


function EGetData($data,$PayID){
  global $dbo;
  $dataarr = $dbo->DataArray($data,"`","~");
  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 = [])
{
global $dbo;
$baseurl = $param['BASE'];
$serviceCode = trim($param['SERVICECODE']) != ""?EGetData($param['SERVICECODE'],$param['PayID']):"";
$publicKey = $param['KEY'];
$nmarr = explode(' ',$param["Name"]);
$inkobo = (float)$param['Amt'] * 100 ;
$info = json_decode($param['Info'],true);
//get Semester
 $ses = SessionName($param['Ses']);
$sem = SemesterName($param['SchSem']);
$part = $param['SemPart'] == 1?"Part":($param['SemPart'] == 2?"Balance":"Full");
$body = [
  "amount" => $inkobo,
  "bearer" => 1,
  "currency" => "NGN",
  "callbackUrl" => $param['CALLBACKURL'],
  "channels"=> ["card", "bank"],
  "customerFirstName" => array_shift($nmarr),
  "customerLastName" => implode(" ",$nmarr),
  "email" => $param['Email'],
  "customerPhoneNumber" =>$param['Phone'],
  "reference"=>$param['Ref'],
  "metadata" => [
    "ref"=> $param['Ref'],
    "customFields"=>[ 
      ["variable_name"=> "regno", "value"=> $param['RegNo'], "display_name"=> "Reg. Number" ],
      ["variable_name"=> "study", "value"=> $param["StudyName"], "display_name"=> "School" ],
      ["variable_name"=> "class", "value"=> $info['ProgName'] . " | ". $info['LevelName']. " (". $info['ClassName'].")", "display_name"=> "Class" ],
   ["variable_name"=> "ses", "value"=> $ses, "display_name"=> "Session" ],
      ["variable_name"=> "sem", "value"=> $sem, "display_name"=> "Term" ],
     ["variable_name"=> "sepmpart", "value"=> $part, "display_name"=> "Installation" ]
    ]
]

];

if(trim($serviceCode) != ""){
  $body['serviceCode'] = $serviceCode;
}
/* {"amount":44207000,"bearer":0,"currency":"NGN","callbackUrl":"http:\/\/live\/academa\/Payment\/finishproxy.php","channels":["card","bank"],"customerFirstName":"KejeM","customerLastName":"Yomi","email":"ab_keje@yahogo.com","customerPhoneNumber":"089757575858","metadata":{"ref":"1331510165","customFields":[{"variable_name":"regno","value":"AK2019\/AGR\/AEC\/001","display_name":"Reg. Number"}]}} */
//return ["Markup"=>$baseurl,"Data"=>$dbo,"Url"=>""];

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST',$baseurl.'/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'];
  //update the order Ref to newlew generated ref from credo
  if(trim($responsed['reference']) != ""){
    $updRef = $dbo->Update("order_tb",["ItemNo"=>$responsed['reference']],"TransNum = '{$param['Ref']}'");
    if(!is_array($updRef))return ["Error"=>"Updating Transaction Reference Failed"];
  }
// 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']];
} 

  
}

function FinishPayment($param = [])
{

 
  $baseurl = $param['BASE'];
  // $publicKey = $param['KEY'];
  $privateKey = $param['SECRET'];
  $headers = [
    'Content-Type' => 'application/json',
    'Accept' => 'application/json',
    // 'Authorization' => $publicKey,
    'Authorization' => $privateKey,
];
// exit(json_encode($param));

$TransNum = $param['TransNum'];
$RegNo = $param['RegNo'];


try{
$client = new \GuzzleHttp\Client();

$response = $client->request('GET',$baseurl."/transaction/{$param['reference']}/verify", [
    'headers' => $headers,
]);

}catch(Exception $e){
  return [0,$param['reference'],$e->getMessage(),0,["DateTime"=>date("Y-m-d")],[]];
}




$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){
  $upRef = "";
  $upRegNo = "";
  //verify details with local
  if(isset($resbody['data']['metadata']) && count($resbody['data']['metadata']) > 0){
    foreach($resbody['data']['metadata'] as $metadata){
      if($metadata['insightTag'] == "ref"){
        $upRef = $metadata['insightTagValue'];
      }
      if($metadata['insightTag'] == "regno"){
        $upRegNo = $metadata['insightTagValue'];
      }
    }
  }
  if(trim($upRef) != ""){
    if($TransNum === $upRef && $resbody['data']['status'] === 0 ){
     
      return [1,$param['reference'],$resbody['message'],0,["DateTime"=>date("Y-m-d")],$resbody['data'],$resbody['data']['debitedAmount']];
    }else{
      return [0,$param['reference'],$resbody['data']['status'].":Payment Failed",0,["DateTime"=>date("Y-m-d")],$resbody['data']];
    }
    
  }else{
    return [0,$param['reference'],"Reference Identification Failed",0,["DateTime"=>date("Y-m-d")],$resbody['data']];
  }

 }
//   exit(json_encode($param));
return [0,$param['reference'],$resbody['message'],0,["DateTime"=>date("Y-m-d")],$resbody['data']];
}

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

  // $Ref = $data['ref'] = $param['TransNum'];
  $reference = $param['ItemNo'];
  // $paydet = $dbo->SelectFirstRow("order_tb","*, ItemID as PayID","TransNum = '$Ref'");
  // if(is_array($paydet)){
    
    $rdirect = $param['CALLBACKURL']."?status=".((int)$param['Paid'] === 1?0:15)."&errorMessage=Approved&transAmount=".$param['Amt']."&currency=NGN&reference=".$reference;
    // return ["Error"=>$rdirect];
   return ["Markup"=>"<script language='javascript'>window.location = '".$rdirect."'</script>","Data"=>$param,"Url"=>$rdirect];
  // }else{
  //   return ["Error"=>"Fetching Transaction Details Failed - ".$Ref];
  // }
}

?>