<?php
include_once 'includes/functions.php';
include_once 'Rremita_constantsRegFee.php';
//include_once 'includes/sms.php';

$json = file_get_contents('php://input');
$arr=json_decode($json,true);

	try {
		if($arr!=null)
		{
			foreach($arr as $key => $value)
			{
				$orderRef = $value['orderRef'];
				//Confirm transaction Status to be sure it is coming from Remita
				$response =  remita_transaction_details($orderRef);
				$response_code = $response['status'];
				$response_reason = $response['message'];
				$rrr = $response['RRR'];
			    $orderId =$response['orderId'];

				if($response_code == '01' || $response_code == '00')
				{
					//Payment Successful, You can Update Status to Paid here on Database;


					$user_id = get_invoice_to_using_txnref($orderId); //get the user id from

					//get the invoice details
					$iid = get_invoice_id_using_txnref($orderId);


					 $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
					 $invoice_amount =	$total_amount;

					//	 $credit = get_invoiced_credit($iid); //get invoice credit

					//	 $payment_status = get_invoice_payment_status($iid); //get the invoice payment status

					 //get invoice instalment or fulpayment
					 //$payment_mode = get_invoice_payment_mode($iid);
						//show payment mode
					 //$show_payment_mode = show_payment_mode($payment_mode);



					//get user programme details
					//$user = get_user_id();//get user
					//$level = '100'; //get user level
					$programme_type = get_user_programme_type_id($invoice_to); //programme type
					$school = get_user_school_id($invoice_to); //school
					$spt = get_user_sponsorship_type($user_id);
					$department = get_user_department_id($invoice_to); //department
					$programme  = get_user_programme_id($invoice_to);//programmeme

					$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
					$student_id = get_user_id($invoice_to);


					 //get current session
					 $current_session = get_current_session_4($id = 4); //get current session
					 $session_title = get_session_title($current_session); //get session title

					 //get current semester
					 $current_semester = get_current_semester($id = 1); //get current semester
					 $semester_title = get_semester_title($current_semester); //get semester title

					 //get remita commission charges
					 $remita_share_fix = '300';
					 $vat_fix = '15';

					 $extra_tot_m = $remita_share_fix + $vat_fix;
					  $payment_mode = get_invoice_payment_mode($iid);

					   // if($payment_mode == '1')
					   // {

							$qqq = "INSERT INTO `summer_school_fee_payments_nce`(`id`, `programme_type_id`,`school_id`, `department_id`, `programme_id`,
								 `session`, `semester`, `student_id`, `payment_status`,`payment_mode`,`payment_method`, `invoice_id`,`sponsorship_type`,
								 `title`, `description`, `amount`, `date_added`)
								 VALUES (NULL,'".$programme_type."','".$school."','".$department."','".$programme."',
								'$current_session','$current_semester','$student_id','1','$payment_mode','2',
								'$iid','$spt','$title','$description','$invoice_amount',NOW())";

					   // }
					   // else
					   // {
							// $qqq = "INSERT INTO `summer_school_fee_payments_nce`(`id`, `programme_type_id`,`school_id`, `department_id`, `programme_id`,
							// 	 `session`, `semester`, `student_id`, `payment_status`,`payment_mode`,`payment_method`, `invoice_id`,`sponsorship_type`,
							// 	 `title`, `description`, `amount`, `date_added`)
							// 	 VALUES (NULL,'".$programme_type."','".$school."','".$department."','".$programme."',
							// 	'$current_session','$current_semester','$student_id','1','$payment_mode','2',
							// 	'$iid','$spt','$title','$description','$invoice_amount',NOW())";
						 //
					   // }//else of mode of payment is full


						if(!has_paid_school_fee($student_id, $current_session, $current_semester))
						{

							$rrr2 = mysqli_query($dbc,$qqq);

							if($rrr2)//mysqli_affected_rows($dbc)
							{
								//if done finally collect all info for receipt
								//update invoice status to paid
								mysqli_query(dbc(),"UPDATE invoices SET payment_status = '1' WHERE invoice_id = '$iid'");


								//send sms


								//get user phone number
								$phone_no = get_user_phone_no($invoice_to);
								$fname = get_user_first_name($invoice_to);
								//attach sms message
								$sms_msg = 'Dear '.$fname.', your School Fees Payment was successful.'; //Please login with valid credentials to continue your application process.-';

							}
							else
							{
								  //show
							    $msg5 =  'System Error!. We are sorry for inconvinience.Please Retry again. Thank you.';
							 	/*
							  header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg5)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);*/
							}








								//check if he /she has made payment





						}
						else
						{//if appicant is in students table and hant made payment tell the banker to retry

							 $msg5 =  'Payment Already Done.';

						 		mysqli_query(dbc(),"UPDATE invoices SET payment_status = '1' WHERE invoice_id = '$iid'");

						/*  header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg5)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);*/

						}

						//if not pay







				  $transaction_type = 24; //returning student
				  $transaction_for = 24; //registration fee
				  $payment_method = 2; //Bank


				  $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_invoices3&error=".urlencode($msg)."&qlk=".md5(8)."&iid=".$iid);*/

							}


						}//en dof if check
					}

				}//end of if response code is successull
			}
	}//end of for each
		exit('OK');
	}catch (Exception $e) {
		exit('Not OK');
	}




function remita_transaction_details($orderId){
	$mert =  "2815618357";//2815618357
	$api_key = "527461";//527461
	$mode = "Live";
	$hash_string = $orderId . $api_key . $mert;
	$hash = hash('sha512', $hash_string);
	if( $mode == 'Test' ){
		$query_url = 'http://www.remitademo.net/remita/ecomm';
		}
	else if( $mode == 'Live' ){
		$query_url = 'https://login.remita.net/remita/ecomm';
		}
	$url 	= $query_url . '/' . $mert  . '/' . $orderId . '/' . $hash . '/' . 'orderstatus.reg';
	$result = file_get_contents($url);
    $response = json_decode($result, true);
    return $response;
}
?>
