<?php
include 'remita_constants.php';
include 'includes/functions.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_admitted_to($user_id); //programme type
							$school = get_user_school_admitted_to($user_id); //school

							$department = get_user_department_admitted_to($user_id); //department
							$programme  = get_user_programme_admitted_to($user_id);//programme
							
							$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 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
							 
							 //get remita commission charges
							 $remita_share_fix = '300';
							 $vat_fix = '15';
							 
							 $extra_tot_m = $remita_share_fix + $vat_fix;
							 
							 
							 
							 $applicant_level = 'I'; //aplicant level 
						  
						  	 $application_number = get_user_application_number($invoice_to);
							 
							 
							 //run a query to convert the applicant to student
							 $q = "SELECT  `type_id`,`cart_id`, `school_id`, `department_id`, `programme_id`, `programme_type_applied_for`,`school_applied_for`, 
									 `department_applied_for`, `programme_applied_for`, `application_number`, `country_id`, `state_id`,
									 `lga_id`, `first_name`, `other_names`, `phone_no`, `pdf_file`, `gender`, `religion`, `nationality`, `day`, `month`, `year`,
									  `marital_status`, `email`, `place_of_birth`,  `address`, `permanent_address`, `image`, `H_status`, 
									  `blood_type`, `disability`,`mode_of_entry`, `medi`,  `town`,  `guardian_name`, `guardian_tel`, `guardian_address`, 
									  `guardian_relationship`, `sponsorship_type`, `sponsorship_name`, `sponsorship_address`, 
									  `admission_status`, `admission_criteria`, `date_admitted`, `admission_serial_no` 
									   
								  FROM `applicants_nce` 
									   
								  WHERE application_number = '$appno'";
									   
								$r = mysqli_query($dbc,$q);
								
								if(mysqli_num_rows($r) > 0)
								{//if succesfully fetch applicant recor
								
								
								
									 
									  //$initial = 0 ;
									  
									   $total_in_programme = get_total_programme_students($programme_type, $school, $programme, $applicant_level);
									   
									   $total_in_programme = $total_in_programme + 1; 
								
									   //generate matric number
									   $applicant_matric_number = generate_matric_number($programme_type, $school, $programme, $applicant_level, $total_in_programme);
							  			
										
									  
							  
									while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))//fetch data to be migrated
									{
										
										//chedk if student has been added already an collect info if added //review this dont depend on this function
										if(!application_number_exist($application_number, $applicant_level))
										{
										       //collect the variables for inserting and check for special string using 
											   $fn = mysqli_real_escape_string($dbc,$row['first_name']); //first name
											   $on = mysqli_real_escape_string($dbc,$row['other_names']);
											   $pn = mysqli_real_escape_string($dbc,$row['phone_no']);
											    $e = mysqli_real_escape_string($dbc,$row['email']);
												$add = mysqli_real_escape_string($dbc,$row['address']);
												$padd = mysqli_real_escape_string($dbc,$row['permanent_address']);
												$pob = mysqli_real_escape_string($dbc,$row['place_of_birth']);
												$gn = mysqli_real_escape_string($dbc,$row['guardian_name']);
												$gr = mysqli_real_escape_string($dbc,$row['guardian_relationship']);
												$gt = mysqli_real_escape_string($dbc,$row['guardian_tel']);
												$ga = mysqli_real_escape_string($dbc,$row['guardian_address']);
												$sn = mysqli_real_escape_string($dbc,$row['sponsorship_name']);
												$sa = mysqli_real_escape_string($dbc,$row['sponsorship_address']);
												$ac = mysqli_real_escape_string($dbc,$row['admission_criteria']);
												$med = mysqli_real_escape_string($dbc,$row['medi']);
												$spt = mysqli_real_escape_string($dbc,$row['sponsorship_type']);

												
												
							  
							  
												//get applicants info and insert into
												$qq = "INSERT INTO `students_nce_bu`(`id`,`cart_id`,`type_id`,`school_id`, `department_id`, `programme_id`, `programme_type_applied_for`,`school_applied_for` `department_applied_for`, 
												`programme_applied_for`, `country_id`, `state_id`, `lga_id`,  `first_name`, `other_names`, `phone_no`, `pdf_file`, `gender`, 
												`nationality`, `medi`,  `day`, `month`, `year`, `marital_status`, `number`, `application_number`, `username`, `password`, `email`,
												 `phone_number`,  `address`, `permanent_address`, `image`, `blood_type`, `disability`, `mode_of_entry`, `entry_year`, `award_in_view`,
												  `user_status`, `place_of_birth`, `religion`, `level`, `H_status`, 
												 `date_added`, `guardian_name`, `guardian_relationship`, `guardian_tel`, `guardian_address`, 
												 `sponsorship_type`, `sponsorship_name`, `sponsorship_address`, `admission_criteria`, `date_admitted`, `admission_serial_no`) 
												 VALUES (NULL,'".$row['cart_id']."','".$row['type_id']."','".$row['school_id']."','".$row['department_id']."','".$row['programme_id']."','".$row['programme_type_applied_for']."',
												 '".$row['school_applied_for']."','".$row['department_applied_for']."','".$row['programme_applied_for']."','".$row['country_id']."','".$row['state_id']."',
												 '".$row['lga_id']."','".$fn."','".$on."','".$pn."',
												 '".$row['pdf_file']."','".$row['gender']."','".$row['nationality']."','".$med."','".$row['day']."','".$row['month']."',
												 '".$row['year']."','".$row['marital_status']."',('$applicant_matric_number'),'".$row['application_number']."', ('$applicant_matric_number'),
												 '".md5('0000')."','".$e."',
												 '".$pn."','".$add."','".$padd."','".$row['image']."','".$row['blood_type']."',
												 '".$row['disability']."','".$row['mode_of_entry']."','2017','1','1','".$pob."','".$row['religion']."',
												 '$applicant_level','".$row['H_status']."',NOW(),'".$gn."','".$gr."',
												 '".$gt."','".$ga."','$spt','".$sn."',
												 '".$sa."', '".$ac."', '".$row['date_admitted']."', '".$row['admission_serial_no']."')";
										  
												 $rr = mysqli_query($dbc,$qq);
								
								
												  if(mysqli_affected_rows($dbc))//mysqli_affected_rows($dbc)
												  {
													  
													   $latest_student_id =  mysqli_insert_id($dbc); //do something like inserting in school fee payment for the latest student added
													   
													   if(!student_id_exist_payments($latest_student_id, $session, $semester))
													   {
														   if($payment_mode == 1)
														   {  //if instalment
														   
														   		$qqq = "INSERT INTO `school_fee_payments_nce_bu`(`id`, `programme_type_id`, `department_id`, `programme_id`, 
																	 `session`, `semester`, `student_id`, `payment_status`, `invoice_id`,
																	 `title`, `description`, `amount`, `date_added`) 
																	 VALUES (NULL,'".$row['type_id']."','".$row['department_id']."','".$row['programme_id']."',
																	'$session','$semester','$latest_student_id','1',
																	'$iid','$invoice_title','$invoice_desc','$invoice_amount',NOW())";
														   
														
														   }
														   else
														   {
															   //if full payment
															   
															   $qqq = "INSERT INTO `school_fee_payments_nce_bu`(`id`, `programme_type_id`, `department_id`, `programme_id`, 
																	 `session`, `semester`, `student_id`, `payment_status`, `invoice_id`,
																	 `title`, `description`, `amount`, `date_added`) 
																	 VALUES (NULL,'".$row['type_id']."','".$row['department_id']."','".$row['programme_id']."',
																	'$session','1','$latest_student_id','1',
																	'$iid','$invoice_title','$invoice_desc','$invoice_amount',NOW()),
																	(NULL,'".$row['type_id']."','".$row['department_id']."','".$row['programme_id']."',
																	'$session','2','$latest_student_id','1',
																	'$iid','$invoice_title','$invoice_desc','$invoice_amount',NOW())";
														   }
													   
															  
															   
															  $rrr = mysqli_query($dbc,$qqq);
													   
															  if($rrr)//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))
																{//end of if update is successful
																  
																  //here the display is handled when its 00

																  /// print receipt echo '<br/><br/> <a target="_blank" href="../students/create_payment_slip.php?qlk='.md5(8).'&s='.$session.'&me='.$latest_student_id.'&act=print_slip" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Click here to Print / Download Receipt"><i class="glyphicon glyphicon-print"> </i> Print / Download Receipt</a>';
																   

																   
																   //clear some sessions
																   
																   
																   
																   $school_fee_payments_entered = true;
													  
																}
																else
																{
																   echo $msg =   '&nbsp;&nbsp;SERVER ERROR: Error (01).';
																	//header("Location: dashboard.php?act=view_invoices3&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
																 echo  $msg2 =  'System Error!. We are sorry for inconvenience.Please Retry again. Thank you. Error (02)';
																 // header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg2)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
															  }
															  
													   }//end of if student doesnt exist
													  
															   
													  
													   
												  }
												  else
												  {
													  //show 
													   echo $msg3 =  'System Error!. We are sorry for inconvenience.Please Retry again. Thank you. Error (03)';
													   //header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg3)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
										  
												  }//end of if insert doesent work
									  
									  
									    }//end of if applicant doesnt exist system
									    else
									    {//but if applicant exist
										
										    //check for the applicant id in students table
											$student_id = get_student_id_application_number($application_number, $applicant_level);
											
											
											
											//check if he /she has made payment
											
											if(student_id_exist_payments($student_id, $session, $semester))
											{
												//echo '<br/><br/> <a target="_blank" href="../students/create_payment_slip.php?qlk='.md5(8).'&s='.$session.'&me='.$student_id.'&act=print_slip" class="btn btn-info" data-toggle="tooltip" data-placement="top" title="Click here to Print / Download Receipt"><i class="glyphicon glyphicon-print"> </i> Print / Download Receipt</a>';

											}
											else
											{//if appicant is in students table and hant made payment tell the banker to retry
												
												 echo  $msg4 =  'System Error!.Duplicate entry. We are sorry for inconvenience. Thank you. Error (04)';
												  //header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg4)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
										  
												
											}
											
											//if not pay
											
											
										
										
										}//take infor mation to display only
									  
								    }//end of while row fetching
									  
							  }//end if applicant record exist
							  else
							  {
								  //show 
								  echo $msg5 =  'System Error!.No Application Number attached. We are sorry for inconvenience. Thank you. Error (01)';
								 // header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg5)."&qlk=".md5(8)."&auth=".sha1(md5(2))."&iid=".$iid);
										  
							  }
								
								
							
							
							$transaction_type = 1; //applicants
							$transaction_for = 1; //registration fee
							$payment_method = 2; //1 for remita pay bank branch payment
							
							
							$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 != '')
							  {
							  
			  
							
									$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
									{
										echo $msg6 =   '&nbsp;&nbsp;SERVER ERROR: Transaction Log has issues, we are sorry for the incovenience. Error(06)';
											  
									   //header("Location: dashboard.php?act=view_invoices3&error=".urlencode($msg)."&qlk=".md5(8)."&iid=".$iid);
								
									}
			  
			   
							  }//en dof if check
							  
							}//end of RRR aint empty
 
							 
							
							
						}//end of if response code is successull
					}//end of for each
				exit('OK');
			}
		
		}
		catch (Exception $e) {
			exit('Not OK');
		}
?>		
		
<?php 


function remita_transaction_details($orderId){
	$mert =  "2547916";
	$api_key = "1946";
	$mode = "Test";
	$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;
}
?>