<?php 


//remita constants
require 'remita_constants.php';


//collect invoice id
$iid = $_SESSION['iida'];
	 
$orderID = "";
if( isset( $_GET['orderID'] )) {
$orderID = $_GET["orderID"];
}
$response_code ="";
$rrr = "";
$response_message = "";
//Verify Transaction
function remita_transaction_details($orderId){
		$mert =  MERCHANTID;
		$api_key =  APIKEY;
		$concatString = $orderId . $api_key . $mert;
		$hash = hash('sha512', $concatString);
		$url 	= CHECKSTATUSURL . '/' . $mert  . '/' . $orderId . '/' . $hash . '/' . 'orderstatus.reg';
		//  Initiate curl
		$ch = curl_init();
		// 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
		$result=curl_exec($ch);
		// Closing
		curl_close($ch);
		$response = json_decode($result, true);
		return $response;
	}
	if($orderID !=null){
		$response = remita_transaction_details($orderID);
		$response_code = $response['status'];
		if (isset($response['RRR']))
			{
			$rrr = $response['RRR'];
			}
		$response_message = $response['message'];
}


?>

<!--	<div style="text-align: center;">
		<?php //if($response_code == '01' || $response_code == '00') { ?>
		<h2>Transaction Successful</h2>
		<p><b>Remita Retrieval Reference: </b><?php //echo $rrr; ?><p>
		<?php // }else if($response_code == '021') { ?>
						<h2>RRR Generated Successfully</h2>
						<p><b>Remita Retrieval Reference: </b><?php //echo $rrr; ?><p>
		<?php //}	else{ ?>
						<h2>Your Transaction was not Successful</h2>
						<?php //if ($rrr !=null){ ?>
						 <p>Your Remita Retrieval Reference is <span><b><?php //echo $rrr; ?></b></span><br />
						<?php //} ?> 
						  <p><b>Reason: </b><?php //echo $response_message; ?><p>
		 <?php //}?>
	</div>-->
    
    
    

<ul class="breadcrumb">
    
        <li><a href="dashboard.php?act=payments&qlk=<?php echo md5(8); ?>">Payments</a> <span class="divider"></span> </li>
        <li><a href="dashboard.php?act=view_invoices&qlk=<?php echo md5(8); ?>&auth=<?php echo sha1(md5(2))?>&iid=<?php echo $iid; ?>">View Invoice</a> <span class="divider"></span> </li>


        <li class="active" > Payment Response <span class="divider"></span> </li>
        
        
</ul>


<div class="well"><!-- well starts -->


      <div class="row" style="padding-left:0px; padding-right:0px;">
      
                      <ul class="list-group">
                          <li class="list-group-item list-group-item-info">
                              <h5>PAYMENT STATUS</h5>
                          </li>
                      </ul>
                      
                      <div class="col-md-12">
                      
                      
                    



 <?php 
 
 
 //collect invoice id
 //if(isset($_POST['iid'],$_POST['qlk']))
 //{
	 
	 
	
	 //
//	
	// $level =  get_user_level($user_id); //get user level

	 
	 
	 //invoice to
	 $invoice_type  = get_invoice_type($iid);//get invoice type
	 $invoice_to = get_invoice_invoice_to($iid);
	 $pay_to = get_invoice_pay_to($iid); //get who to pay the invoce to
	 $invoice_for = get_invoice_for($iid); //get what the invoice is made for 
	 $title = get_invoice_title($iid); // get the invocie title
	 $description = get_invoice_desc($iid); //get the invoice desc
//	 $amount = get_invoice_amount($iid); //get the invocie amount
//	 $total_amount = get_invoice_total_amount($iid); //get invoice total amount
//	 $credit = get_invoiced_credit($iid); //get invoice credit
	 
//	 $payment_status = get_invoice_payment_status($iid); //get the invoice payment status

     
	 //pass invoice to user id
	$user_id =  $invoice_to;
	
	
		//$user = get_user_id();//get user
	//$level = '100'; //get user level
	$programme_type = get_user_programme_type_applied_for($user_id); //programme type
	$department = get_user_department_applied_for($user_id); //department
	$programme  = get_user_programme_applied_for($user_id);//programme
	
        $mode = 2; //programme mode 1 -  full time, 2 part time

	 
 
 //get current session 
 $session = get_current_session($id = 1); //get current session
 $session_title = get_session_title($session); //get session title
 
 //get current semester
