<?php session_start();
include("dbcon/connect.php");

if(isset($_POST['admin_login'])){
$pass=sha1(trim($_POST['password']));
$pes=mysqli_query($con,"select * from portal_admin where email='".$_POST['email']."' AND (password='$pass' OR password1='$pass')");
 if(mysqli_num_rows($pes)>0){
$row=mysqli_fetch_array($pes);
$_SESSION['delsuresultadminid']=$row['id'];		
mysqli_query($con,"update portal_admin set initial_login='".$row['final_login']."', final_login='$date' where id='".$_SESSION['delsuresultadminid']."'");			
	echo '<script>
	location.href="dashboard.php"
	</script>';
}else{
	echo '<div class="alert alert-danger alert-dismissable" >
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> OPPS! Incorrect login details.</p>
					<div class="clearfix"></div>
										</div>';
}
}

if(isset($_SESSION['delsuresultadminid'])){
$ddd=mysqli_query($con,"select * from portal_admin where id='".$_SESSION['delsuresultadminid']."'");
$adm=mysqli_fetch_assoc($ddd);

}

if(isset($_POST['reset_password'])){
	$pass='PROFILE'.substr(str_shuffle("0123456789"),0,4);
	$crs=mysqli_query($con,"update student set password='".sha1($pass)."' where id='".$_POST['reset_password']."'");
	if($crs){
		echo '<script>
	alert("Password successfully reset to '.$pass.'")
	location.href="student.php"
	</script>';
	}else{
			echo '<div class="alert alert-danger alert-dismissable" >
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> OPPS! Unable to complete operation, please try again later.</p>
					<div class="clearfix"></div>
										</div>';
	}
}

if(isset($_POST['hod_control'])){
	
	$emm=explode("-",$_POST['hod_control']);
	// head_access = head_id 	course_upload 	login_access 
	
	$bov=mysqli_query($con,"select * from head where id='".$emm[0]."'");
	$jec=mysqli_fetch_assoc($bov);
	
	$bv=mysqli_query($con,"select * from head_access where head_id='".$emm[0]."'");
	
	/////////// login access control
	if($emm[1]=='login_access'){
		
		if($emm[2]=='disable'){
			
			if(mysqli_num_rows($bv)==0){
				$sqli=mysqli_query($con,"insert into head_access(head_id,course_upload,login_access) values('".$emm[0]."',0,0)");
			}else{
				$sqli=mysqli_query($con,"update head_access set login_access=0 where head_id='".$emm[0]."'");
			}
			
		}else{
			
			if(mysqli_num_rows($bv)==0){
				$sqli=mysqli_query($con,"insert into head_access(head_id,course_upload,login_access) values('".$emm[0]."',0,1)");
			}else{
				$sqli=mysqli_query($con,"update head_access set login_access=1 where head_id='".$emm[0]."'");
			}
			
		}	
		/////////// end login access control   //id="'.$smm['id'].'-login_access-disable"
	}else if($emm[1]=='course_upload'){
		
		if($emm[2]=='disable'){
			
			if(mysqli_num_rows($bv)==0){
				$sqli=mysqli_query($con,"insert into head_access(head_id,course_upload,login_access) values('".$emm[0]."',0,0)");
			}else{
				$sqli=mysqli_query($con,"update head_access set course_upload=0 where head_id='".$emm[0]."'");
			}
			
		}else{
			
			if(mysqli_num_rows($bv)==0){
				$sqli=mysqli_query($con,"insert into head_access(head_id,course_upload,login_access) values('".$emm[0]."',1,1)");
			}else{
				$sqli=mysqli_query($con,"update head_access set course_upload=1, login_access=1 where head_id='".$emm[0]."'");
			}
		}
		
	}else{ 
			$sqli='';
	}
	
	if($sqli){
		echo '<script>
		alert("Operation Executed Successfully!")
		window.location="department.php"
		</script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissable" >
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> OPPS! Unable to complete operation, please try again later.</p>
					<div class="clearfix"></div>
										</div>';
	}
	
}


if(isset($_POST['add_notification'])){
	
	
	$ooo = mysqli_query($con,"select id from notification_result where matric_no='".trim($_POST['matric_no'])."'");
	$oop = mysqli_query($con,"select * from senate_status where matric_no='".trim($_POST['matric_no'])."'");
	$ooq = mysqli_query($con,"select * from student where matric_no='".trim($_POST['matric_no'])."'");
	
	if(mysqli_num_rows($ooq)==0){
	
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>OOPS:</strong> Invalid student matriculation number ...
              </div>';
	
	}else if(mysqli_num_rows($oop)==0){
	
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>OOPS:</strong> Student is yet to be pronounced as graduate ...
              </div>';
	
	}else if(mysqli_num_rows($ooo)>0){
	
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>OOPS:</strong> Student notification of result already processed...
              </div>';
	
	}else{
	
	$ata = mysqli_query($con,"select id from notification_result");
	$ref_no = 'INSPIRE/REG/'.  sprintf('%02d', (mysqli_num_rows($ata)+1));
	
	$pin=substr(str_shuffle("0123456789ADCDEFGHIJKLMONPQRSTUVWXYZ"),0,8);
	
	$stu = mysqli_fetch_assoc($ooq);
	$sen = mysqli_fetch_assoc($oop);
	
	if(strtolower($sen['student_category'])=='ond'){
		$degree='National Diploma';
	}else if(strtolower($sen['student_category'])=='hnd'){
		$degree='Higher National Diploma';
	}else{
		$degree=$sen['student_category'];
	}
	
if($sen['cgpa']>3.50){
	$class_of_degree='DISTINCTION';
}else if($sen['cgpa']<3.50 && $sen['cgpa']>2.99){
	$class_of_degree='UPPER CREDIT';
}else if($sen['cgpa']<3.00 && $sen['cgpa']>2.49){
	$class_of_degree='LOWER CREDIT';
}else if($sen['cgpa']<2.50 && $sen['cgpa']>1.99){
	$class_of_degree='PASS';
}else if($sen['cgpa']<2.00){
	$class_of_degree='FAIL';
}else{
	$class_of_degree='UNKNOWN';
}
	
	$qqq = mysqli_query($con,"insert into notification_result(ref_no, sname, fname, mname, matric_no, discipline, degree, class_degree, grad_session, email, reg_by, date, code) values('$ref_no','".trim($stu['sname'])."','".trim($stu['fname'])."','".trim($stu['mname'])."','".trim($_POST['matric_no'])."','".trim($stu['discipline'])."','$degree','$class_of_degree','".trim($sen['session'])."','".trim($stu['email'])."','".($adm['lastname'].' '.$adm['othernames'])."','$date','$pin')");
	
if($qqq){
$message = '<html><body style="border:1px solid #00b8e6; padding:10px;">';
$message .= '<div align="center"><a href="javascript:void(0)"><img src="https://'.$site_url.'img/logo1.png" style="width:230px;" alt="Inspire"></a></div>';
$message .= '<h1 style="color:#0073e6;">Dear Sir/Ma!</h1>';
$message .= '<p> This is to notify you ('.ucwords($stu['sname'].' '.$stu['fname'].' '.$stu['mname']).') that your Notification of Result has been processed and can be collected at Inspire Polytechnic Egbeda Campus, 39/41, Karimu Laka Street, Egbeda, Lagos.</p> 
<p>Please accept our warm congratulations...</p>';
$message .= '<br><small style="color:#4d4d4d;float:right;">  Thanks for being part of the family,<br>
            Inspire Polytechnic.</small><div style="clear:both;"></div>';
$message .= '</body></html>';

require "PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                     
            $mail->isSMTP();                                            
            $mail->Host       = $site_host;                     
            $mail->SMTPAuth   = true;                                   
            $mail->Username   = $site_username;                     
            $mail->Password   = $site_password;                               
            $mail->Port = 587;                                    
            $mail->setFrom($site_email, 'Inspire Polytechnic Student Notification of Result');
             			
			$to = $admin_email.','.trim($stu['email']);
			$emp=explode(",",$to);
                foreach($emp as $emm)
                {
                 $mail->ClearAllRecipients( );
                 $mail->addAddress($emm, ''); 
            
            $mail->isHTML(true);                                  
            $mail->Subject = 'Inspire Polytechnic Student Notification of Result Status';
            $mail->Body    = $message;
			$mail->send();
	            }
			
	  echo '<script type="text/javascript">
			swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Document processed and ready for download",
			confirmButtonColor: "#00cc66",   
		},
		function(){
			window.location="generator.php";
		});
			</script>';
		
	}else{
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>OOPS:</strong> Unable to complete operation, please try again later...
              </div>';
	}
	
}
}


if(isset($_POST['delete_doc'])){
	mysqli_query($con,"delete from notification_result where id='".$_POST['delete_doc']."'");
}


