<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
//AllowUser("Bdata");
//require("../../../../epconfig/GenScript/PHP/getinfo.php");
//function to add accesscode
function AddAccessCode($GenReg,$studaccescode,$Cond = ""){
	if(trim($studaccescode) == "" || trim($GenReg) == "")return true;
	global $dbo;
	$update = false;
	if(trim($Cond) != ""){
	  //check if access code record already exist
	  $ac = $dbo->SelectFirstRow("accesscode_tb","",$Cond);
	  if(is_array($ac)){
        $update = true;
	  }else{
		//$update = false;
		//cannot find student accesscode
		//return false;
	  }
	}
if($update){
	$acupdate = $dbo->Updatedbtb("accesscode_tb",array("JambNo"=>$GenReg,"AccessCode" => $studaccescode),$Cond);
	if(!is_array($acupdate)){
		return false;
	}else{
		return true;
	}
}else{
	$acinsert = $dbo->Insert2DbTb(array("JambNo"=>$GenReg,"AccessCode" => $studaccescode),"accesscode_tb");
	if($acinsert != "#"){
		return false;
	}else{
		return true;
	}
}
	
	
}

//function to move passport
function MovePassport(){
	global $paasp;
	global $ERegNo;
	global $updreg;
	global $SRegNo;
	global $loaded;
	global $GenReg;
	$regfile = str_replace("/","_",$GenReg);
	$sregfile = str_replace("/","_",$SRegNo);
  //move image if passport change
 if(isset($paasp) && trim($paasp) != ""){
	 if(!file_exists("../../../../../../".$_POST['SubDir']."Files/".$paasp)){return 0;}
	 $move = rename("../../../../../../".$_POST['SubDir']."Files/".$paasp,"../../../../../../".$_POST['SubDir']."Files/UserImages/Student/{$regfile}.jpg");
	 if($move){
		 return 1;
	 }else{
		 return -1;
	 }
 }else if((int)$updreg == 1){//global update, meaning regno has change and passport name has change in db
 //the file name must be change too
	if(!$loaded){
		if(!file_exists("../../../../../../".$_POST['SubDir']."Files/"."UserImages/Student/{$sregfile}.jpg")){return 0;}
		$move = rename("../../../../../../".$_POST['SubDir']."Files/"."UserImages/Student/{$sregfile}.jpg","../../../../../../".$_POST['SubDir']."Files/"."UserImages/Student/{$regfile}.jpg");
		if($move){
			return 1;
		}else{
			return -1;
		}
	}else{ //delete the old passport
		unlink("../../../../../../".$_POST['SubDir']."Files/"."UserImages/Student/{$sregfile}.jpg");
	}
 }
 return 0;
}

