<?php
include_once 'includes/functions.php';
include_once 'remita_constants_sf.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
    						 $invoice_title = get_invoice_title($iid); // get the invocie title
    						 $invoice_desc = 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;
								 $type_id = get_type_id($iid);

								 if($type_id==1)
								 {

								 	$full_name= get_user_fullname_prence($invoice_to);
								 	$U_addres = get_user_address_prence($invoice_to);
								 	$U_state = show_state(get_user_state_id_prence($invoice_to));
								 	$email = get_user_email_prence($invoice_to);
								 	$phone_no = get_user_phone_no_prence($invoice_to);
								 	//pass invoice to user id
								 	$user_id = $invoice_to;
								 	//collect matric number
								 	$m_no = get_user_mat_no_prence($user_id);
								 	$programme_type = get_user_programme_type_id_prence($user_id); //programme type
								 	$department = get_user_department_id_prence($user_id); //department
								 	$programme = get_user_programme_id_prence($user_id); //programme
								 }else if($type_id==2)
								 {
								 	$full_name= get_user_fullname_nce($invoice_to);
								 	$U_addres = get_user_address_nce($invoice_to);
								 	$U_state = show_state(get_user_state_id_nce($invoice_to));
								 	$email = get_user_email_nce($invoice_to);
								 	$phone_no = get_user_phone_no_nce($invoice_to);
								 	//pass invoice to user id
								 	$user_id = $invoice_to;
								 	//collect matric number
								 	$m_no = get_user_mat_no_nce($user_id);
								 	$programme_type = get_user_programme_type_id_nce($user_id); //programme type
								 	$department = get_user_department_id_nce($user_id); //department
								 	$programme = get_user_programme_id_nce($user_id); //programme
								 }else if($type_id==3)
								 {

								 	$full_name= get_user_fullname_duap($conn_2, $invoice_to);
								 	$U_addres = get_user_address_duap($conn_2, $invoice_to);
								 	$U_state = show_state(get_user_state_id_duap($conn_2, $invoice_to));

								 	$payment_status = get_invoice_payment_status($iid); //get the invoice payment status
								 	$invoice_expire_date = get_invoice_exp_date($iid);
								 	$email = get_user_email_duap($conn_2, $invoice_to);
								 	$phone_no = get_user_phone_no_duap($conn_2, $invoice_to);
								 	//pass invoice to user id
								 	$user_id = $invoice_to;
								 	//collect matric number
								 	$m_no = get_user_mat_no_duap($conn_2, $user_id);
								 	$programme_type = get_user_programme_type_id_duap($conn_2, $user_id); //programme type
								 	$department = get_user_department_id_duap($conn_2, $user_id); //department
								 	$programme = get_user_programme_id_duap($conn_2, $user_id); //programme
								 }else if($type_id==4)
								 {

								 	$full_name= get_user_fullname_duap_udus($conn_2, $invoice_to);
								 	$U_addres = get_user_address_duap_udus($conn_2, $invoice_to);
								 	$U_state = show_state(get_user_state_id_duap_udus($conn_2, $invoice_to));
								 	$email = get_user_email_duap_udus($conn_2, $invoice_to);
								 	$phone_no = get_user_phone_no_duap_udus($conn_2, $invoice_to);
								 	//pass invoice to user id
								 	$user_id = $invoice_to;
								 	//collect matric number
								 	$m_no = get_user_mat_no_duap_udus($conn_2, $user_id);
								 	$programme_type = get_user_programme_type_id_duap_udus($conn_2, $user_id); //programme type
								 	$department = get_user_department_id_duap_udus($conn_2, $user_id); //department
								 	$programme = get_user_programme_id_duap_udus($conn_2, $user_id); //programme
								 }else if($type_id==5)
								 {

								 	$full_name= get_user_fullname_summer($invoice_to);
								 	$U_addres = get_user_address_summer($invoice_to);
								 	$U_state = show_state(get_user_state_id_summer($invoice_to));

								 	$email = get_user_email_summer($invoice_to);
								 	$phone_no = get_user_phone_no_summer($invoice_to);
								 	//pass invoice to user id
								 	$user_id = $invoice_to;
								 	//collect matric number
								 	$m_no = get_user_mat_no_summer($user_id);
								 	$programme_type = get_user_programme_type_id_summer($user_id); //programme type
								 	$department = get_user_department_id_summer($user_id); //department
								 	$programme = get_user_programme_id_summer($user_id); //programme
								 }else if($type_id==6)
								 {

								 	$full_name= get_user_fullname_lvsp($invoice_to);
								 	$U_addres = get_user_address_lvsp($invoice_to);
								 	$U_state = show_state(get_user_state_id_lvsp($invoice_to));

								 	$email = get_user_email_lvsp($invoice_to);
								 	$phone_no = get_user_phone_no_lvsp($invoice_to);
								 	//pass invoice to user id
								 	$user_id = $invoice_to;
								 	//collect matric number
								 	$m_no = get_user_mat_no_lvsp($user_id);
								 	$programme_type = get_user_programme_type_id_lvsp($user_id); //programme type
								 	$department = get_user_department_id_lvsp($user_id); //department
								 	$programme = get_user_programme_id_lvsp($user_id); //programme
								 }





    						 //get current session
    						 //$session = get_current_session($id = 1); //get current session
							 $session = 6;
    						 $session_title = get_session_title($session); //get session title




    					   $remita_share_fix = '300';
    					   $vat_fix = '15';


    					   $extra_tot_m = $remita_share_fix + $vat_fix;



							 ///check if he / she has paid fee
							if(has_paid_hostel_fee($user_id,$session))
							{

											echo '<li class="list-group-item list-group-item-info"><h3>Payment already processed</h3></li><br>';

							}
							else
							{
								$payment_year = date('Y');//payment year


								$qqq1 = "INSERT INTO `hostel_fee_payments`(`id`, `programme_type_id`, `department_id`, `programme_id`,
								`session_id`, `semester_id`, `student_id`, `payment_status`, `invoice_id`,
								`title`, `description`, `amount`, `date_added`)
								 VALUES (NULL,'$programme_type','$department','$programme',
								 '$session','0','$invoice_to','1', '$iid','$invoice_title','$invoice_desc','$invoice_amount',NOW())";

								$rrr1 = mysqli_query($conn_1,$qqq1);

								if($rrr1)//mysqli_affected_rows($dbc)
								{
								//if done finally collect all info for receipt

										$q441 = "UPDATE hostel_allocation SET `status` = 1 WHERE student_id = '$invoice_to' AND session_id = '$session'";
										$r441 = mysqli_query($conn_1, $q441);

										//query
										$q442= "UPDATE hostel_invoices SET payment_status = 1 WHERE invoice_id = '$iid'"; //update invoice to paid where payment status is 1
										$r442 = mysqli_query($conn_1, $q442);

										if(mysqli_affected_rows($conn_1))
										{//end of if update is successful

										//here the display is handled when its 00

												//echo '&nbsp;&nbsp;&nbsp;<a class="btn btn-success"  href="create_sma_payment_slip.php?me='.$user_id.'&s='.$session.'&myid='.md5('fuckusha1sha1').'."   data-toggle="tooltip" data-placement="top" title="Download / Print  ">Click here to  DOWNLOAD / PRINT </a>';

												echo '<li class="list-group-item list-group-item-info"><h3>Payment succesfully processed</h3></li><br>';


										 //clear some sessions


										 $school_fee_payments_entered = true;

										}
										else
										{
												echo $msg =   '&nbsp;&nbsp;SERVER ERROR1: Please try again.';
										//header("Location: dashboard.php?act=view_invoices_sma&error=".urlencode($msg)."&qlk=".md5(2)."&auth=".sha1(md5(2))."&iid=".$iid);

										}//end of if invoice is updated

								}
								else
								{
									echo $msg =   '&nbsp;&nbsp;SERVER ERROR: Please try again .(2)';

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

								}//end of if inserted



							}//end of if he / she has paid school




    				  $transaction_type = 5; //applicants
    				  $transaction_for = 5; //registration fee
    				  $payment_method = 3; //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 = $total_amount;


    					if($rrr != '')
    					{


    					    if($rrr != '' && $orderId != '')
    					    {

    							//also balance the paid amount against expected and may be the transaction fee paid


    							$qry23="UPDATE  `hostel_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($conn_1, $qry23);


    							  //if(mysqli_affected_rows($dbc))
    							if($rst23)
    							{
    								//end of if update is successful


    									 $response_code = '';
                            		    $rrr = '';
                            		    $orderId = '';
    									 //clear some sessions

    									 //unset($_SESSION['iid']);
    									 //unset($_SESSION['amnt']);



    							  //do nothing for now

    							}else{
    								 echo $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 =  "4012912825";//2815618357
	$api_key = "Y71O2FOB";//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;
}
?>