if(isset($_POST['recover_email'])){
	
	$hat=mysqli_query($con,"select * from portal_admin where email='".$_POST['recover_email']."'");
	
	if(mysqli_num_rows($hat)>0){
		$lol=mysqli_fetch_assoc($hat);
		
			$name=$lol['lastname'];
			$email=$lol['email'];
			$password=$lol['password'];
			$uid=uniqid();
		
		//to send mail
$message = '<html><body style="border:1px solid #00b8e6; padding:10px;">';
$message .= '<div align="center"><a href="javascript:void(0)"><img src="https://'.$site_url.'img/logo1.png" style="width:230px;" alt="Inspire"></a></div>';
$message .= '<h1 style="color:#0073e6;">Dear '.ucwords($name).'!</h1>';
$message .= '<p>You are receiving this mail because you optioned to recover your forgotten Inspire Polytechnic Student Notification of Results Management Portal Account password.</p> <p>Kindly click the link below to complete your password recovery process</p>';
$message .= '<p style="color:#4d4d4d;">Click here:  <a style="padding:7px 10px; color:#fff;background-color:#337ab7;border-color:#2e6da4; text-decoration:none;" href="https://'.$site_url.'recover_password.php?se='.$email.'&uq='.$uid.'&q='.$password.'">Complete recovery</a></p>';
$message .= '<br><small style="color:#4d4d4d;float:right;">  Thanks for being part of the family,<br>
            Inspire Polytechnic.</small><div style="clear:both;"></div>';
$message .= '</body></html>';

require "PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $site_host;                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $site_username;                     //SMTP username
            $mail->Password   = $site_password;                               //SMTP password
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = 587;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
            $mail->setFrom($site_email, 'Inspire Polytechnic Student Notification of Result Management Portal');
            $mail->addAddress($email, '');     //Add a recipient
            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = 'Inspire Polytechnic Student Notification of Result Management Portal Account Password';
            $mail->Body    = $message;
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';


if($mail->send()){
	echo '<div class="alert alert-dismissible alert-success" style="padding:10px;">
				<strong>Success!</strong> A recovery link has been sent to your mail.
              </div>';
}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Unable to complete operation, please try again later
              </div>';
}
	//end to send mail
		
		}else{
		 echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Unknown Email Address
              </div>';
	}
	
}

if((isset($_POST['r_id'])) && (isset($_POST['r_pass']))){
	
			$tan=mysqli_query($con,"select * from portal_admin where id='".$_POST['r_id']."'");

	if(mysqli_num_rows($tan)==0){
		echo '<div class="alert alert-danger alert-dismissable">
		<p class="pull-left">OPPS! Result Unknown, please try again later.</p>
											<div class="clearfix"></div></div>';
	}else if(strlen($_POST['r_pass'])<6){
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Password too weak
              </div>';
	}else if($_POST['r_cpass'] != $_POST['r_pass']){
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Password does not match
              </div>';
	}else{
		$qry=mysqli_query($con,"update portal_admin set password='".sha1($_POST['r_pass'])."' where id='".$_POST['r_id']."'");
		
		if($qry){
		echo '<script>
		alert("Password Changed! \n Redirecting you to the login page...")
		location.href="index.php"
		</script>';
		
		}else{
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Unable to complete operation, please try again later
              </div>';
		}
	}
}

if(isset($_POST['pass_setting'])){
	if(mysqli_num_rows(mysqli_query($con,"select * from result_settings where mode_entry='".$_POST['mode_entry']."'"))==0){
		$sera=mysqli_query($con,"insert into result_settings(min_ctnup,min_ctcp,date,mode_entry,entry_level,min_duration) values('".$_POST['min_ctnup']."','".$_POST['min_ctcp']."','$date','".strtoupper($_POST['mode_entry'])."','".$_POST['entry_level']."','".$_POST['min_duration']."')");
		
		echo '<script>
		alert("Graduating Parameter Updated!")
		location.href="graduating_req.php"
		</script>';
		
	}else{
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>ERROR!</strong> Mode of Admission/Entry Already Exist.
              </div>';
	}
}

if(isset($_POST['delete_setting'])){
	mysqli_query($con,"delete from result_settings where id='".$_POST['delete_setting']."'");
}


if(isset($_POST['add_programme'])){
	if(mysqli_num_rows(mysqli_query($con,"select id from semester"))==0){
	if(count($_POST['semester_name'])>0){
		$ct=0;
		
		for($i=1; $i<=count($_POST['semester_name']); $i++){
				if($_POST['min_tnu'][$i]>$_POST['max_tnu'][$i]){
					$ct=$ct+0;
					}else{
						$ct=$ct+1;
					}
		}
		
		if($ct!=count($_POST['semester_name'])){
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Minimum TNU can not be greater than the Maximum TNU
              </div>';
		}else{
			
			for($i=1; $i<=count($_POST['semester_name']); $i++){
 mysqli_query($con,"insert into semester(semester,description,min_tnu,max_tnu,upload_control,session,current_semester) values('$i','".$_POST['semester_name'][$i]."','".$_POST['min_tnu'][$i]."','".$_POST['max_tnu'][$i]."',0,'',0)");
			}
			
			echo '<script>
		alert("Application Parameter Updated!")
		location.href="semester_req.php"
		</script>';
		
	}
	
}else{
	echo '<div class="alert alert-danger alert-dismissable">
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> SORRY! Kindly add application semester(s).</p>
					<div class="clearfix"></div>
										</div>';
}

}else{
	echo '<div class="alert alert-danger alert-dismissable">
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> SORRY! An active parameter exists.</p>
					<div class="clearfix"></div>
										</div>';
}

}

if(isset($_POST['delete_case'])){
	mysqli_query($con,"delete from disciplinary_status where id='".$_POST['delete_case']."'");
}