// $semester = get_current_semester($id = 1); //get current semester
 //$semester_title = get_semester_title($semester); //get semester title
 
 

 
 
 
     $full_name = get_user_fullname($invoice_to);
	 $email = get_user_email($invoice_to);
	 $phone_no = get_user_phone_no($invoice_to);
 
  //collect matric number an dother student info
  $appno = get_user_application_number($invoice_to);
	 
	 
  //get the programme type
  //$programme_type = get_user_programme_type($invoice_to); //programme type

 

 if(isset($_POST['transaction_id']))
 {//begin if interswitch rep
 
          
		  
		  //demo key
		  //$json = file_get_contents('https://voguepay.com/?v_transaction_id='.$_POST['transaction_id'].'&type=json&demo=true');

		  
		  //live key
		  $json = file_get_contents('https://voguepay.com/?v_transaction_id='.$_POST['transaction_id'].'&type=json');
		  
		  $transaction = json_decode($json, true);
		  
		  
		  
		  
		  $merchant_id2 = $transaction['merchant_id'];
		  $tid = $transaction['transaction_id']; //transaction from vp
		  $em = $transaction['email']; //email for notification
		  $tot = $transaction['total'];  //total of the whole sum
		  
		  $tot_b = $transaction['total_paid_by_buyer'];  //total paid  by buyer
		  $tot_m = $transaction['total_credited_to_merchant'];  //total of paid to school
          $extra_tot_m = $transaction['extra_charges_by_merchant'];  //extra charges by merchant


		  $mref = $transaction['merchant_ref']; //transaction ref sent from the portal
		  $mem = $transaction['memo']; //description of the payment sent from the portal
		  $stat = $transaction['status']; // status returned  from the transaction by vp
		  $dat = $transaction['date']; // date the transaction was carried out
		  $refr = $transaction['referrer']; //referer url returned
		  $meth = $transaction['method']; //payment method by the customer
		  $cur = $transaction['cur']; //currency
		  
		  $fma = $transaction['fund_maturity']; //fund maturity

		  
		 
		  
		  
		  //collect report from success url
		  if(isset($_GET['is']))
		  {
			  $statt = $_GET['is'];//statt here is status of the returned url
		  }
		  
		  
		   //collect report from success url
		  if(isset($_GET['error']))
		  {
			  $statt = $_GET['error']; //statt here is status of the returned url
		  }

		  
		  
		  //finally if none of the above happens
		  echo vog_response_code($statt, $mref, $tid, $stat );
		  
		  
		  

		  
			
 
  
  		// $apprAmt = 3600000;
  
   		 $amt = $_SESSION['amntt']; // amount passed from the confirmation page this for the interswitch collagepay 
  
  
  		//store all the parameter above in db for logging
	
	
	
 
 
 
	   //now if response code 
	   //check if the payment is succesful
	   
	   if($_GET['is'] == 'success')
	   {
		
		
			   //check if the applicant doesnt exist
			   if(!applicant_id_exist_payments($invoice_to)) //in future add session to match exactly the candidate
			   {
			   
					  
					  $payment_year = date('Y');//payment year
	  
					  $qry44="INSERT INTO `applicants_fee_payments`
					  (`programme_type_id`,`department_id`,`programme_id`,  `applicant_id`, `payment_method`, `invoice_id`, `amount`, `date_added`, `mode`) 
					   VALUES ('$programme_type','$department','$programme','$invoice_to','1','$iid','$amt',NOW(),'$mode')";
					  
					   $rst44 =  mysqli_query($dbc, $qry44);
					  
					  if($rst44)//mysqli_affected_rows($dbc)
					  {
						//if done finally collect all info for receipt
						
						
						
						 //query
						  $q441 = "UPDATE invoices SET payment_status = 1 WHERE invoice_id = '$iid'"; //update invoice to paid where payment status is 1
						  $r441 = mysqli_query($dbc, $q441);
						  
						  if(mysqli_affected_rows($dbc))
						  //if($r441)
						  {//end of if update is successful
							
							 
							 echo '<br/><br/> <a target="_blank" href="create_app_payment_slip.php?qlk='.md5(8).'&me='.$invoice_to.'" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Click here to Print / Download Payment Receipt"><i class="glyphicon glyphicon-print"> </i> Print / Download Receipt</a>';
							 //clear some sessions
							 
							 
							 //$applicant_fee_payments_entered = true;
				
						  }
						  else
						  {
							 $msg =   '&nbsp;&nbsp;SERVER ERROR: Please try again.';
							header("Location: dashboard.php?act=view_invoices&error=".urlencode($msg)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
				
						  }//end of if invoice is updated
					
						
						
					  }
					  else
					  {
						 //else tell the admin to reprint
						  
						  $msg =  'System Error! We are sorry for inconvenience.Please Retry again. Thank you.';
						  header("Location: dashboard.php?act=view_invoices&error=".urlencode($msg)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
					  }
					  
			   }//end of if applicnt id exist in payment
			   else
			   {
							 echo '<br/><br/> <a target="_blank" href="create_app_payment_slip.php?qlk='.md5(8).'&me='.$invoice_to.'" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Click here to Print / Download Payment Receipt"><i class="glyphicon glyphicon-print"> </i> Print / Download Receipt</a>';
	  
			   }
		  
	  }//en dof json of response code 
 
 


 



			  $transaction_type = 0; //applicants
			  $transaction_for = 0; //application fee
			  $payment_method = 1; //1 for vogue pay
			  
			  
			  $iid2 = $iid;//pass invoice id
			  $title2 = $title;
			  $desc2 = $description;
			  
			 
			  //get payment status using 
			  $payment_status = get_payment_status_by_resp_code($statt);
			  //$amt = $amt / 100;
			  $amt = $tot;
			  
			  
			  
			  
			  
			  if($statt != '')
			  {
			  
			  
			    if($first_tid != '' && $mref != '')
			    {
				

			  
					  $qry23="UPDATE  `vogue_webpay_transaction_log`  SET  
					   `payment_method` = '$meth', `payment_status` = '$payment_status', `response_code` = '$stat', `response_description` = '$mem',
					   `total_paid_by_buyer` = '$tot_b',`total_credited_to_merchant` = '$tot_m',`extra_charges_by_merchant` = '$extra_tot_m',
					   `fund_maturity` = '$fma', `transaction_id` = '$tid',  `merchant_reference` = '$mref', `email` = '$em', `memo` = '$mem',
					   `referrer` = '$refr', `currency` = '$cur',  `transaction_date` ='$dat'
					   
					   WHERE transaction_reference = '$mref'";
						 
					  $rst23 =  mysqli_query($dbc, $qry23);
				  
					  //if(mysqli_affected_rows($dbc))
					  if($rst23)
					  {//end of if update is successful
					  
							 
							 
							 //clear some sessions
							 
							 //unset($_SESSION['iid']);
							 //unset($_SESSION['amnt']);
							 
							 
							
					  
					  
					  //do nothing for now
					  
					  }
					  else
					  {
						  $msg =   '&nbsp;&nbsp;SERVER ERROR: Transaction Log has issues, we are sorry for the incovenience.';
								
						 header("Location: dashboard.php?act=view_invoices&error=".urlencode($msg)."&qlk=".md5(8)."&iid=".$iid);
				  
					  }

 
				}//en dof if check
				
			  }
 
 
  }//end of if we have  response fromvogu pay
  
  
  
  
  
 if(isset($_GET["orderID"]))
 {//begin if interswitch rep
 
          
		  
		  
		  //finally if none of the above happens
		  echo remita_response_code($response_code, $rrr, $response_message, $orderID );
		  
		  
		  

  
  		// $apprAmt = 3600000;
  
   		 $amt = $_SESSION['amnttr']; // amount passed from the confirmation page this for the interswitch collagepay 
  
  
  		
	
 
	   //now if response code 
	   //check if the payment is succesful
	   
	   if($response_code == '00' || $response_code == '01')
	   {
		

						  
						 //check if the applicant doesnt exist
			   if(!applicant_id_exist_payments($invoice_to)) //in future add session to match exactly the candidate
			   {
			   
					  
					  $mode = 2; //programme mode 1 -  full time, 2 part time
					  
					  
					  $payment_year = date('Y');//payment year
	  
					  $qry44="INSERT INTO `applicants_nce_fee_payments`
					  (`mode`,`programme_type_id`,`department_id`,`programme_id`,`session`,`applicant_id`, `payment_method`, `invoice_id`, `amount`, `date_added`) 
					   VALUES ('$mode','$programme_type','$department','$programme','$session','$invoice_to','1','$iid','$amt',NOW())";
					  
					   $rst44 =  mysqli_query($dbc, $qry44);
					  
					  if($rst44)//mysqli_affected_rows($dbc)
					  {
						//if done finally collect all info for receipt
						
						
						
						 //query
						  $q441 = "UPDATE invoices SET payment_status = 1 WHERE invoice_id = '$iid'"; //update invoice to paid where payment status is 1
						  $r441 = mysqli_query($dbc, $q441);
						  
						  if(mysqli_affected_rows($dbc))
						  //if($r441)
						  {//end of if update is successful
							
							 
							 echo '<br/><br/> <a target="_blank" href="create_app_payment_slip.php?qlk='.md5(8).'&me='.$invoice_to.'" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Click here to Print / Download Payment Receipt"><i class="glyphicon glyphicon-print"> </i> Print / Download Receipt</a>';
							 //clear some sessions
							 
							 
							 //$applicant_fee_payments_entered = true;
				
						  }
						  else
						  {
							 $msg =   '&nbsp;&nbsp;SERVER ERROR: Please try again.';
							header("Location: dashboard.php?act=view_invoices&error=".urlencode($msg)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
				
						  }//end of if invoice is updated
					
						
						
					  }
					  else
					  {
						 //else tell the admin to reprint
						  
						  $msg =  'System Error! We are sorry for inconvenience.Please Retry again. Thank you.';
						  header("Location: dashboard.php?act=view_invoices&error=".urlencode($msg)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
					  }
					  
			   }//end of if applicnt id exist in payment
			   else
			   {
							 echo '<br/><br/> <a target="_blank" href="create_app_payment_slip.php?qlk='.md5(8).'&me='.$invoice_to.'" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Click here to Print / Download Payment Receipt"><i class="glyphicon glyphicon-print"> </i> Print / Download Receipt</a>';
	  
			   }

			///end of if application is successful and insert into students table  
	  }//en dof json of response code 
 
 


 


			//balane the transactions table


			  $transaction_type = 0; //applicants
			  $transaction_for = 0; //application fee fee
			  $payment_method = 1; //1 for remita pay epayments
			  
			  
			  $iid2 = $iid;//pass invoice id
			  $title2 = $title;
			  $desc2 = $description;
			  
			 
			  //get payment status using 
			  $payment_status = get_payment_status_by_resp_code($response_code);
			  //$amt = $amt / 100;
			  $amt = $tot;
			  
			  
			  
			  
			  
			  if($rrr != '')
			  {
			  
			  
			    if($rrr != '' && $orderID != '')
			    {
				
				
				//also balance the paid amount against expected and may be the transaction fee paid

			  
					  $qry23="UPDATE  `remita_webpay_transaction_log`  SET  
					   `payment_method` = '$payment_method', `payment_status` = '$payment_status', `response_code` = '$response_code', `response_description` = '$response_message',
					   `total_paid_by_buyer` = '$amt',`extra_charges_by_merchant` = '$extra_tot_m',
					    `transaction_id` = '$rrr',  `email` = '$email', `transaction_date` =NOW()
					   
					   WHERE transaction_reference = '$orderID'";
						 
					  $rst23 =  mysqli_query($dbc, $qry23);
				  
					  //if(mysqli_affected_rows($dbc))
					  if($rst23)
					  {//end of if update is successful
					  
							 
							 
							 //clear some sessions
							 
							 //unset($_SESSION['iid']);
							 //unset($_SESSION['amnt']);
							 
							 
							
					  
					  
					  //do nothing for now
					  
					  }
					  else
					  {
						  $msg =   '&nbsp;&nbsp;SERVER ERROR: Transaction Log has issues, we are sorry for the incovenience.';
								
						 header("Location: dashboard.php?act=view_invoices&error=".urlencode($msg)."&qlk=".md5(8)."&iid=".$iid);
				  
					  }

 
				}//en dof if check
				
			  }
 
 
  }//end of if we have  response from remita

 
 
 ?>
 


              
                
                	
      
      </div><!-- /.col md 12 -->
      
      
      </div><!-- /row-->
      
      <div class="clearfix"></div>

      
     
		
	
</div><!-- /.well -->	


 <br/><br/>
      
      <ul class="list-group">
          <li class="list-group-item list-group-item-info">
              <h5>TRANSACTION LOG</h5>
          </li>
      </ul>
      <div class="clearfix"></div>
      <div class="col-md-12">
      
      		<?php echo view_remita_pay_transaction_log($invoice_to, $transaction_type, $transaction_for);   ?>              

      </div>	
      
      <div class="col-md-12">
       
       <br/><br/><br/>
          
        <hr> 
       
       </div>
         
        
        <div class="col-md-12">
              <div class="col-sm-6  help-block">     
                    
                     
                     
<!--                     <img src="images/secured pay opt.png" class="img-responsive" />
-->           

                     <img src="images/remita-payment-logo-horizonal-opt.png" class="img-responsive" />
       
                  </div>    
              
                <div class="col-sm-6  help-block">     
                    <h4>For Support, Email or Call : </h4>
                    <h5><span class="glyphicon glyphicon-envelope"></span> eportals@ibbuconsult.com.ng </h5>
                     <h5><span class="glyphicon glyphicon-phone"></span> +234- 08142411717 OR 07068401380 </h5>
                     
                     
                     <img src="images/support.png" class="pull-right" />
                  
                  </div>
         </div>
           
