<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
//function to add accesscode
function AddAccessCode(){
	global $dbo;
	global $RegNo;
	global $studaccescode;
	global $ERegNo;
	global $JambNo;
	global $GenReg;
	//$studaccescode = trim($studaccescode);
	//global $updreg;
 //update accesscode
  //check if student exist in accesscode_tb
  $acexist = $dbo->RunQuery("SELECT JambNo from accesscode_tb where JambNo = '$RegNo' OR JambNo = '$GenReg'");
  $acexist = $acexist[1] > 0?true:false;
  if($acexist){ //update accesscode
  //if regno has changed update the regno in accesscode too
   // $updatearr = (int)$updreg == 1?array("JambNo"=>$ERegNo,"AccessCode" => $studaccescode):array("AccessCode" => $studaccescode);
	  $acupdate = $dbo->Updatedbtb("accesscode_tb",array("JambNo"=>$GenReg,"AccessCode" => $studaccescode),"JambNo = '$RegNo' OR JambNo = '$GenReg'");
	  if(is_array($acupdate)){
		  return $acupdate[1];
	  }else{
		  return -1;
	  }
  }else{
	  $acinsert = $dbo->Insert2DbTb(array("JambNo"=>$GenReg,"AccessCode" => $studaccescode),"accesscode_tb");
	  if($acinsert == "#"){
		  return "#";
	  }else{
		  return -1;
	  }
  }	
	
}

