<?php
session_start();
require_once("../phplb.php");
$strmanup = new StrFunctions();
if(isset($_GET['r'])){
  // $ret = $strmanup->_($_GET['r']);
  $ret = $_GET['r'];
  $cs = $_GET['cs'];
  $sk = "injesuswestand";
  $cks = md5($ret.$sk);
  if($cs != $cks){
    $err = "Data Integrity Check Failed";
  }else{
    // exit($ret);
    $RealData = json_decode($ret,true);
  if(!is_null($RealData)){
    if(isset($RealData['SubDir'])){
      $subdir = urldecode($RealData['SubDir']);
    }else{
      $subdir = urldecode($_SESSION['SubDir']);
    }

    $configdir = "../../../../".$subdir;
 
    require_once("../config.php");
    //die($configdir);
    //require_once("../../TaquaLB/Elements/Elements.php");
    require_once("../getinfo.php");
   
    $school = GetSchool();
    
    $err = "";
    $Ref = "";
    $SRefID = "";
    $RefIndicator = "Ref";
    $thirdpartyDet = [];
    //$_GET['err'] = json_encode($_REQUEST);
   
    if(isset($_GET['err'])){
        $err = $_GET['err'];
    }else{ //if no local error found
      //get the finish script
      if(!isset($_SESSION['Ref'])){
        //get all registered refids
      $refids = $dbo->Select("thirdparty_tb","");
      if(!is_array($refids)){
        $err = "Reading Registered Ref IDs Failed";
      }else{
          if($refids[1] < 1){
            $err = "No Gateway Found";
          }else{
            
              //get the ref
              while($RefID = $refids[0]->fetch_assoc()){
                  if(isset($RealData[$RefID['NotificationRefID']])){
                    $Ref = $RealData[$RefID['NotificationRefID']];
                    $SRefID = $RefID['NotificationRefID'];
                    $RefIndicator = $RefID['RefIndicator'];
                    $thirdpartyDet = $RefID;
                    break;
                  }
              }
          }
      }
      }else{ //if ref exist
         $Ref = $_SESSION['Ref']; 
      }
      
      if(trim($Ref) == ""){
        $err = "No Payment Reference Received";
    }else{
     
       $HasExpired = false;
        //get the payment details
        $paydet = $dbo->SelectFirstRow("order_tb","*, ItemID as PayID","ItemNo='$Ref' OR TransNum = '$Ref' OR ExpiredRef LIKE '%:$Ref:%'");
        if(!is_array($paydet)){
          $paydet = $dbo->SelectFirstRow("order_ex_tb","*, ItemID as PayID","ItemNo='$Ref' OR TransNum = '$Ref'",MYSQLI_ASSOC);
          $HasExpired = "ex";
        }else{
          //it is expired found in order_tb
          if($paydet['TransNum'] != $Ref && $paydet['ItemNo'] != $Ref){
            $HasExpired = "ord"; 
            $paydet['TransNum'] = $Ref;
          }
        }
        
        if(!is_array($paydet)){
            $err = "Invalid Payment Reference Received".$paydet;
        }else{
          
          //$Ref = $paydet['TransNum']; //update ref
          //get the third party details
          if(count($thirdpartyDet) == 0){
            //if thirdparty attached to the order, use the id to get the thirdparty details
           // exit(json_encode($paydet));
            if((int)$paydet['PayGatewayID'] > 0){
              $thirdpartyDet = $dbo->SelectFirstRow("thirdparty_tb","","ID=".$paydet['PayGatewayID']);
              if(!is_array($thirdpartyDet)){
                 //use the school set gate way ID
                 $GatewayID = (int)$school['PayThirdPartyID'];
                 if($GatewayID > 0){
                  $thirdpartyDet = $dbo->SelectFirstRow("thirdparty_tb","","ID=".$GatewayID);
                 }
              }
            }
          }
          
          if(is_array($thirdpartyDet) && count($thirdpartyDet) > 0){
            $gatewayparam = $thirdpartyDet['USE'] == "LIVE" ? $thirdpartyDet['PARAM'] : $thirdpartyDet['DEMO_PARAM'];
            $gatparams = $dbo->DataArray($gatewayparam);
              //get the gatway script
             // require_once "../../../".$thirdpartyDet['Script'];
             $scrarr = explode("/",$thirdpartyDet['Script']);
             
    require_once "Gateways/".$scrarr[count($scrarr) - 1];
              if(function_exists($thirdpartyDet['FinishPayMethod'])){
               
                //all param
                $params = array_merge($RealData,$paydet,$gatparams);
                 
                /*  $err = json_encode($params);
                exit($err); */
                $paid = call_user_func($thirdpartyDet['FinishPayMethod'],$params);
                //exit(json_encode($paid));
                // exit(json_encode($paid));
                   //$err = json_encode($paid);
                //exit($err); 
                if(!isset($paid[0]) || $paid[0] == 0){
                  $err = is_null($paid[2]) || !isset($paid[2])?"Unknown Error":$paid[3];
                  if(trim($err) == "")$err = "Unknown Error";
                }
                
              }else{
                $err = "Wrong Gateway Setup - ".$thirdpartyDet['FinishPayMethod'];
              }
          }else{
            //check payment
            //$err = json_encode(HasPaidRef($paydet['TransNum'],$paydet));
            $paid = HasPaidRef($Ref,$paydet);
            if($paid[0] == 0){
                $err = "Pay Error: ".$paid[5];
            }else{
              $paid = [1,$paydet['TransNum'],"Transaction Successfull",0,["Amt"=>$paydet['Amt'],"Bank"=>"ONLINE","Branch"=>"ONLINE","DateTime"=>date("Y-m-d")]];
            }
          }
    
          if($paid[0] == 1){
                        
            if($HasExpired == "ex"){ //if expired from order_ex_tb
              //bring it back
              unset($paydet['Issue']);
              unset($paydet['ID']);
              $info = json_decode($paydet['Info'],true);
              $paydet['ProgID'] = isset($info['ProgID'])?$info['ProgID']:0;
              $inst = $dbo->InsertID2("order_tb",$paydet);
            }
    
            if($HasExpired == "ord"){
              //update the Ref
              $inst = $dbo->Update("order_tb",$paydet,"ID=".$paydet['ID']);
            }
            //confirm if pay update done
            if(!is_array($dbo->SelectFirstRow("payhistory_tb","","TransID='{$paydet['TransNum']}' LIMIT 1",MYSQLI_ASSOC))){
              //$err = json_encode($paid[5])."aaaa";
              //if not updated from thirdparty script
              if(isset($paid[6]))$paydet['GWAmt'] = $paid[6];
              
              $Paidd = MakePaidByRef($paydet['TransNum'],$paydet,$paid[4]);
              //$Paidd = [1];
              //@@ Check if wallet payment, then update wallet_tb as required
              if(!is_array($Paidd)){
                $err = "Internal Error: Payment Update Failed";
              }
              //exit(json_encode($Paidd));
              if($Paidd[0] == 0){
                $err = $Paidd[5];
              }else{
                $err = "";
            } 
            }
          }
          
            
        }
    }
    }
  }else{
    $err = "INVALID PARAMETER";
  }
  }
  
  
}else{
  $err = isset($_GET['err'])?$_GET['error']:"INVALID PARAMETER";
}