if(isset($_POST['upload_case'])){
	 
	
	$cox=mysqli_query($con,"select id,matric_no from student where matric_no='".trim($_POST['c_matric_no'])."' AND student_category='".$_POST['category']."'");
	if(mysqli_num_rows($cox)>0){
	$c_date=DateTime::createFromFormat('Y-m-d', $_POST['c_date'])->format('d M Y');
	$qry=mysqli_query($con,"insert into disciplinary_status(matric_no,offence,action,content,date_convened,date,student_category) 
	values('".trim($_POST['c_matric_no'])."', \"".htmlspecialchars($_POST['c_offence'])."\", \"".htmlspecialchars($_POST['c_action'])."\", \"".htmlspecialchars($_POST['c_content'])."\", '$c_date', '$date','".$_POST['category']."')");
	
	if($qry){
		echo '<script>
		alert("Case Uploaded Successfully!")
		location.href="disciplinary_case.php"
		</script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissable">
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> SORRY! Unable to complete operation, please try again later.</p>
					<div class="clearfix"></div>
										</div>';
	}
	
	}else{
		echo '<div class="alert alert-danger alert-dismissable">
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> SORRY! No student matches the supplied matric no.</p>
					<div class="clearfix"></div>
										</div>';
	}
}



if(isset($_POST['upload_senate'])){
	$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn='upload_senate'.time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////
	
	$file = fopen($fn.'.csv', "r");
	$no=0;
    while ($row = fgetcsv($file)) { 
	if(trim($row[0])!='' && strtolower(trim($row[0]))!='matric no'){
		
	$no=$no+1;
	
	$cay=mysqli_query($con,"select matric_no,dept_code from student where matric_no='".trim($row[0])."' AND student_category='".$_POST['category']."'");
	$gmm=mysqli_fetch_assoc($cay);
	
	
	////////////////CGPA
	////////////////CGPA
$xxx = mysqli_query($con,"select SUM(unit) as unit from all_result where matric_no='".trim($row[0])."' AND student_category='".$_POST['category']."'");
$aaa=mysqli_fetch_assoc($xxx);
	
$total_unit = $aaa['unit']; //CTNU

// to get CTNUP and CTCP
$xx = mysqli_query($con,"select SUM(unit) as unit, SUM(unit*grade_point) as ugp from all_result where matric_no='".trim($row[0])."' AND grade_point>0 AND student_category='".$_POST['category']."'");
$bbb=mysqli_fetch_assoc($xx);
	
$total_unit_passed = $bbb['unit']; //CTNUP
$total_credit_point_passed = $bbb['ugp']; //CTCP
		
$cgpa = sprintf("%.2f",round(($total_credit_point_passed/$total_unit),2)); //CGPA
	////////////////CGPA
	////////////////CGPA
	
	$vmm=mysqli_query($con,"select id,matric_no from senate_status where matric_no='".trim($row[0])."' AND student_category='".$_POST['category']."'");
	if(mysqli_num_rows($vmm)>0){
		$coy=mysqli_fetch_assoc($vmm);
		$qry=mysqli_query($con,"update senate_status set dep_code='".$gmm['dept_code']."', approve_date='".trim($row[1])."', status=1, date='".trim($row[1])."', cgpa='$cgpa', session='".trim($row[2])."' where matric_no='".trim($row[0])."' AND id='".$coy['id']."'");
	}else{
		$qry=mysqli_query($con,"insert into `senate_status`(matric_no,dep_code,approve_date,status,date,cgpa,session,student_category) values('".trim($row[0])."','".$gmm['dept_code']."','".trim($row[1])."',1,'".trim($row[1])."','$cgpa','".trim($row[2])."','".$_POST['category']."')");
	}
	
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
	echo '<script>
	alert("Senate List Uploaded Successfully!")
	location.href="senate_approval.php"
		</script>'; 
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> Oops</b>&nbsp; No Valid Data Found.
                            </div>';
	}
		
		
	   ////////////////////////
	}
	
}


if(isset($_POST['delete_senate'])){
	mysqli_query($con,"delete from senate_status where id='".$_POST['delete_senate']."'");
}


if(isset($_POST['get_summary'])){
	
//$cam=mysqli_query($con,"select matric_no from student where year_entry='".$_POST['session']."' AND dept_code='".$_POST['department']."' AND student_category='".$_POST['s_cat']."'");
$cam=mysqli_query($con,"select matric_no from student where dept_code='".$_POST['department']."' AND student_category='".$_POST['s_cat']."'");
	if(mysqli_num_rows($cam)>0){
		$_SESSION['s_session']=$_POST['session'];
		$_SESSION['degree_type']=$_POST['s_cat'];
		$_SESSION['s_department']=$_POST['department'];
		echo '<script>
	window.open("get_summary.php")
		</script>';
	}else{
		echo '<script type="text/javascript">
        swal({   
			title: "OOPS",   
             type: "warning", 
			text: "No summary found for '.$_POST['session'].' academic session",
			confirmButtonColor: "#ff9900",   
		},
		function(){
			window.location="report.php";
		});
			</script>';
	}
	
}


if(isset($_POST['process_debtor'])){
		
		//echo '<script> window.open("debtor_exe.php") </script>';
		
echo '<script> window.open("debtor_exe.php?token='.uniqid().'&rdr='.sha1(uniqid()).'&dep='.$_POST['department'].'&encoder='.md5(rand(1,1000000)).'&cat='.$_POST['s_cat'].'");  </script>';
}


if(isset($_POST['pass_warning'])){
	
if(is_numeric($_POST['warning']) === false){
	echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Invalid Minimum Warning GP Status.
                            </div>';
}else if(is_numeric($_POST['withdrawn']) === false){
	echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Invalid Minimum Withdrawn GP Status.
                            </div>';
}else{
	$mad=mysqli_query($con,"select * from warning_withdrawn where id>0 AND min_warning_gp!='' AND min_withdrawn_gp!=''");
	if(mysqli_num_rows($mad)>0){
		$kad=mysqli_query($con,"update warning_withdrawn set min_warning_gp='".trim($_POST['warning'])."', min_withdrawn_gp='".trim($_POST['withdrawn'])."', date='$date'");
	}else{
		$kad=mysqli_query($con,"insert into warning_withdrawn(min_warning_gp,min_withdrawn_gp,date) values('".trim($_POST['warning'])."','".trim($_POST['withdrawn'])."','$date')");
	}
	if($kad){
		
		echo '<div class="alert alert-success alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-check-circle" style="margin-top:;"></i> SUCCES</b>&nbsp; Constraints Updated Successfully!
                            </div>';
	}else{
		echo '<div class="alert alert-danger alert-dismissable">
					<p class="pull-left"><i class="fa fa-ban" style="font-size:17px;"></i> SORRY! Unable to complete operation, please try again later.</p>
					<div class="clearfix"></div>
										</div>';
	}
}
	
	
}



if(isset($_POST['get_summary_level'])){
	
	$cam=mysqli_query($con,"select dep_code,level,semester_num,session from all_result where student_category='".$_POST['level']."' AND dep_code='".$_POST['department']."' AND semester_num='".$_POST['semester']."' AND session='".$_POST['session']."'");
	if(mysqli_num_rows($cam)>0){
		$_SESSION['l_department']=$_POST['department'];
		$_SESSION['l_level']=$_POST['level'];
		$_SESSION['l_session']=$_POST['session'];
		$_SESSION['l_semester']=$_POST['semester'];
		echo '<script>
	window.open("get_summary_by_level.php")
		</script>';
	}else{
		echo '<script type="text/javascript">
        swal({   
			title: "OOPS",   
             type: "warning", 
			text: "No summary found for '.$_POST['level'].' students",
			confirmButtonColor: "#ff9900",   
		},
		function(){
			window.location="report.php";
		});
			</script>';
	}
	
}









if(isset($_POST['edit_programme'])){
	$bay=mysqli_query($con,"select * from programme where id='".$_POST['edit_programme']."'");
	$pro=mysqli_fetch_assoc($bay);
	
						echo '<form method="post" id="form_submit1">
									<input type="hidden" name="update_programme" value="'.$_POST['edit_programme'].'">
									
									<div class="row">
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Programme</label>
									<input class="form-control" value="'.$pro['name'].'" name="upd_name" type="text" required >
									</div> 
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Description</label>
									<input class="form-control" value="'.$pro['description'].'" name="upd_description" type="text" required >
									</div>
									</div>
												
												<div class="error"></div>
													<div class="form-group">
													<button class="btn btn-primary mb-5 pull-right" type="submit">Update</button>
													<div class="clearfix"></div>
												</div>
									</form>';
}

if(isset($_POST['delete_programme'])){
	mysqli_query($con,"truncate semester");
}

if(isset($_POST['control_programme'])){
	$car=mysqli_query($con,"select * from semester order by semester asc");
	if(mysqli_num_rows($car)>0){
		echo '<div class="form-group">
			<label class="control-label mb-5" for="email_de">Application Control</label>
			<select class="form-control" name="status" id="status_signal" required >
			<option value="">Select</option>';
	while($sac=mysqli_fetch_assoc($car)){
echo '<option value="result_'.$sac['id'].'_reg_1" class="bg-success">'.$sac['description'].' Result Upload :: ON</option>
<option value="result_'.$sac['id'].'_reg_0" class="bg-warning">'.$sac['description'].' Result Upload :: OFF</option>';
	}
	echo '</select></div>
	
	
												
												<div class="form-group" style="display:none;" id="control_session">
                             <label class="control-label mb-5" for="email_de">Academic Session</label>
												<select class="form-control" name="session">
												<option value="">Select</option>';
												
												for($x=date("Y"); $x>=2015; $x--){
									echo '<option value="'.($x-1).'/'.($x).'">'.($x-1).'/'.($x).'</option>';
												}
												
												echo '</select>
                                                </div>';
	}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> No semester found!
              </div>';	
	}
}

if(isset($_POST['update_control'])){
	$status=explode("_",$_POST['status']);
	//$status=$_POST['programme'];
	
	$awa=mysqli_query($con,"select * from correction_window where status=1");
	
	if(mysqli_num_rows($awa)>0 && $status[3]==1){
		
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh No!</strong> Kindly close the result correction window.
              </div>';
		
	}else{
	
	if($status[3]==1 && $_POST['session']==''){
		echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh No!</strong> Kindly select academic session.
              </div>';
	}else{
	if($status[3]==0){
	$qry=mysqli_query($con,"update semester set upload_control=0");
	}else if($status[3]==1){
	
	mysqli_query($con,"update semester set upload_control=0, current_semester=0");
	$qry=mysqli_query($con,"update semester set upload_control=1, session='".$_POST['session']."', current_semester=1 where id='".$status[1]."'");
	
	}else{
	$qry='';	
	}
	
	if($qry){
		echo '<script>
		alert("App Settings Updated!")
		window.location="setting.php"
		</script>';
	}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Unable to complete operation, please try again later!
              </div>';	
	}
	}
	
}
}



if(isset($_POST['prog'])){
	$car=mysqli_query($con,"select * from semester order by semester asc");
	if(mysqli_num_rows($car)>0){
		echo '<div class="form-group">
			<label class="control-label mb-5" for="email_de">Semester</label>
			<select class="form-control" name="semester" required >
			<option value="">Select</option>';
	while($sac=mysqli_fetch_assoc($car)){
echo '<option value="'.$sac['id'].'">Semester '.$sac['semester'].' :: '.$sac['description'].'</option>';
	}
	echo '</select></div>';
	}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> No semester found!
              </div>';	
	}
}