//function to update studentinfo_tb
function UpdateStudent($updateCond="",$oldpassp = "",$updatetype=true){
	global $dbo;
	global $SRegNo;
	global $ERegNo;
	global $JambNo;
	global $studdet;

	extract($_POST);
	$formdet = STUDREG();
	$studSet = StudentSettings();
$payreg = "";
if(is_array($studdet)){
	$payreg = trim($studdet['RegNo']) != ""?$studdet['RegNo']:$studdet['JambNo'];
	
}else{
   $payreg = $RegType == 'R'?$ERegNo:$JambNo;
   
}

if($studSet['AdminVerifyPay'] == 'TRUE'){ //if admin payment verification is enabled
$payacc = HasPaid($payreg,$formdet['PayID'],1,3,3,1,-1);
	if(trim($studaccescode) != "" && $payacc[0] != 1)return "#Invalid Operation: Student Accesscode can only be assigned when required payment is made";	
}


	if(trim($studaccescode) != ""){
		$studReglvl = 6;
	}else{
		$studReglvl = 2;

	}
	//studReglvl
	//set option array
	$GenderArr = array("M","F");
	$MarStArr = array("S","M");
	$NatArr = array("NIGERIAN","OTHERS");

	if(isset($studstartses) && (int)$studstartses > 0){
		$startSes = $studstartses;
	}else{
		return "#Invalid Start Session Specified";
	}
	//calculate startses
/* 	$lv = (int)$studlvl; //level
	$me = (int)$modeentry; //mode of entry
	$currSes = CurrentSes();
	$currSesID = (int)$currSes['SesID'];
	
	$startSes = $currSesID + $me - $lv;
	if($startSes < 1 || $startSes > $currSesID){ //invalid start ses
		return "#Invalid Level or Mode of Entry";
	} */
  //form the data array
  $data = array("RegNo"=>$ERegNo,
                "SurName"=>$surnametxt,
				"FirstName"=>$firstnametxt,
				"OtherNames"=>$othernametxt,
				"DOB"=>MysqlDateEncode($studDOB),
				"JambNo"=>$JambNo,
				"StateId"=>$stateorig,
				"LGA"=>$lga,
				"Gender"=>$GenderArr[$studgender],
				"MaritalStatus"=>$MarStArr[$studstatus],
				"Nationality"=>$NatArr[$nat],
				"Religion"=>$studreligion,
				"Phone"=>$studphone,
				"Email"=>$bdemail,
				"Addrs"=>$studaddr,
				"NName"=>$nkname,
				"NAddrs"=>$nkaddr,
				"Nphone"=>$nkphone,
				"StartSes"=>$startSes,
				"ModeOfEntry"=>$modeentry,
				"RegDate"=>date('Y-m-d'),
				"JambAgg"=>(int)@$jambscor,
				"OlevelRstDetails"=>$olvelDet,
				"OlevelRst"=>$olvelRst,
				"RegLevel"=>$studReglvl,
				"ProgID"=>$studprog,
				"StudyID"=>$studstudy,
				"ClassID"=>(int)$studclass,
				"AdmSes"=>(int)$admisionses,
				"AutoGenReg"=>trim($ERegNo) != ""?'TRUE':'FALSE',
				"Enable"=>$studEnable,
			"RegID"=>1);
			//exit($olvelRst);
			if($data['AutoGenReg'] == 'FALSE'){
				$data['AutoNum'] = 0;
			}

		/* 	if(trim($adDate_year) != "" && trim($adDate_month) != "" && trim($adDate_day) != ""){
				$data["AdminDate"]=$adDate_year."-".$adDate_month."-".$adDate_day;
			} */
			//
			if(trim($adDate) != ""){
				$data["AdminDate"]=MysqlDateEncode($adDate);
			}
			/* if(trim($regDate_year) != "" && trim($regDate_month) != "" && trim($regDate_day) != ""){
				$data["RegDate"]=$regDate_year."-".$regDate_month."-".$regDate_day;
			} */
			if(trim($regDate) != ""){
				$data["RegDate"]=MysqlDateEncode($regDate);
			}
			
			$regfile = $RegType == "R"?$ERegNo:$JambNo;
 $regfile = str_replace("/","_",$regfile);
 //$data['Passport'] = "UserImages/Student/{$regfile}.jpg";
 
 //if PID is 1 - meaning there is a selected Reg Number and it does not match with any of the Registration Num.
//it should try to update to the new reg number
 

 $dbo->Begin(); //bigin transaction

 if($updatetype){
	 //if it is an update operation and it is type 1 - meaning update the student info but not the regnos
	 //try to upload new passport if exist
	$passpu = UpdatePassport($oldpassp);
	//$dbo->Rollback();
	//return "#Image Test: ".$passpu;
	if($passpu === false  && $studSet['AdminPassportReq'] == 'TRUE'){
		$dbo->Rollback();
		return "#Operation Aborted: Cannot Upload Student Passport - Select a valid image";
	}
	if($studSet['AdminPassportReq'] != 'TRUE' && $passpu === false){
		$data['Passport'] = "";
	}else{
		$data['Passport'] = "UserImages/Student/{$regfile}.jpg";
	}
	
  if($PID == 1){
		 unset($data['RegNo']);
		 unset($data['JambNo']);
     unset($data['Passport']);
	}
	 $update = $dbo->Updatedbtb("studentinfo_tb",$data,$updateCond);
 if(is_array($update)){ //check if update done 
	if($update[1] > 1){ //if updated more than one student, terminate could be hackers
		$dbo->Rollback();
		return "#Technical Error - 023: Student Update Failed";
		//exit;
	}
	
	

	$GenReg = $RegType == 'R'?$ERegNo:$JambNo;
	if($PID == 1 || $PID == 4){
		$Cond = $_POST['RegType'] == "R"?"JambNo='".$ERegNo."'":"JambNo='".$JambNo."'";
	}else{
		$Cond = "JambNo = '{$SRegNo}'";
		$acupdate = AddAccessCode($GenReg,$studaccescode,$Cond);
	if(!$acupdate){
		$dbo->Rollback();
		return "#Error - 024: Access Code Update Failed";
	}
	}
	//update acesscode
	//$acupdate = $dbo->Updatedbtb("accesscode_tb",array("JambNo"=>$GenReg,"AccessCode" => $studaccescode),$Cond);
	

	if($PID == 2){ //if process 2 - meaning other table updated must be done (global update)
		//update in course reg
		$GenReg = $RegType == 'R'?$ERegNo:$JambNo;
		$regnoCond2 = "RegNo = '{$SRegNo}'";
			 $coursereg = $dbo->Updatedbtb("coursereg_tb",array("RegNo" => $GenReg),$regnoCond2);
			 //update in order 
			 $order = $dbo->Updatedbtb("order_tb",array("RegNo" => $GenReg),$regnoCond2);
			 //update in order_ex
			$order = $dbo->Updatedbtb("order_ex_tb",array("RegNo" => $GenReg),$regnoCond2);
			 //update in payment history
			 $payhist = $dbo->Updatedbtb("payhistory_tb",array("RegNo" => $GenReg),$regnoCond2);
			 //update in result tb
			 $result = $dbo->Updatedbtb("result_tb",array("RegNo" => $GenReg),$regnoCond2);
			 //update in screaning screening_tb
			 $screening = $dbo->Updatedbtb("screening_tb",array("RegNo" => $GenReg),$regnoCond2);
			 //update in wallet payment history
			$wallet = $dbo->Updatedbtb("wallet_tb",array("RegNo" => $GenReg),$regnoCond2);
			 if(!is_array($coursereg) || !is_array($order)  || !is_array($payhist)  || !is_array($result)  || !is_array($screening) || !is_array($wallet)){
				 
				 $dbo->Rollback();
				 return "#Error - 025: Student Global Update Failed";
				 //exit;
				 
			 }
			 $sregfile = str_replace("/","_",$SRegNo);
//rename the passport
$move = rename("../../../../../../".$_POST['SubDir']."Files/UserImages/Student/{$sregfile}.jpg","../../../../../../".$_POST['SubDir']."Files/UserImages/Student/{$regfile}.jpg");
$arr = [$SRegNo,$ERegNo,$JambNo];
$folder = ["JambResult","Origin","Waec"];
foreach($arr as $rrr){
	$rrr = str_replace("/","_",$rrr);
foreach($folder as $fd){
if(file_exists("../../../../../../".$_POST['SubDir']."Files/UserImages/{$fd}/{$rrr}.jpg")){
       rename("../../../../../../".$_POST['SubDir']."Files/UserImages/{$fd}/{$rrr}.jpg","../../../../../../".$_POST['SubDir']."Files/UserImages/{$fd}/{$regfile}.jpg");
	 }
}
}
	 }

	   $totupdate++; //add num of update to total update
	}else{
		$dbo->Rollback();
		return "#Error - 024: Student Update Failed - ".$update;
		//exit;
	}
	
	$rptstr = "*Student Record Updated Successfully";
 }else{ //insert operation
	$passpu = UpdatePassport();
	  if($passpu === false && $studSet['AdminPassportReq'] == 'TRUE'){
		$dbo->Rollback();
		return "#Operation Aborted: Cannot Upload Student Passport";
	}
	if($studSet['AdminPassportReq'] != 'TRUE' && $passpu === false){
		$data['Passport'] = "";
	}else{
		$data['Passport'] = "UserImages/Student/{$regfile}.jpg";
	}
	$insert = $dbo->Insert2DbTb($data,"studentinfo_tb");

	if($insert == "#"){//if inserted
	  

	$GenReg = $RegType == 'R'?$ERegNo:$JambNo;
	//add to accesscode
	//$acinsert = $dbo->Insert2DbTb(array("JambNo"=>$GenReg,"AccessCode" => $studaccescode),"accesscode_tb");
	$acinsert = AddAccessCode($GenReg,$studaccescode,"");
	  if(!$acinsert){
		$dbo->Rollback();
		return "#Error - 030: Adding Accesscode Faild";
	  }
    
	}else{ //if failed
		$dbo->Rollback();
		return "#Error - 029: Adding Student Failed -".$insert;
	}
	$rptstr = "*Student Record Added Successfully";
 }
 
	$dbo->Commit();
	
	return $rptstr;

}