//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("../../../../".$paasp)){return 0;}
	 $move = rename("../../../../".$paasp,"../../../../epconfig/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("../../../../epconfig/UserImages/Student/{$sregfile}.jpg")){return 0;}
		$move = rename("../../../../epconfig/UserImages/Student/{$sregfile}.jpg","../../../../epconfig/UserImages/Student/{$regfile}.jpg");
		if($move){
			return 1;
		}else{
			return -1;
		}
	}else{ //delete the old passport
		unlink("../../../../epconfig/UserImages/Student/{$sregfile}.jpg");
	}
 }
 return 0;
}
//sleep(10);
if(isset($_POST['selstudid']) && isset($_POST['studregNo']) && isset($_POST['updreg'])){ //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");
  $RegNo = "";
  $updreg = (int)$_POST['updreg']; //get the type of update 
  $GenReg = $ERegNo == ""?$JambNo:$ERegNo; //set the general entered regno if Entered regno is not set use the Jamb No
  //confirm stud regno
  if($SRegNo == $GenReg){ //if user selected regno is entered regno
	  $RegNo = $GenReg;//set the operational regno to any of the two
  }else{ //if selected is not entered
	  if($updreg == 0){ //0 rep user entered regno is to be used/ which could be new insert or update if the regno exist
		  $RegNo = $GenReg;
	  }else{ //1 rep the operational regno is the selected one, hensce the user RegNo will be updated, which calls for a global update
		 $RegNo = $SRegNo; 
	  }
  }
  
  //work on jambno
  
 // $JambNo = $JambNo == ""?$RegNo:$JambNo;
  if($RegNo == $JambNo){//if jambno is same as regno
	  //$regnoCond = "RegNo = '$RegNo' OR JambNo = '$RegNo'";
	  //$regnoCond2 = "RegNo = '$RegNo'";
	  $regnoCond = "(RegNo = '$RegNo' && TRIM(RegNo) != '') OR (JambNo = '$RegNo' && TRIM(JambNo) != '')";
	  $regnoCond2 = "(RegNo = '$RegNo' && TRIM(RegNo) != '')";
  }else{ //if jambno is not same as regno
 
  //serarch all student that eiether has either the regno or jambno
    
	  //$regnoCond = "RegNo = '$RegNo' OR JambNo = '$JambNo' OR RegNo = '$JambNo'  OR JambNo = '$RegNo'";
	  //$regnoCond2 = "RegNo = '$RegNo' OR RegNo = '$JambNo'";
	 // $regnoCond = "(RegNo = '$RegNo' && TRIM(RegNo) != '') OR (JambNo = '$JambNo' && TRIM(JambNo) != '') OR (RegNo = '$JambNo' && TRIM(RegNo) != '') OR (JambNo = '$RegNo' && TRIM(JambNo) != '')";
	 $regnoCond = "(TRIM(RegNo) != '' AND (RegNo = '$RegNo' OR RegNo = '$JambNo')) OR (TRIM(JambNo) != '' AND  (JambNo = '$RegNo' OR JambNo = '$JambNo'))";
	  $regnoCond2 = "TRIM(RegNo) != '' && (RegNo = '$RegNo' OR RegNo = '$JambNo')";
  }
  
  //get the existence of the regno, include general entered RegNo (ERegNo or EJambNo)
  $exitcond = (int)$updreg == 0?$regnoCond:$regnoCond." OR RegNo = '$GenReg'  OR JambNo = '$GenReg'";
  $exist = $dbo->RunQuery("SELECT id from studentinfo_tb where ".$exitcond);
    $tot = $exist[1];
	
	if($tot > 1){
	 // echo "#Save Failed: Multiple Record Found :"."SELECT id from studentinfo_tb where ".$exitcond;
	  exit("#Save Failed: Multiple Record Found");	
	}
  $exist = $exist[1] > 0?true:false;
  
  //extract all data from the post array
  extract($_POST);
  /* [surnametxt] => INYANGUDOH
    [firstnametxt] => EMEM
    [othernametxt] => YOMMY
    [studDOB_day] => 12
    [studDOB_month] => 3
    [studDOB_year] => 1991
    [studgender] => 1
    [studstatus] => 0
    [studreligion] => 
    [studregNo] => 59035924AD
    [jambNo] => 49035924AD
    [studstudy] => 5
    [studfac] => 5
    [studdept] => 30
    [studprog] => 38
    [studlvl] => 2
    [modeentry] => 2
    [flatbtn_32250] => 
    [stateorig] => 3
    [lga] => ETINAN
    [nat] => 0
    [bdemail] => emyinyangudoh@gmail.com
    [studphone] => 07033587759
    [studaddr] => 29 NTIEDO UDOSEN STREET, OFF OBIO IMO LANE, UYO, AKWA IBOM STATE
    [nkname] => dorcas
    [nkphone] => 08066096978
    [nkaddr] => ifa atai
    [jambscor] => 0
    [olvrstxamtype1] => WAEC
    [olvrstxamtype2] => WAEC
    [olvrstxamyear1] => 2008
    [olvrstxamyear2] => 2011
    [olvrstschn1] => ETINAN INSTITUTE, ETINAN
    [olvrstschn2] => Martha Memorial Comprehensive Secondary School, Afaha Nsit
    [studReglvl] => 6
    [regDate_day] => 8
    [regDate_month] => 5
    [regDate_year] => 2015
    [adDate_day] => 2
    [adDate_month] => 3
    [adDate_year] => 2016
    [studaccescode] => yommybo 
    [olvelDet] => ETINAN INSTITUTE, ETINAN`~2008`~`~WAEC###Martha Memorial Comprehensive Secondary School, Afaha Nsit`~2011`~`~WAEC 
    [olvelRst] => ENGLISH LANGUAGE=C6;GOVERNMENT=E8;LITERATURE IN ENGLISH=B3;ECONOMICS=C4;MATHEMATICS=B3;AGRICULTURAL SCIENCE=C6;COMMERCE=D7###
    [selstudid] => 59035924AD
    [updreg] => 0
    [paasp] => */
	//set option array
	$GenderArr = array("M","F");
	$MarStArr = array("S","M");
	$NatArr = array("NIGERIAN","OTHERS");
	
	//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
		echo "#Invalid Level or Mode of Entry";
		exit;
	}
  //form the data array
  $data = array("RegNo"=>$ERegNo,
                "SurName"=>$surnametxt,
				"FirstName"=>$firstnametxt,
				"OtherNames"=>$othernametxt,
				"DOB"=>$studDOB_year."-".$studDOB_month."-".$studDOB_day,
				"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"=>$regDate_year."-".$regDate_month."-".$regDate_day,
				"AdminDate"=>$adDate_year."-".$adDate_month."-".$adDate_day,
				"JambAgg"=>(int)@$jambscor,
				"OlevelRstDetails"=>$olvelDet,
				"OlevelRst"=>$olvelRst,
				"RegLevel"=>$studReglvl,
				"ProgID"=>$studprog,
				"StudyID"=>$studstudy,
			"RegID"=>1);
  
  //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