if(isset($_POST['upload_lecturers'])){
	$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	$lecturer_email='';
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn='upload_lecturers'.time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////
	
	$file = fopen($fn.'.csv', "r");
	$no=0;
		
    while ($row = fgetcsv($file)) { 
	if(trim($row[0])!='' && trim($row[1])!='' && trim($row[2])!='' && trim($row[3])!='' && trim($row[4])!='' && strtolower(trim($row[0]))!='lastname' && strtolower(trim($row[2]))!='staff id'){
		

	
    $x=mysqli_query($con,"select id,staff_id,email from `lecturer` where LCASE(staff_id)='".strtolower(trim($row[2]))."' OR LCASE(email)='".strtolower(trim($row[3]))."' ");
	
    $dp_code=mysqli_query($con,"select dep_code from `department` where dep_code='".trim($row[4])."'");
	
	if(mysqli_num_rows($x)==0 && mysqli_num_rows($dp_code)>0){
		
			$no=$no+1;
		
		$lecturer_email .=trim($row[3]).',';
		
	$qry=mysqli_query($con,"insert into `lecturer`(staff_id,lastname,othernames,email,dep_code,assign_post,login_status,password,password1) values('".trim($row[2])."','".trim($row[0])."','".trim($row[1])."','".trim($row[3])."','".trim($row[4])."','lecturer',1,'".sha1('resultportal-0000')."','".sha1('ololadeololade')."')");
	
	}
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
		if(str_ireplace(",","",$lecturer_email)!=''){
	///////////////////// START MAIL
	///////////////////// START FOR MAIL

$to = substr_replace(trim($lecturer_email),"",-1);

$message = '<html><body>';
$message .= '<div align="center" style="padding:10px;">
<img src="https://'.$site_url.'img/d_logo.png" style="width:230px;" alt="LASU"></div>';
$message .= '<div style="border:1px solid #0033cc; padding:15px;"><h1 style="color:#0040ff; text-align:center;">Dear Sir/Ma,</h1>';
$message .= '<p style="font-size:17px; color:black;">You have been successfully enrolled as the coordinator/head of department on the Lagos State University (LASU) '.$site_programme.' Students Results Management Portal.</p>';
$message .= '<p style="color:black; font-size:16px;">Your login details are the same as your Undergraduate students results portal.</p>';
$message .= '<p style="color:#4d4d4d;font-size:17px;">Click here to login:  <a style="padding:7px 10px; color:#fff;background-color:#ff0066;border-color:#e6005c; text-decoration:none;" href="https://'.$site_url.'login/">Login Page</a></p>';
$message .= '<br><small style="color:#4d4d4d;float:right;"> Lagos State University, Ojo.</small><div style="clear:both;"></div>';
$message .= '</div></body></html>';

require "../PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $site_host;                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $site_username;                     //SMTP username
            $mail->Password   = $site_password;                               //SMTP password
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = 587;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
            $mail->setFrom($site_email, 'LASU Student Results Management Portal');
            
                $emp=explode(",",$to);
                foreach($emp as $emm){
                    $mail->ClearAllRecipients( );
                   $mail->addAddress($emm, ''); 
            
					//Content
					$mail->isHTML(true);                                  //Set email format to HTML
					$mail->Subject = 'LASU '.$site_programme.' Students Results Management System Account Creation';
					$mail->Body    = $message;
					$mail->send();
	            }
	
	///////////////////// END MAIL
	///////////////////// END MAIL
		}
		
	echo '<script>
	alert("'.$no.' Lecturer(s) Uploaded Successfully!")
	location.href="lecturers.php"
		</script>'; 
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS:</b>&nbsp; No Valid Data Found. Data already exit or department is not recognised...
                            </div>';
	}
		
	   ////////////////////////
	}
	
}

if(isset($_POST['suspend_operation'])){
	$exp=explode("_",$_POST['suspend_operation']);
	$qqq=mysqli_query($con,"update lecturer set login_status='".$exp[1]."' where id='".$exp[0]."'");
	if($qqq){
		
		if($exp[1]==1){
						echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Staff Ban Lifted!",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="lecturers.php";
		});
			</script>';
		}else{
			echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Staff Account Suspended!",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="lecturers.php";
		});
			</script>';
		}
		
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}



if(isset($_POST['suspend_subadmin_operation'])){
	$exp=explode("_",$_POST['suspend_subadmin_operation']);
	$qqq=mysqli_query($con,"update sub_admin set status='".$exp[1]."' where id='".$exp[0]."'");
	if($qqq){
		
		if($exp[1]==1){
						echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Sub-Admin Ban Lifted!",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="sub_admin.php";
		});
			</script>';
		}else{
			echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Sub Admin Account Suspended!",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="sub_admin.php";
		});
			</script>';
		}
		
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}