//function to update passport
function UpdatePassport($oldpassp = ""){
	global $ERegNo;
	global $JambNo;
	//global $RegType;
	global $SRegNo;
    $RegType = $_POST['RegType'];
	//return $RegType;
  //check if passp has change or regno has changed
 // $imgfile = $_FILES['studpassp']['name'];
 $fileName = $_FILES["studpassp_image_file"]["name"]; // The file name
 $fileTmpLoc = $_FILES["studpassp_image_file"]["tmp_name"]; // File in the PHP tmp folder
 //$fileType = $_FILES["studpassp_image_file"]["type"]; // The type of file it is
 //$fileSize = $_FILES["studpassp_image_file"]["size"]; // File size in bytes
 //$fileErrorMsg = $_FILES["studpassp_image_file"]["error"]; // 0 for false... and 1 for true
 
 $loaded = false; //determine if a fresh passport uploaded
 $regfile = $RegType == "R"?$ERegNo:$JambNo;
 $regfile = str_replace("/","_",$regfile);
 if ($fileTmpLoc) { // if file not chosen
	  $fn = "UserImages/Student/{$regfile}.jpg";
	  //get the real filetype
	  if(!in_array(strtolower(trim(file_mime_type($fileTmpLoc,false))),["image/jpeg","image/jpg","image/pjpeg","image/gif","image/png"])){
		return false;
	  }

	  //return $fn;
	 if(move_uploaded_file($fileTmpLoc, "../../../../../../".$_POST['SubDir']."Files/".$fn)){
		  $data["Passport"] = $fn."?".mt_rand();
		   //remove the rand part
		   $oldpassparr = explode($oldpassp,"?");
		   $oldpassp = is_array($oldpassparr)?$oldpassparr[0]:$oldpassp;
//return "#".$fileTmpLoc;
		  $loaded = "Files/".$fn."?".mt_rand();
		  //remove old file if exist
		   if(trim($oldpassp) != "" && strtolower(trim($oldpassp)) != strtolower(trim($fn)) && file_exists("../../../../../../".$_POST['SubDir']."Files/".$oldpassp)){
             unlink("../../../../../../".$_POST['SubDir']."Files/".$oldpassp);
		  }
//rename in other folders
$arr = [$SRegNo,$ERegNo,$JambNo];
$folder = ["JambResult","Origin","Waec"];
foreach($arr as $rrr){
	$rrr = str_replace("/","_",$rrr);
foreach($folder as $fd){
if(file_exists("../../../../../../".$_POST['SubDir']."Files/"."UserImages/{$fd}/{$rrr}.jpg")){
       rename("../../../../../../".$_POST['SubDir']."Files/"."UserImages/{$fd}/{$rrr}.jpg","../../../../../../".$_POST['SubDir']."Files/"."UserImages/{$fd}/{$regfile}.jpg");
	 }
}
}
	 } else {
		 //return "#Operation Aborted: Cannot Upload Student Passport";
		 //exit();
	 }
 }else{

	if($oldpassp != ""){
		$loaded = "g";
	}

///return "#No Passport - ".$fileName;
 }
 return $loaded;
}