if ($fileTmpLoc) { // if file not chosen
    $regfile = str_replace("/","_",$ERegNo);
	 $fn = "UserImages/Student/{$regfile}.jpg";
	if(move_uploaded_file($fileTmpLoc, "../../../../epconfig/".$fn)){
		 $data["Passport"] = "../epconfig/".$fn."?".mt_rand();
		 $loaded = true;
	} else {
		echo "#Operation Aborted: Cannot Upload Image";
		exit();
	}
}else{ //if no new file uploaded
  //if($SRegNo != $ERegNo){
	  $rSRegNo = str_replace("/","_",$SRegNo);
	  //$rERegNo = str_replace("/","_",$ERegNo);
	 // $paasp = "epconfig/UserImages/Student/{$rSRegNo}.jpg"; //the current passport
	  
 // }else{

 // }
}
  /*if(trim($paasp) != "" || (int)$updreg == 1){
	  //update passport path 
	  $regfile = str_replace("/","_",$ERegNo);
	  $data["Passport"] = "UserImages/Student/{$regfile}.jpg?".mt_rand();
  }*/
  
  //Update if regno exist and insert if not
  //start transaction
  $dbo->Begin(); //bigin transaction
  $report = ""; //what to display to the user
  $totupdate = 0;
  if($exist){ //update
        //check if user entered regno is not(i.e user change the regno) jambno, and user whant to add new or update
	  //if($JambNo != $ERegNo && $updreg == 0 && $SRegNo != $ERegNo){
		if($updreg == 0 && $SRegNo != $GenReg){ //GenReg Represent the enetered regno or jamb no
		  $existe = $dbo->RunQuery("SELECT id from studentinfo_tb where RegNo = '$GenReg' OR JambNo = '$GenReg'");
          $tote = $existe[1];
		  if($tote == 0){
			 // echo "#Save Failed: Invalid Registration Number, with a Valid Entrance Number";
	          exit("#Save Failed: Invalid Student");	
		  }
	
		  
	  }
	  if((int)$updreg == 1){ //if global update
	   // $rERegNo = str_replace("/","_",$_POST["studregNo"]);
	    $rERegNo = str_replace("/","_",$GenReg);
        $data["Passport"] = "../epconfig/UserImages/Student/{$rERegNo}.jpg"."?".mt_rand();
	  }
	  $update = $dbo->Updatedbtb("studentinfo_tb",$data,$regnoCond);
	  if(is_array($update)){ //check if update done 
	  if($update[1] > 1){
		  echo "#Technical Error - 023: Student Update Failed";
		  $dbo->Rollback();
		  exit;
	  }
		 $totupdate++; //add num of update to total update
	  }else{
		  echo "#Error - 024: Student Update Failed";
		  $dbo->Rollback();
		  exit;
	  }
	  
	  //check for global update
	  if((int)$updreg == 1){
		  //update in course reg
			$coursereg = $dbo->Updatedbtb("coursereg_tb",array("RegNo" => $GenReg),$regnoCond2);
			//update in order 
			$order = $dbo->Updatedbtb("order_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);
			if(!is_array($coursereg) || !is_array($order)  || !is_array($payhist)  || !is_array($result)  || !is_array($screening)){
				echo "#Error - 025: Student Global Update Failed";
		        $dbo->Rollback();
		        exit;
			}else{
				$totupdate += $coursereg[1] + $order[1] + $payhist[1] + $result[1] + $screening[1];
			}
	  }
	  //update accesscode
	  $accessC = AddAccessCode();
	  if($accessC === -1){
		  echo "#Error - 026: Access Code Update Failed";
		        $dbo->Rollback();
		        exit;
	  }else if($accessC === "#"){
		  $totupdate++;
	  }else{
		 $totupdate += (int)$accessC;
	  }
	  
	  //move passport
	  $pap = MovePassport();
	  if($pap != 0){
		  if($pap == -1){//if there is an error
			  echo "#Error -027: Passport Upload Failed";
			  $dbo->Rollback();
		      exit;
		  }
	  }
	  //check if update done
	  if($totupdate > 0){
		  //check if global or not
		  if((int)$updreg == 1){
			  $report = "*Student Record(Global) Updated Successfully";
		  }else{
			  $report = "*Student Record Updated Successfully";
		  }
	  }else{
		// $report = "No Update Done";
		$report = "*Student Record Updated Successfully";
	  }
  }else{ //student does not exist
	  $insert = $dbo->Insert2DbTb($data,"studentinfo_tb");
	  if($insert == "#"){
		  //update accesscode
		$accessC = AddAccessCode();
		if($accessC === -1){
			echo "#Error - 028: Access Code Update Failed";
				  $dbo->Rollback();
				  exit;
		}
		 /*$pap = MovePassport();
		  if($pap != 0){
			  if($pap == -1){//if there is an error
				  echo "#Error: Passport Upload Failed";
				  $dbo->Rollback();
				  exit;
			  }
		  }*/
		  if(!$loaded){
			  echo "#Error - 029: Adding New Student requires a New Passport Photograph";
				  $dbo->Rollback();
				  exit;
		  }
		  $report = "*Student Record Added Successfully";
	  }else{
		  echo "#Error - 030: Adding Student Failed ".$insert;
		  $dbo->Rollback();
		  exit;
	  }
  }
  
 $dbo->Commit();
 echo $report;

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


?>