?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Payment Response</title>
<link href="<?php echo $configdir.$dbo->Config['Require']; ?>FA4/css/font-awesome.min.css" media="all" type="text/css" rel="stylesheet"  />
<script src="../TaquaLB/Loader/Loader.min.js" loadtype="Premium;../../cportal/Resources/Javascripts/pay.js"  type="text/javascript" onComplete=""></script>
<script type="text/javascript">
function PrintOrder(orderid){
	_("pri").className = _("pri").className.Replace("print","cog fa-spin");
	//Pay.PrintPay('ItemNo='+orderid,function(){_("pri").className = _("pri").className.Replace("cog fa-spin","print")},true)
	PDFPrinter.Print("../Slip.php","folder=Payment&ItemNo="+escape(orderid)+"&paper=A4&orientation=P&MT=4&MB=30");
	
}

function Reload(){
	_("rei").classList.toggle("fa-spin");
	//Pay.Printer.Print('Bank/Slip.php?ItemNo='+orderid,function(){_("pri").className = _("pri").className.Replace("cog fa-spin","print")})
	
}

function loaded(){
/* 	var openwin = window.opener;
	if(openwin != null && typeof openwin != "undefined"){
		//putme, acceptance fee payment
		if(openwin._("verifybtn") != null){
			openwin._("verifybtn").click();
			openwin.focus();
			//alert('reload');
		}else if(openwin._("loadpaybtn") != null){//school fee payment
			var currentsel = openwin.Admin.Sel; //the current selected menu
			if(currentsel != null){
				currentsel.click();
			}
		}else if(openwin._("loadcoursebtn") != null){//school fee payment from cuorse reg
			openwin._("loadcoursebtn").click();
		}else if(openwin._("converifybtn") != null){//convocation payment
			openwin._("converifybtn").click();
		}
		
		
		
  } */

  if(localStorage.getItem('Reload') != null)localStorage.removeItem('Reload');
  if(localStorage.getItem('PayFinish') != null)localStorage.removeItem('PayFinish');
  localStorage.setItem('Reload','ReloadOnPaid');
  localStorage.setItem('PayFinish','TRUE');
  
}
</script>
<style media="all" type="text/css">
   body{
	   margin:0px;
	  font-family:"Segoe UI Light", "Segoe UI Semibold", "Segoe UI Semilight","Segoe UI", "Segoe UI Black" ;
	  font-weight:lighter;
	  padding:0px;
	  background-color:#EBEBEB;
	  /* background-image: url(../../images/App/Images/eduportareal.png);
	  background-position:right bottom;
	  background-repeat:no-repeat;
	  background-attachment:fixed; */
   }
   .logo{width:150px; height:150px; display:block; margin:auto; margin-top:10px;}
   h2{text-decoration:none; font-weight:normal; font-size:1.4em; display:block; width:95%; margin:auto; text-align:center; font-weight:600}
   #SchoolName{width:100%; text-align:center; margin-top:5px; font-size:1.1em; font-weight:600; margin-bottom:20px}

    .grpbx{border:rgba(0,0,0,.1) solid thin;background-color:#FAFAFA; min-width:200px; min-height:200px;border-radius:8px; overflow:hidden; max-width:400px; width:calc(100% - 40px); margin:auto; margin-top:40px; float:none; height:auto;
}.grpbx .grpbxinner{border:rgba(255,255,255,1) solid 1px; width:calc(100% - 12px); height:calc(100% - 12px); padding:5px;border-radius:8px;overflow:hidden; min-height:inherit; overflow:inherit;
}.grpbx .grpbxinner .grpbxtitle{ text-transform: uppercase; font-size:1.0em; font-weight:bold; color:rgba(0,0,0,.2); text-align:right; padding-right:10px; width:100%; float:right}
  table{border-collapse:collapse; border:#BCF3BD thin solid; background-color:#F3FEF1; font-size:0.9em; width:95%; margin-top:10px; font-size:0.8em; border-radius:4px}
  table.failed{border:#FDBFB0 thin solid; background-color:#FEEDE9;}
  tr, td{border: inherit; text-align:left}
  table tr.alt{background-color:#D7F9D2; }table.failed tr.alt{background-color:#FEDBD6; }
  td.val{font-weight:600}
  button{width:45%; text-align:center; color:#FFFFFF; background-color:#090; height:40px; border:none;background-color:#F15F2E;
	background-image:-webkit-linear-gradient(top,#F15F2E,#F4825B);
	background-image:-o-linear-gradient(top,#F15F2E,#F4825B);
	background-image:-moz-linear-gradient(top,#F15F2E,#F4825B);
	background-image:linear-gradient(top,#F15F2E,#F4825B); border-radius:4px; margin-top:20px; margin-bottom:20px; font-size:1.1em;}
	button.success{background-color:#379C1B;
	background-image:-webkit-linear-gradient(top,#379C1B,#44AE20);
	background-image:-o-linear-gradient(top,#379C1B,#44AE20);
	background-image:-moz-linear-gradient(top,#379C1B,#44AE20);
	background-image:linear-gradient(top,#379C1B,#44AE20);}
</style>

</head>
<body onLoad="">
<div class="grpbx">
 <div class="grpbxinner">
<img class="logo" src="<?php echo $dbo->Config['SubDir2'] . "Files/".$school['logo']; ?>" name="SchoolImg" alt=""  />
<h2 id="SchoolName"><?php echo $school['Name'] ?></h2>
	<div style="text-align: center;">
		<h2><?php echo trim($err) != ""?"Transaction Failed":"Transaction Successful" ?></h2>
		
         <table cellpadding="6" cellspacing="0" border="1" align="center" class="<?php echo trim($err) != ""?"failed":"" ?>">
         <?php
           if(isset($paydet['TransNum'])){
         ?>
            <tr> <td><?php echo $RefIndicator; ?>:</td><td class="val"><?php echo $paydet['TransNum']  ?></td> </tr>
            <tr class="alt"> <td>Transaction No:</td><td class="val"><?php echo $paydet['ItemNo']  ?></td> </tr>
            <tr> <td>Payment:</td><td class="val"><?php echo $paydet['ItemName']  ?></td> </tr>
            <tr class="alt"> <td>Amount:</td><td class="val"><?php echo number_format($paydet['Amt'],2)  ?></td> </tr>
            <?php if(isset($paydet['GWAmt']) && (float)$paydet['Amt'] != (float)$paydet['GWAmt']){  ?>
            <tr class="alt"> <td>Debited Amount:</td><td class="val"><?php echo number_format($paydet['GWAmt'],2)  ?></td> </tr>
            <?php } ?>
            <tr> <td>Reg. No:</td><td class="val"><?php echo $paydet['RegNo'];  ?></td> </tr>
            <?php
           }
            if(trim($err) != ""){
               ?>
<tr class="alt"> <td>Reason:</td><td class="val"><?php echo $err ?></td> </tr>
<?php
            }
            ?>
		  
         </table>
         <?php if(trim($err) == ""){  //if no error reload the page on the portal, to display updated details
            ?>
          
            <?php
         }
         ?>
         
		 <!-- <button id="prs" class="success" onClick="PrintOrder('<?php echo @$Ref ?>')"> <i id="pri" class="fa fa-print"></i> Print Invoice </button> -->
		 <?php if(trim($SRefID)!="") {  ?>
         <!-- <button id="pr" onClick="_('rei').classList.toggle('fa-spin');document.location = '?<?php echo $SRefID."=".$Ref ?>&rel=<?php echo mt_rand(1000000000,9999999999); ?>'"> <i id="rei" class="fa fa-sync"></i> Reload </button> -->
         <?php }else{ ?>
        <!-- <button id="pr" onClick="window.close()"> <i class="fa fa-times"></i> Close </button> -->
        
        <?php }
        
		//log payment $PayDes,$Message,$Type
		//LogPayment($logdescr,$mess,$thirdps);
		
		 ?>
     <button id="pr" onClick="window.close()"> <i class="fa fa-times"></i> Close </button>
          <script>loaded();</script>
	</div>
 </div>
 </div>
</body>
</html>