//exit($_POST['studregNo']);
//sleep(10);
if(isset($_POST['selstudid']) && isset($_POST['studregNo']) && isset($_POST['PID'])){ //if regno sent
//loop through all post data sent and make them save for mysql studaccescode
/*print_r($_POST);
exit;*/ 
//selstudid
  foreach($_POST as $key => $val){
	  $_POST[$key] = $dbo->SqlSafe($val);
  }
  $SRegNo = strtoupper(trim($_POST['selstudid']));
  $ERegNo = strtoupper(trim($_POST['studregNo']));
  $JambNo = strtoupper(trim($_POST['jambNo']));
  if($JambNo == "" && $ERegNo == "")exit("#Cannot Identify Student");
  //Proccess 1
  if($_POST['PID'] == 1){
	  //Add new Student if student does not exist, Update if student exist
	  //get operational RegNo
	  $Cond = $_POST['RegType'] == "R"?"RegNo='".$ERegNo."'":"JambNo='".$JambNo."'";
	  //check if student exist
	  $studdet = $dbo->SelectFirstRow("studentinfo_tb","",$Cond);

	  if(is_array($studdet)){ //if exist
		//perform an update
		$oldPassport = $studdet['Passport'];
		$updated = UpdateStudent("id=". $studdet['id'],$oldPassport);
		
	  }else{ //if not exist add as new student
		$updated = UpdateStudent("","",false);
	  }
	  exit($updated);
  }

  //Proccess 2
  if($_POST['PID'] == 2){
	$Cond = "RegNo = '{$SRegNo}' OR JambNo = '{$SRegNo}'";
	//check if student exist
	$studdet = $dbo->SelectFirstRow("studentinfo_tb","",$Cond);
	$rtnstr = "";
	if(is_array($studdet)){ //if student record exist
	  //update student info and other tables
	  $oldPassport = $studdet['Passport'];
	  $rtnstr = UpdateStudent("id=". $studdet['id'],$oldPassport);
	}else{
		$rtnstr = "#Internal Error: Reading Student Details Failed";
	}
   exit($rtnstr);
  }

  //process 3
  if($_POST['PID'] == 3){ //if no modification on RegNo or JambNo
	$Cond = "RegNo = '{$SRegNo}' OR JambNo = '{$SRegNo}'";
	//check if student exist
	$studdet = $dbo->SelectFirstRow("studentinfo_tb","",$Cond);
	$rtnstr = "";
	if(is_array($studdet)){ //if student record exist
	  //update student info and other tables
	  $oldPassport = $studdet['Passport'];
	  $rtnstr = UpdateStudent("id=". $studdet['id'],$oldPassport);
	}else{
		$rtnstr = "#Internal Error: Reading Student Details Failed";
	}
   exit($rtnstr);
  }

  //process 4
  if($_POST['PID'] == 4){ //if no selected Student
	$Cond = $_POST['RegType'] == "R"?"RegNo='".$ERegNo."'":"JambNo='".$JambNo."'";
	$studdet = $dbo->SelectFirstRow("studentinfo_tb","",$Cond);
	$rtnstr = "";
	if(is_array($studdet)){ //if student record exist
	  //update student info and other tables
	  $oldPassport = $studdet['Passport'];
	  $rtnstr = UpdateStudent("id=". $studdet['id'],$oldPassport);
	}else{//if not exist add as new student
		$rtnstr = UpdateStudent("","",false);
	}
   exit($rtnstr);
  }


  
  
  
  //"Passport"=>"",
			//update student passport photograph
			
			
			
}else{
	echo "#Error - 031: Cannot Identify Student"; 
}


?>