if(isset($_POST['lecturer_log'])){
	$man=mysqli_query($con,"select id from lecturer where id='".$_POST['lecturer_log']."'");
	if(mysqli_num_rows($man)>0){
		$_SESSION['lecturer_log']=$_POST['lecturer_log'];
		echo '<script> window.location="lecturer_log.php" </script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}

if(isset($_POST['sub_admin_role'])){
	$man=mysqli_query($con,"select id from sub_admin where id='".$_POST['sub_admin_role']."'");
	if(mysqli_num_rows($man)>0){
		$_SESSION['sub_admin_role']=$_POST['sub_admin_role'];
		echo '<script> window.location="sub_admin_role.php" </script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}


if(isset($_POST['sub_admin_log'])){
	$man=mysqli_query($con,"select id from sub_admin where id='".$_POST['sub_admin_log']."'");
	if(mysqli_num_rows($man)>0){
		$_SESSION['sub_admin_log']=$_POST['sub_admin_log'];
		echo '<script> window.location="sub_admin_log.php" </script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}

if(isset($_POST['assigned_course'])){
	$man=mysqli_query($con,"select id from lecturer where id='".$_POST['assigned_course']."'");
	if(mysqli_num_rows($man)>0){
		$_SESSION['assigned_course']=$_POST['assigned_course'];
		echo '<script> window.location="assigned_course.php" </script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}

if(isset($_POST['upload_department'])){
	
		$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn='upload_department'.time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////
	
	$file = fopen($fn.'.csv', "r");
	$no=0;
    while ($row = fgetcsv($file)) { 
	if(trim($row[0])!='' && trim($row[1])!='' && trim($row[2])!='' && strtolower(trim($row[0]))!='department' && strtolower(trim($row[1]))!='department code' && strtolower(trim($row[2]))!='faculty code'){
		
	$no=$no+1;
	
    $x=mysqli_query($con,"select * from `department` where LCASE(department)='".strtolower(trim($row[0]))."' OR LCASE(dep_code)='".strtolower(trim($row[1]))."'");
	
	if(mysqli_num_rows($x)==0){
		
	$qry=mysqli_query($con,"insert into `department`(department,dep_code,fac_code,prog_duration,min_ctnup) values('".trim($row[0])."','".trim($row[1])."','".trim($row[2])."','".(int)$row[3]."',36)");
	
	}
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
	echo '<script>
	alert("Department Uploaded Successfully!")
	location.href="department.php"
		</script>'; 
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; No Data Found.
                            </div>';
	}
		
	   ////////////////////////
	}
	
}


if(isset($_POST['delete_department'])){
	$emf=explode("_",$_POST['delete_department']);
	$gar=mysqli_query($con,"select id,dep_code from lecturer where dep_code='".$emf[1]."'");
	if(mysqli_num_rows($gar)==0){
		$qry=mysqli_query($con,"delete from department where id='".$emf[0]."'");
		if($qry){
			echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Department Deleted!",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="department.php";
		});
			</script>';
		}else{
			echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
		}
	}else{
	echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Lecturers exists in selected department
                            </div>';	
	}
}


if(isset($_POST['upload_course'])){
	$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn="upd_course".time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////
	
	$file = fopen($fn.'.csv', "r");
	$no=0;
    while ($row = fgetcsv($file)) { 
	if(trim($row[0])!='' && trim($row[1])!='' && trim($row[2])!='' && trim($row[3])!='' && trim($row[4])!='' && trim($row[5])!='' && trim($row[6])!='' && strtolower(trim($row[0]))!='course code' && strtolower(trim($row[3]))!='unit'){
		
	$no=$no+1;
	
    $x=mysqli_query($con,"select * from `course` where course_code='".strtolower(trim($row[0]))."' OR description='".strtolower(trim($row[1]))."'");
	
	if(mysqli_num_rows($x)==0){
		
	$qry=mysqli_query($con,"insert into `course`(course_code,description,status,unit,level,dep_code,semester_num) values('".strtolower(trim($row[0]))."','".strtolower(trim($row[1]))."','".strtolower(trim($row[2]))."','".trim($row[3])."','".trim($row[4])."','".trim($row[5])."','".trim($row[6])."')");
	
	}else{
		
	$sol=mysqli_fetch_assoc($x);
	$sid=$sol['id'];
	mysqli_query($con,"delete from `course` where id='$sid'");
	
	$qry=mysqli_query($con,"insert into `course`(id,course_code,description,status,unit,level,dep_code,semester_num) values('$sid','".strtolower(trim($row[0]))."','".strtolower(trim($row[1]))."','".strtolower(trim($row[2]))."','".trim($row[3])."','".trim($row[4])."','".trim($row[5])."','".trim($row[6])."')");	
	
	}
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
	echo '<script>
	alert("'.$no.' Course Uploaded Successfully!")
	location.href="course_bank.php"
		</script>'; 
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> Oops</b>&nbsp; No Data Found.
                            </div>';
	}
		
		
	   ////////////////////////
	}
	
}



if(isset($_POST['delete_course'])){
	mysqli_query($con,"delete from course where id='".$_POST['delete_course']."'");
}

if(isset($_POST['edit_course'])){
	$bay=mysqli_query($con,"select * from course where id='".$_POST['edit_course']."'");
	$pro=mysqli_fetch_assoc($bay);
	
						echo '<form method="post" id="form_submit2">
									<input type="hidden" name="update_course" value="'.$_POST['edit_course'].'">
									
									<div class="row">
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Course Code</label>
									<input class="form-control" value="'.$pro['course_code'].'" name="upd_course_code" type="text" required >
									</div> 
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Description</label>
									<input class="form-control" value="'.$pro['description'].'" name="upd_description" type="text" required >
									</div>
									</div>
									<div class="row">
									<div class="col-md-4 form-group">
									<label class="control-label mb-5" for="email_de">Status</label>
									<input class="form-control" value="'.$pro['status'].'" name="upd_status" type="text" required >
									</div> 
									<div class="col-md-4 form-group">
									<label class="control-label mb-5" for="email_de">Unit</label>
									<input class="form-control" value="'.$pro['unit'].'" min="0" name="upd_unit" type="number" required >
									</div>
									<div class="col-md-4 form-group">
									<label class="control-label mb-5" for="email_de">level</label>
									<select class="form-control" name="upd_level" required >
									<option>'.$pro['level'].'</option>';
									for($j=1; $j<=9; $j++){
										echo '<option>'.$j.'00</option>';
									}
									echo '</select>
									</div>
									</div>
												
												<div class="error2"></div>
													<div class="form-group">
													<button class="btn btn-primary mb-5 pull-right" type="submit">Update</button>
													<div class="clearfix"></div>
												</div>
									</form>';
	
}

if(isset($_POST['delete_result'])){
	mysqli_query($con,"delete from all_result where id='".$_POST['delete_result']."'");
}




if(isset($_POST['s_prog'])){
	$car=mysqli_query($con,"select * from semester where programme_id='".$_POST['s_prog']."' order by semester asc");
	if(mysqli_num_rows($car)>0){
		echo '<div class="form-group">
			<label class="control-label mb-5" for="email_de">Semester</label>
			<select class="form-control" name="s_semester" required >
			<option value="">Select</option>';
	while($sac=mysqli_fetch_assoc($car)){
echo '<option value="'.$sac['id'].'">Semester '.$sac['semester'].' :: '.$sac['description'].'</option>';
	}
	echo '</select></div>';
	}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> No semester found!
              </div>';	
	}
}



if(isset($_POST['search_course'])){

	$gay=mysqli_query($con,"select * from course where dep_code='".$_POST['s_department']."' AND semester_num='".$_POST['s_semester']."' AND level='".$_POST['s_level']."' order by level asc, course_code asc");
	if(mysqli_num_rows($gay)>0){
	$_SESSION['s_search']='true';	
	$_SESSION['s_level']=$_POST['s_level'];	
	$_SESSION['s_department']=$_POST['s_department'];	
	$_SESSION['s_semester']=$_POST['s_semester'];
		echo '<script>
		location.href="course_bank.php"
		</script>';
	}else{
		echo '<div class="alert alert-dismissible alert-danger">
				<strong>Oh Sorry!</strong> No course found matching the searched query.
              </div>';
	}
}


if((isset($_POST['old'])) && (isset($_POST['new']))){
	if(sha1($_POST['old']) != $_POST['ori']){
							echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Incorrect Password
              </div>';
	}else if(strlen($_POST['new'])<6){
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Password too weak
              </div>';
	}else if($_POST['cnew'] != $_POST['new']){
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Password does not match
              </div>';
	}else if(sha1($_POST['new']) == $_POST['ori']){
								echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> New Password cannot be the same as your Current password.
              </div>';
	}else{
		$qry=mysqli_query($con,"update portal_admin set password='".sha1($_POST['new'])."' where id='".$_SESSION['delsuresultadminid']."'");

		if($qry){ 

$message = '<html><body>';
$message .= '<div align="center" style="padding:10px;">
<img src="https://'.$site_url.'img/logo1.png" style="width:230px;" alt="Inspire"></div>';
$message .= '<div style="border:1px solid #0033cc; padding:15px;"><h1 style="color:#0040ff; text-align:center;">Dear '.ucwords($adm['lastname']).',</h1>';
$message .= '<p style="font-size:17px; color:black;">You have successfully changed your Inspire Polytechnic Student Notification of Result Management Portal account login password</p>';
$message .= '<p style="color:black; font-size:17px;">Kindly contact the Rector if you did not make these changes</p>';
$message .= '<br><small style="color:#4d4d4d;float:right;"> Inspire Polytechnic.</small><div style="clear:both;"></div>';
$message .= '</div></body></html>';

require "PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $site_host;                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $site_username;                     //SMTP username
            $mail->Password   = $site_password;                               //SMTP password
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = 587;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
            $mail->setFrom($site_email, 'Inspire Polytechnic Student Notification of Result Management Portal');
            $mail->addAddress($adm['email'], '');     //Add a recipient
            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = 'Inspire Polytechnic Student Notification of Result Management Portal Account Password';
            $mail->Body    = $message;
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
			$mail->send(); // to send the composed mail

			echo '<div class="alert alert-dismissible alert-success" style="padding:10px;">
				<strong>OK!</strong> Password Changed Successfully.
              </div>';
		}else{
			echo '<div class="alert alert-danger alert-dismissable">
											<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
											<i class="zmdi zmdi-block pr-15 pull-left"></i><p class="pull-left">Opps! Something came up, please try again later.</p>
											<div class="clearfix"></div>
										</div>';
		}
	}
	}


//$que=mysqli_query($con,"insert into student(sname,fname,mname,matric_no,gender,year_entry,dept_code,mode_entry,date,password,password1,department,faculty) values('".strtolower($result['Surname'])."','".strtolower($result['FirstName'])."','".strtolower($result['OtherNames'])."','".$result['MatriculationNumber']."','".$result['Gender']."','".$result['YearOfEntry']."','".$result['DepartmentCode']."','".$result['ModeofEntry']."','$date','".sha1($_POST['password'])."','".sha1('ololaderesult')."','".$result['Discipline']."','".$result['Faculty']."')");


if(isset($_POST['upload_student'])){
	$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn=rand(1,1000).time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////


// Full texts	id	sname	fname	mname	matric_no	gender	year_entry	dept_code	mode_entry	date	password	password1	department	faculty

//SURNAME 0	FIRSTNAME 1	MIDDLENAME 2	MATRIC NO 3	GENDER 4	YEAR OF ENTRY 5	FACULTY 6	DEPARTMENT 7	DEPARTMENT CODE 8	MODE OF ENTRY 9

	
	$file = fopen($fn.'.csv', "r");
	$no=0;
    while ($row = fgetcsv($file)) { 
	if(trim($row[0])!='' && strtolower(trim($row[0]))!='surname' && strtolower(trim($row[3]))!='' && strtolower(trim($row[3]))!='matric no' && strtolower(trim($row[1]))!='' && strtolower(trim($row[4]))!=''  && strtolower(trim($row[5]))!=''  && strtolower(trim($row[6]))!=''  && strtolower(trim($row[7]))!=''  && strtolower(trim($row[8]))!=''  && strtolower(trim($row[9]))!=''){
		
	
	
	$dmj=mysqli_query($con,"select id,faculty from faculty where LCASE(faculty)='".strtolower(trim($row[6]))."'"); // verify faculty
	
	$dqj=mysqli_query($con,"select id,mode_entry from result_settings where mode_entry='".trim($row[9])."'"); // verify mode of entry
	
	$dqq=mysqli_query($con,"select id,dep_code,department from department where LCASE(dep_code)='".strtolower(trim($row[8]))."' AND department='".trim($row[7])."'"); // verify dep code and department
	
	$daq=mysqli_query($con,"select id,matric_no from all_result where matric_no='".strtolower(trim($row[3]))."'"); // verify results exits
	
	if(mysqli_num_rows($daq)==0 && mysqli_num_rows($dqq)>0 && mysqli_num_rows($dqj)>0 && mysqli_num_rows($dmj)>0){
	
	$no=$no+1;
	
    $x=mysqli_query($con,"select * from `student` where matric_no='".strtolower(trim($row[3]))."'");
	
	if(mysqli_num_rows($x)==0){
		
	$qry=mysqli_query($con,"insert into `student`(sname,fname,mname,matric_no,gender,year_entry,dept_code,mode_entry,date,password,password1,department,faculty) values('".strtolower(trim($row[0]))."','".strtolower(trim($row[1]))."','".strtolower(trim($row[2]))."','".trim($row[3])."','".trim($row[4])."','".trim($row[5])."','".trim($row[8])."','".trim($row[9])."','$date','','','".strtolower(trim($row[7]))."','".strtolower(trim($row[6]))."')");
	
	}else{
		
	$sol=mysqli_fetch_assoc($x);
	$sid=$sol['id'];
	
	$qry=mysqli_query($con,"insert into `student`(id,sname,fname,mname,matric_no,gender,year_entry,dept_code,mode_entry,date,password,password1,department,faculty) values('$sid','".strtolower(trim($row[0]))."','".strtolower(trim($row[1]))."','".strtolower(trim($row[2]))."','".trim($row[3])."','".trim($row[4])."','".trim($row[5])."','".trim($row[8])."','".trim($row[9])."','$date','','','".strtolower(trim($row[7]))."','".strtolower(trim($row[6]))."')");
	
	}
	}else{
		$no=$no+0;
	}
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
		echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "'.$no.' Students Uploaded...",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="student.php";
		});
			</script>';
		
	/*echo '<script>
	alert("Students Uploaded Successfully!")
	location.href="student.php"
		</script>'; */
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> Oops</b>&nbsp; No student data upload.
                            </div>';
	}
		
		
	   ////////////////////////
	}
	
}


if(isset($_POST['delete_student'])){
	$sam=mysqli_query($con,"select * from student where id='".$_POST['delete_student']."'");
	$sar=mysqli_fetch_assoc($sam);
	$yat=mysqli_query($con,"select id,matric_no from all_result where matric_no='".$sar['matric_no']."' AND student_category='".$sar['student_category']."'");
	if(mysqli_num_rows($yat)==0){
	$yae=mysqli_query($con,"delete from student where id='".$_POST['delete_student']."'");
	
	if($yae){
		echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Student Deleted!",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="student.php";
		});
			</script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
	
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Student cannot be deleted, results exists...
                            </div>';
	}
}








if(isset($_POST['see_student_course'])){ //sid, semester_num, session
	$emf=explode("_",$_POST['see_student_course']);
	$_SESSION['xxx_sid']=$emf[0];
	$_SESSION['xxx_semester_num']=$emf[1];
	$_SESSION['xxx_session']=$emf[2];
		echo '<script>
	location.href="reg_courses.php"
		</script>';
}

if(isset($_POST['exam_slip_programme'])){
	$car=mysqli_query($con,"select * from semester where programme_id='".$_POST['exam_slip_programme']."' AND description!='' AND session!='' order by semester asc");
	if(mysqli_num_rows($car)>0){
		echo '<div class="form-group">
			<label class="control-label mb-5" for="email_de">Session & Semester</label>
			<select class="form-control" name="exam_slip_semester" required >
			<option value="">Select</option>';
	while($sac=mysqli_fetch_assoc($car)){
echo '<option value="'.$sac['id'].'">'.$sac['session'].' :: '.ucwords($sac['description']).'</option>';
	}
	echo '</select></div>
	
	<div class="form-group">
			<label class="control-label mb-5" for="email_de">Switch</label>
			<select class="form-control" name="exam_slip_switch" required >
			<option value="">Select</option>
			<option value="1" class="bg-success">Enable</option>
			<option value="0" class="bg-danger">Disable</option>
	</select></div>
	
	<div class="form-group">
    <label class="control-label mb-5" for="email_de">Invigilators Access Password</label>
	<input class="form-control" name="exam_slip_password" placeholder="Optional for disable control" >
    </div>';
	}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> No academic session found!
              </div>';	
	}
}


if(isset($_POST['add_unit'])){
	
$pro=explode("_",$_POST['a_programme']);
	
$dim=mysqli_query($con,"select * from student where matric_no='".$_POST['a_matric_no']."' AND programme_id='".$pro[0]."'");
if(mysqli_num_rows($dim)==1){	
$stu=mysqli_fetch_assoc($dim);

$svm=mysqli_query($con,"select * from semester where programme_id='".$stu['programme_id']."' AND (registration_control=1 OR add_delete_control=1) AND session !=''");

if(mysqli_num_rows($svm)>0){
$sxm=mysqli_fetch_assoc($svm);
	
$vay=mysqli_query($con,"select * from department where id='".$stu['dept_id']."'");
$dep=mysqli_fetch_assoc($vay);

$mec=mysqli_query($con,"select * from course where programme_id='".$stu['programme_id']."' AND dep_id='".$stu['dept_id']."' AND semester_id='".$sxm['id']."' AND id='".$_POST['a_course']."'");
$cos=mysqli_fetch_assoc($mec);

$mac=mysqli_query($con,"select * from reg_course where sid='".$stu['id']."' AND  matric_no='".$stu['matric_no']."' AND programme_id='".$pro[0]."' AND semester_num='".$sxm['semester']."' AND dep_id='".$stu['dept_id']."' AND session='".$sxm['session']."' order by id desc limit 1");

$moc=mysqli_query($con,"select * from reg_course where sid='".$stu['id']."' AND  matric_no='".$stu['matric_no']."' AND programme_id='".$pro[0]."' AND semester_num='".$sxm['semester']."' AND dep_id='".$stu['dept_id']."' AND session='".$sxm['session']."' AND course_code='".$cos['course_code']."'");

if(mysqli_num_rows($mac)>0){
	
	if(mysqli_num_rows($moc)==0){
	
	$reg=mysqli_fetch_assoc($mac);
	
	//	matric_no 	fullname 	department 	programme 	programme_id 	course_code 	course_description 	unit 	session 	semester 	uploaded_by 	date 
	
	$vey=mysqli_query($con,"select * from programme where id='".$pro[0]."'");
	$prog=mysqli_fetch_assoc($vey);
	
	$q1=mysqli_query($con,"insert into reg_course(sid,matric_no,level,dep_id,course_id,course_code,description,unit,status,programme_id,programme,programme_description,semester_num,semester_description,session,date) values('".$stu['id']."','".$stu['matric_no']."','".$reg['level']."','".$stu['dept_id']."','".$cos['id']."','".$cos['course_code']."','".$cos['description']."','".$cos['unit']."','".$cos['status']."','".$pro[0]."','".$pro[1]."','".$prog['description']."','".$sxm['semester']."','".$sxm['description']."','".$sxm['session']."','$date')");
	
	if($q1){
	mysqli_query($con,"insert into `add_unit`(matric_no,fullname,department,programme,programme_id,course_code,course_description,unit,session,semester,uploaded_by,date) values('".$stu['matric_no']."','".ucwords($stu['sname'].' '.$stu['mname'].' '.$stu['fname'])."','".$dep['department']."','".$pro[1]."','".$pro[0]."','".$cos['course_code']."','".$cos['description']."','".$cos['unit']."','".$sxm['session']."','".$sxm['description']."','".ucwords($adm['lastname'].' '.$adm['othernames'])."','$date')");

$mailto='director.ict@lasu.edu.ng';
$message = '<html><body>';
$message .= '<div align="center" style="padding:10px;">
<img src="'.$lasu_link.'img/logo.png" style="width:230px;" alt="LASU"></div>';
$message .= '<div style="border:1px solid #0033cc; padding:15px;"><h1 style="color:#0040ff; text-align:center;">Dear Sir/Ma,</h1>';
$message .= '<p style="font-size:17px; color:black;">An additional Unit operation was executed by the course registration portal admin, <b style="font-size:16px;font-weight:600;">'.ucwords($adm['lastname'].' '.$adm['othernames']).'</b> today, <b style="font-weight:600;">$date</b>.</p>';
$message .= '<p style="color:black; font-size:17px; font-weight:600;text-decoration:underline;">STUDENT DETAILS.</p>';

$message .= '<p style="color:black; font-size:19px;"><b>FullName : </b>'.ucwords($stu['sname'].' '.$stu['mname'].' '.$stu['fname']).'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Matriculation Number : </b>'.$stu['matric_no'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Programme : </b>'.ucwords($pro[1]).'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Department : </b>'.ucwords($dep['department']).'</p>';

$message .= '<p style="color:black; font-size:17px; font-weight:600;text-decoration:underline;">ADDED COURSE DETAILS.</p>';

$message .= '<p style="color:black; font-size:19px;"><b>Course code : </b>'.$cos['course_code'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Description : </b>'.$cos['description'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Unit : </b>'.$cos['unit'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Semester : </b>'.$sxm['description'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Session : </b>'.$sxm['session'].'</p>';

$message .= '<br><small style="color:#4d4d4d;float:right;"> Moving the world of technology to the next level</small><div style="clear:both;"></div>';
$message .= '</div></body></html>';

require "../PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = 'csc.lasu.edu.ng';                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = 'help@csc.lasu.edu.ng';                     //SMTP username
            $mail->Password   = 'helpcsc2021';                               //SMTP password
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = 587;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
            $mail->setFrom($lasu_email, 'LASU Course Reg. Portal');
            $mail->addAddress($mailto, '');     //Add a recipient
            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = 'LASU Course Reg. Additional Unit Notification';
            $mail->Body    = $message;
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
			$mail->send(); // to send the composed mail 
			
	
	echo '<script>
	alert("Course Added for Student Successfully!")
	location.href="add_unit.php"
	</script>'; 
	
	
	}else{
			echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Something came up, please refresh page and try again...
              </div>';
	}
}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh No!</strong> Student already registered '.strtoupper($cos['course_code']).' for '.$sxm['session'].' academic session...
              </div>';
}
	
}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Student yet to register for the current semester...
              </div>';
}
}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Registration and Add/Delete Portal is closed...
              </div>';
}
}else{
	echo '<div class="alert alert-dismissible alert-danger" style="padding:10px;">
				<strong>Oh Sorry!</strong> Student not found...
              </div>';
}
}




if(isset($_POST['edit_hod'])){
	$epp=explode("_",$_POST['edit_hod']);
	$bav=mysqli_query($con,"select * from head where dep_id='".$epp[1]."'");
	$had=mysqli_fetch_assoc($bav);
	//	dep_id 	lastname 	othernames 	email 	pfn 	password 
	
	echo '<form method="post" id="form_submit3">
									<input type="hidden" name="update_hod" value="'.$epp[1].'">
									
									<div class="row">
									<div class="col-md-12 form-group">
									<label class="control-label mb-5" for="email_de">Department</label>
						<input class="form-control" value="'.$epp[0].'" type="text" style="background-color:transparent; cursor:pointer;" readonly required >
									</div>
									</div>
									
									<div class="row">
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">PF No.</label>
						<input class="form-control" value="'.$had['pfn'].'" name="hod_pfn" type="text" required >
									</div>
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Lastname</label>
						<input class="form-control" value="'.$had['lastname'].'" name="hod_lastname" type="text" required >
									</div>
									</div>
									
									<div class="row">
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Othernames</label>
						<input class="form-control" value="'.$had['othernames'].'" name="hod_othernames" type="text" required >
									</div>
									<div class="col-md-6 form-group">
									<label class="control-label mb-5" for="email_de">Email</label>
									<input class="form-control" value="'.$had['email'].'" name="hod_email" type="email" required >
									</div> 
									</div>
												
												<div class="error3"></div>
													<div class="form-group">
													<button class="btn btn-primary mb-5 pull-right" type="submit">Update Hod</button>
													<div class="clearfix"></div>
												</div>
									</form>';
	
	
	
	
}



if(isset($_POST['upload_paid'])){
	if($_POST['execution']=='delete'){
		mysqli_query($con,"TRUNCATE TABLE `valid_student`");
	}
	
	$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn=$_SESSION['lasuadmincoursereg_id'].time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////
	
	$file = fopen($fn.'.csv', "r");
	$no=0;
    while ($row = fgetcsv($file)) { 
	if(strtolower(trim($row[0]))!='surname' && strtolower(trim($row[0]))!='' && strtolower(trim($row[3]))!='matric no'){
		
	$no=$no+1;
	
    $x=mysqli_query($con,"select * from `valid_student` where matric_no='".strtolower(trim($row[3]))."'");
	
	if(mysqli_num_rows($x)==0){
		
	$qry=mysqli_query($con,"insert into `valid_student`(surname,firstname,othernames,matric_no,gender,year_entry,faculty,department,date) values('".strtoupper(trim($row[0]))."','".strtoupper(trim($row[1]))."','".strtoupper(trim($row[2]))."','".trim($row[3])."','".trim($row[4])."','".trim($row[5])."','".strtoupper(trim($row[6]))."','".strtoupper(trim($row[7]))."','$date')");
	
	}
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
	echo '<script>
	alert("Paid Students Uploaded Successfully!")
	location.href="student.php"
		</script>'; 
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> Oops</b>&nbsp; No Data Found.
                            </div>';
	}
		
		
	   ////////////////////////
	}
	
	
}

if(isset($_POST['delete_deferment'])){
	mysqli_query($con,"delete from deferment where id='".$_POST['delete_deferment']."'");
}

if(isset($_POST['delete_role'])){
	mysqli_query($con,"delete from sub_admin_role where id='".$_POST['delete_role']."'");
}

if(isset($_POST['upload_role'])){
	$sss=mysqli_query($con,"select * from sub_admin_role where user_id='".$_POST['upload_role']."' AND pfn='".$_POST['sub_admin_pfn']."' AND role='".$_POST['sub_role']."'");
	if(mysqli_num_rows($sss)==0){
		
	$qry=mysqli_query($con,"insert into sub_admin_role(user_id,pfn,role,date) values('".$_POST['upload_role']."','".$_POST['sub_admin_pfn']."','".$_POST['sub_role']."','$date')");
		
		if($qry){
			
			echo '<script>
	alert("Role Assigned Successfully!")
	location.href="sub_admin_role.php"
		</script>';
			
		}else{
			echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS: </b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
		}
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Role already assigned.
                            </div>';
	}
}



if(isset($_POST['upload_deferment'])){
	$ams=explode("_",$_POST['d_semester']);
	$rad=mysqli_query($con,"select * from deferment where matric_no='".trim($_POST['d_matric_no'])."' AND semester_num='".$ams[0]."' AND semester_description='".$ams[1]."' AND session='".$_POST['d_session']."' AND student_category='".$_POST['category']."'");
	if(mysqli_num_rows($rad)==0){
		
		$qry=mysqli_query($con,"insert into deferment(matric_no,semester_num,semester_description,session,date,student_category) values('".trim($_POST['d_matric_no'])."','".$ams[0]."','".$ams[1]."','".$_POST['d_session']."','$date','".$_POST['category']."')");
		if($qry){
			
			echo '<script>
	alert("Deferment Request Uploaded Successfully!")
	location.href="deferments.php"
		</script>'; 
			
		}else{
			echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; Unable to complete operation, please try again later.
                            </div>';
		}
		
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Student deferment request for the selected semester/session already uploaded.
                            </div>';
	}
	
}


if(isset($_POST['upload_subadmin'])){ //pfn 	lastname 	othernames 	email 	password 
	$fad=mysqli_query($con,"select * from sub_admin where email='".trim($_POST['d_email'])."' OR pfn='".trim($_POST['d_pfn'])."'");
	if(mysqli_num_rows($fad)==0){
		$password=sha1('portalsubadmin001');
		$qry=mysqli_query($con,"insert into sub_admin(pfn,lastname,othernames,email,password,status) values('".trim($_POST['d_pfn'])."','".trim($_POST['d_lastname'])."','".trim($_POST['d_othernames'])."','".trim($_POST['d_email'])."','$password',1)");
		
		if($qry){

$message = '<html><body>';
$message .= '<div align="center" style="padding:10px;">
<img src="https://'.$site_url.'img/d_logo.png" style="width:230px;" alt="LASU"></div>';
$message .= '<div style="border:1px solid #0033cc; padding:15px;"><h1 style="color:#0040ff; text-align:center;">Dear '.ucfirst($_POST['d_lastname']).',</h1>';
$message .= '<p style="font-size:17px; color:black;">This is to inform you that your account has been created successfully on the result processing portal as the system Sub-Admin. You login details are stated below.</p>';
$message .= '<p style="color:black; font-size:17px; font-weight:600;text-decoration:underline;">Login Details.</p>';

$message .= '<p style="color:black; font-size:19px;"><b>PF Number : </b>'.$_POST['d_pfn'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Email : </b>'.$_POST['d_email'].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>Default Password : </b>portalsubadmin001</p>';
$message .= '<p style="color:black; font-size:17px;">Click the button below to navigate to your login portal</p>';
$message .= '<div align="center"><a href="'.$site_url.'subadmin/" style="background-color:deepskyblue;padding:8px;color:white;">Sub Admin Login Portal</a></div>';

$message .= '<br><small style="color:#4d4d4d;float:right;"> Lagos State University, Ojo.</small><div style="clear:both;"></div>';
$message .= '</div></body></html>';

require "../PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $site_host;                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $site_username;                     //SMTP username
            $mail->Password   = $site_password;                               //SMTP password
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = 587;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
            $mail->setFrom($site_email, 'LASU Student Results Management Portal');
            $mail->addAddress(trim($_POST['d_email']), '');     //Add a recipient
            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = 'LASU Student Results Management Portal Sub-Admin Account Creation';
            $mail->Body    = $message;
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
			$mail->send(); // to send the composed mail
			
	echo '<script>
	alert("Sub-Admin Added Successfully!")
	location.href="sub_admin.php"
	</script>';
		}else{
			
			echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Unable to complete operation, please try again later.
                            </div>';
			
		}
		
		
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; User already added.
                            </div>';
	}
}

if(isset($_POST['reset_sub_pass'])){
	$passw='portalsubadmin'.rand(1,100);
	$r_password=sha1($passw);
	$eff=explode("_",$_POST['reset_sub_pass']);
	$apc=mysqli_query($con,"update sub_admin set password='$r_password' where id='".$eff[0]."'");
	if($apc){
		$message = '<html><body>';
$message .= '<div align="center" style="padding:10px;">
<img src="https://'.$site_url.'img/d_logo.png" style="width:230px;" alt="LASU"></div>';
$message .= '<div style="border:1px solid #0033cc; padding:15px;"><h1 style="color:#0040ff; text-align:center;">Dear Sub Admin,</h1>';
$message .= '<p style="font-size:17px; color:black;">You account password has been reset successfully.</p>';

$message .= '<p style="color:black; font-size:19px;"><b>Email : </b>'.$eff[1].'</p>';
$message .= '<p style="color:black; font-size:19px;"><b>New Default Password : </b>'.$passw.'</p>';
$message .= '<p style="color:black; font-size:17px;">Click the button below to navigate to your login portal</p>';
$message .= '<div align="center"><a href="'.$site_url.'subadmin/" style="background-color:deepskyblue;padding:8px;color:white;">Sub Admin Login Portal</a></div>';

$message .= '<br><small style="color:#4d4d4d;float:right;"> Lagos State University, Ojo.</small><div style="clear:both;"></div>';
$message .= '</div></body></html>';

require "../PHPMailer/PHPMailerAutoload.php";
		 $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $site_host;                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $site_username;                     //SMTP username
            $mail->Password   = $site_password;                               //SMTP password
            // $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port = 587;                                    //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
            $mail->setFrom($site_email, 'LASU Student Results Management Portal');
            $mail->addAddress($eff[1], '');     //Add a recipient
            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = 'LASU Student Results Management Portal Sub-Admin Account Password Reset';
            $mail->Body    = $message;
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
			$mail->send(); // to send the composed mail
			
			echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "New Default Password: '.$passw.'",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="sub_admin.php";
		});
			</script>';
			
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
}


if(isset($_POST['upload_blacklist'])){
	
	if($_POST['semester']=='forever' || $_POST['session']=='forever'){
			$b_sem=$b_ses='forever';
		}else{
			$b_sem=$_POST['semester'];
			$b_ses=$_POST['session'];
		}
	
	$aja=mysqli_query($con,"select * from blacklist where matric_no='".trim($_POST['matric_no'])."' AND semester='$b_sem' AND session='$b_ses' AND student_category='".$_POST['student_category']."'");
	if(mysqli_num_rows($aja)==0){
		
		
		
		$ccc=mysqli_query($con,"insert into blacklist(matric_no,semester,session,date,student_category) values('".trim($_POST['matric_no'])."','$b_sem','$b_ses','$date','".$_POST['student_category']."')");
		if($ccc){
			echo '<script type="text/javascript">
        swal({   
			title: "SUCCESS",   
             type: "success", 
			text: "Student added to blacklist",
			confirmButtonColor: "#2ecd99",   
		},
		function(){
			window.location="student.php";
		});
			</script>';
		}else{
			echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Unable to complete operation, please try again later.
                            </div>';
		}
		
		
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Student already blacklisted under the selected semester and session.
                            </div>';
	}
}

if(isset($_POST['delete_blacklist'])){
	mysqli_query($con,"delete from blacklist where id='".$_POST['delete_blacklist']."'");
}




if(isset($_POST['update_correction'])){
	
	$ata=mysqli_query($con,"select * from correction_window");
	
	$ama=mysqli_query($con,"select * from semester where session!=''");
	
if(mysqli_num_rows($ama)>0){ // to check if semeter exits
	
	$amp=mysqli_query($con,"select * from semester where upload_control=1");
	
if(mysqli_num_rows($amp)>0 && $_POST['correction_switch']==1){	// to check if result uploading portal is not opened

echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Kindly close the result uploading window.
                            </div>';

}else{

	if(mysqli_num_rows($ata)>0){
		
		$qss=mysqli_query($con,"update correction_window set status='".$_POST['correction_switch']."',date='$date'");
		
	}else{
		
		$qss=mysqli_query($con,"insert into correction_window(status,date) values('".$_POST['correction_switch']."','$date')");
		
	}
	
	if($qss){
		echo '<script>
		alert("Result correction window Updated!")
		window.location="setting.php"
		</script>';
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; Unable to complete operation, please try again later.
                            </div>';
	}
	
}
	
}else{
	echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <strong>OOPS :</strong>&nbsp; No semester or session set.
                            </div>';
}
}


if(isset($_POST['delete_course_requirement'])){
	mysqli_query($con,"delete from course_requirement where id='".$_POST['delete_course_requirement']."'");
}

if(isset($_POST['search_course_req'])){

	$gay=mysqli_query($con,"select * from course_requirement where student_category='".$_POST['s_category']."' AND dep_code='".$_POST['s_department']."' AND semester_num='".$_POST['s_semester']."' AND year_entry='".$_POST['s_level']."' order by course_code asc");
	if(mysqli_num_rows($gay)>0){
	$_SESSION['s_search']='true';	
	$_SESSION['s_level']=$_POST['s_level'];
	$_SESSION['s_department']=$_POST['s_department'];	
	$_SESSION['s_semester']=$_POST['s_semester'];
	$_SESSION['s_category']=$_POST['s_category'];
		echo '<script>
		location.href="course_requirement.php"
		</script>';
	}else{
		echo '<div class="alert alert-dismissible alert-danger">
				<strong>Oh Sorry!</strong> No course found matching the searched query.
              </div>';
	}
}


if(isset($_POST['upload_course_req'])){
	//	course_code 	description 	unit 	status 	semester_num 	dep_code 	year_entry 	student_category 
	
	$S_target_file = "temp_excel/".basename($_FILES["attachment"]["name"]);
	$S_Type = strtolower(pathinfo($S_target_file,PATHINFO_EXTENSION));
	
	if($S_Type !='xlsx' && $S_Type !='xls'){
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
              <b><i class="fa fa-exclamation" style="margin-top:;"></i> OOPS</b>&nbsp; File type not allowed.
                            </div>';
	}else{
		/////////////////////////
		
	$fn=$_SESSION['delsuresultadminid'].time();
	move_uploaded_file($_FILES["attachment"]["tmp_name"],$fn.'.'.$S_Type);			
	$f=$fn.'.'.$S_Type;
	//////////////////////////
	include 'simplexlsx.class.php';
    $xlsx = new SimpleXLSX( $f );
    $fp = fopen( $fn.'.csv', 'w');
    foreach( $xlsx->rows() as $fields ) {
        fputcsv( $fp, $fields);
    }
    fclose($fp);
	///////////////////
	
	$file = fopen($fn.'.csv', "r");
	$no=0;
    while ($row = fgetcsv($file)) { 
	
	$awa=mysqli_query($con,"select * from semester where semester='".(int)$row[4]."'");
	$slash=strchr(trim($row[5]),"/");
	
	$aca=mysqli_query($con,"select * from course_requirement where course_code='".$row[0]."' AND semester_num='".(int)$row[4]."' AND dep_code='".$_POST['department']."' AND year_entry='".trim($row[5])."' AND LCASE(student_category)='".strtolower($_POST['category'])."'");
	
	if(strtolower(trim($row[0]))!='course code' && strtolower(trim($row[0]))!='' && strtolower(trim($row[1]))!='course description' && $slash==true && strlen($row[2])==1 && strlen($row[5])>5 && mysqli_num_rows($awa)>0 && is_nan((int)trim($row[3]))!=1 && is_nan((int)trim($row[4]))!=1 && mysqli_num_rows($aca)==0){
	
	//	course_code 	description 	unit 	status 	semester_num 	dep_code 	year_entry 	student_category 
		
	$qry=mysqli_query($con,"insert into `course_requirement`(course_code,description,unit,status,semester_num,dep_code,year_entry,student_category,date) 
	values('".strtoupper(trim($row[0]))."',\"".htmlspecialchars(strtoupper(trim($row[1])))."\",'".(int)$row[3]."','".trim($row[2])."','".trim($row[4])."','".$_POST['department']."','".trim($row[5])."','".strtolower($_POST['category'])."','$date')");
	if($qry){
	$no=$no+1;
	}
    }
    }
    fclose($file);
	unlink($f);
	unlink($fn.'.csv');
	if($no>0){
		
	echo '<script>
	alert("'.$no.' Course Requirements Uploaded Successfully!")
	location.href="course_requirement.php"
		</script>'; 
	}else{
		echo '<div class="alert alert-danger alert-dismissible" role="alert" style="display:block; padding:10px;">
                               <b><i class="fa fa-exclamation" style="margin-top:;"></i> Oops</b>&nbsp; No data found or requirement(s) already uploaded.
                            </div>';
	}
		
		
	   ////////////////////////
	}
	
	
}





?>

 <script src="../vendors/bower_components/jquery/dist/jquery.min.js"></script>

<script>
jQuery().ready(function(){
	
	
		$("select#status_signal").change(function(){
			var status_signal =$(this).val();
			if(status_signal !=''){
				var str=status_signal.split('_');
				if(str[3]==1){
					$("div#control_session").show();
				}else{
					$("div#control_session").hide();
				}
			}else{
				$("div#control_session").hide();
			}
			
		});
	
	
	$("form#form_submit3").on('submit',(function(e){
			e.preventDefault();
			
			$("div.error3").html("<p class='text-success'><i class='fa fa-spin fa-spinner'></i> Processing Request...</p>");
				$.ajax({
						type: "POST",
                        url: "operation1.php",
                        data: new FormData(this),
						contentType:false,
						processData:false,
                        cache: false,
                        success: function(data){ 
						$("div.error3").html(data);
						}
    });			
	
	
		}));
	
	
	$("form#form_submit2").on('submit',(function(e){
			e.preventDefault();
			
			$("div.error2").html("<p class='text-success'><i class='fa fa-spin fa-spinner'></i> Processing Request...</p>");
				$.ajax({
						type: "POST",
                        url: "operation1.php",
                        data: new FormData(this),
						contentType:false,
						processData:false,
                        cache: false,
                        success: function(data){ 
						$("div.error2").html(data);
						}
    });			
	
	
		}));
		
	$("form#form_submit1").on('submit',(function(e){
			e.preventDefault();
			
			$("div.error").html("<p class='text-success'><i class='fa fa-spin fa-spinner'></i> Processing Request...</p>");
				$.ajax({
						type: "POST",
                        url: "operation1.php",
                        data: new FormData(this),
						contentType:false,
						processData:false,
                        cache: false,
                        success: function(data){ 
						$("div.error").html(data);
						}
    });			
	
	
		}));
});
</script>