<?php

namespace App\Controllers;
use \CodeIgniter\Controller;
use App\Models\User_model;
use App\Libraries\fpdf;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Gsp extends BaseController
{
	public $session;
	public $encrypter;
	public $fpdf;
	//public $portal_config;

	public function __construct(){
		
		$this->fpdf = new FPDF();
		$this->session = \Config\Services::session();
		$this->encrypter = \Config\Services::encrypter();
		//$this->portal_config = $this->gsp_model->get_portal_config();
		
	}

	public function index(){
		return view("gsp/login");
	}

	public function logout(){
		$this->session->remove('logged_gsp');
		$this->session->remove('name');
		$this->session->remove('department');
		$this->session->destroy();
		return redirect()->to(base_url()."/gsp");		
	}
	
	public function login_checker()
	{
		if($this->request->getMethod() == 'post'){
			$email = $this->request->getVar("email");
			$password = $this->request->getVar("password");

			$check_login = $this->gsp_model->verify_gsp($email);

			if($check_login){
				if(password_verify($password, $check_login['password'])){
					$this->session->set('gsp_logged', true);
					$this->session->set('id', $check_login['id']);
					$this->session->set('email', $email);
					$this->session->set('name', $check_login['fullname']);
					
					/*$dept_id = $check_login['join_department'];
					$department = $this->gsp_model->get_department_name($dept_id);
					$faculty = $this->gsp_model->get_faculty_name(17);*/
					
					/*$this->session->set('department', $department['title']);
					$this->session->set('faculty', $faculty[0]->title);*/
					$this->session->set('current_session', $this->portal_config['reg_session']);
					//$this->session->set('dept_id', $dept_id);
				
					return redirect()->to('dashboard');
				}else{
					$this->session->setTempdata('loginError', 'Incorrect Password', 3);
					return redirect()->to('index');
				}
				
			}else{
				$this->session->setTempdata('loginError', 'Email does not Exist', 3);
				return redirect()->to('index');
			}
	}

	} // end of login checker
	
	public function dashboard()
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}
		$data = [
			'page_title' => 'Dashboard',
			'page_subtitle' => '',
			'user' => $this->session->get('name'),
			'gsp_model' => $this->gsp_model,
			'id' => $this->session->get('id'),
			'c_num' => count($this->gsp_model->get_courses()),
			'courses' => $this->gsp_model->get_courses()
		];
		//$data['user'] = $this->session->get('logged_hod');
		return view("gsp/dashboard", $data);
		
	}

	public function password(){

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}
		if($this->request->getMethod() == 'post'){
		    $pass = password_hash($this->request->getVar('pass1'), PASSWORD_BCRYPT);
            $error = '';
            $success = '';
			if($this->gsp_model->update_password($this->session->get('id'), $pass)){
				$success = "Password updated successfully";
			}else{
				$error = "Oops! Something went wrong. Try later.";
			}

            $output = array(
                'error'		=>	$error,
                'success'	=>	$success
            );
        	echo json_encode($output);
		}else{
    		$data = [
    			'page_title' => 'Settings',
    			'page_subtitle' => 'Change Password',
    			'user' => $this->session->get('name')
    		];
    		
    		return view('gsp/change_password', $data);
		}
		
	}

	public function track_uploaded_results()
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}
		$data = [
			'page_title' => 'My Results',
			'page_subtitle' => 'Track Result',
			'user' => $this->session->get('name'),
			'id' => $this->session->get('id')
		];

		$staff_no = $this->session->get('id');
		$data['result'] = $this->gsp_model->get_course_allocation($staff_no, '2020/2021');
		
		return view("gsp/track_uploaded_results", $data);

	}

	public function course_submitted($result_id)
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}
		$data = [
			'page_title' => 'My Results',
			'user' => $this->session->get('name'),
			'id' => $this->session->get('id')
		];

		$id = str_replace(",", "/", $result_id);

		$staff_no = $this->session->get('id');
		$data['submission'] = $this->gsp_model->get_marks($id);
		$data['detail'] = $this->gsp_model->get_course_detail_($id);

		
		return view("gsp/course_submitted", $data);

	}

	public function view_courses()
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}

		$semester = !empty($this->request->getVar('semester')) ? urldecode($this->request->getVar('semester')) : false;
		$level = !empty($this->request->getVar('level')) ? urldecode($this->request->getVar('level')) : false;

		$data = [
			'page_title' => 'Courses',
			'page_subtitle' => 'View Courses',
			'semester' => $semester,
			'level' => $level,
			'courses' => $this->gsp_model->get_courses_filter($semester, $level)
		];
		
		return view("gsp/view_courses", $data);
	}

	public function view_student_enrollments()
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp/login");	
		}
		$data = [
			'page_title' => 'Courses',
			'page_subtitle' => 'Students'
		];
		
		return view("gsp/view_student_enrollments", $data);
		
	}

	public function download_result_template()
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}
		$data = [
			'page_title' => 'My Results',
			'page_subtitle' => 'Download Template',
			'courses' => $this->gsp_model->get_courses()
		];
	
		return view("gsp/download_result_template", $data);
	}

	public function upload_exam_result()
	{

		if(!session()->has('gsp_logged')){
			return redirect()->to(base_url()."/gsp");	
		}

		$upload_deadline = '';
        if($this->portal_config['erps_upload_deadline'] == NULL || $this->portal_config['erps_upload_deadline'] == 'NULL' || $this->portal_config['erps_upload_deadline'] == '' || $this->portal_config['erps_upload_deadline'] == '0000:00:00'){
          $upload_deadline = '';
        }else{
          $upload_deadline = 'on '.date("d F, Y", strtotime($this->portal_config['erps_upload_deadline']));
        }

		$data = [
			'page_title' => 'My Results',
			'page_subtitle' => 'Upload Result',
			'upload_status' => $this->portal_config['erps_upload_status'],
			'upload_deadline' => $upload_deadline,
			'courses' => $this->gsp_model->get_courses()
		];
		
		return view("gsp/upload_exam_result", $data);
		
	}


	//List of enrolled students
	function get_program_enrolled($course_code)
	{

		$course_code = urldecode($course_code);
		$staff_no = $this->session->get('id');
		$programme = $this->gsp_model->get_allocated_programmes($staff_no, $course_code, '2020/2021');
		
		$value = [];
		$output = "";
		$output .= '<div class="form-group">
					<label class="label"><b>Select Programme:</b></label>
					<select class="form-control select2" name="programme" id="programmesField" onchange="spawn_students()" required> 
					<option>Programme</option>';
		$program = explode(',',$programme['programmes_allocated_to']);
		foreach($program as $prog){
			$name = $this->gsp_model->get_program_ccode($prog);
			$title =  $name[0]->title;
			$programme_id =  $name[0]->id;                               
			$output .= "<option value = ".$programme_id.">".$title."</option>";                                            
		}
		$output .= "</select></div>";			
		echo $output;
	}

	//View download sheet template
	function get_allocated_program_enrolled($course_code, $session)
	{

		$course_code = urldecode($course_code);
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$programmes = $this->gsp_model->get_programmes($course_code, $session);
		
		$output = "";
		
		if($programmes){
			$output .= '<div class="form-group">
					<label>Select Programme:</label>
					<select class="form-control select2" name="programme" id="programmesField" onchange="spawn_button()" required> 
						<option selected disabled>- Select Programme -</option>';
			//$program = explode(',',$programme['programmes_allocated_to']);
			foreach($programmes as $prog){                            
				$output .= "<option value = ".$prog->awarded_programme.">".$prog->title."</option>";                                   
			}
			$output .= "</select></div>";
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> No student enrollment in this course for the selected session</div>';
		}
				
		echo $output;
	}

	function get_allocated_courses_enrolled($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('id');
		$course = $this->gsp_model->get_courses();
		
		$value = [];
		$output = "";
		//if($this->gsp_model->check_allocation_instance($staff_no, $session)){
			$output .= '<div class="form-group">
					<label><b>Select Course:</b></label><br/>
					<select class="form-control select2" name="course" id="courseField" onchange="spawn_allocated_programmes()" required> 
					<option>Course</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		/*}else{
			$output .= "<br/><br/><strong><h4>There is no course allocation for this session</h4></strong>";
		}*/
				
		echo $output;
	}

	//Enrolled students
	function get_allocated_courses_enrolled_students($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		//$staff_no = $this->session->get('id');
		$course = $this->gsp_model->get_course_allocation($session);
		
		$value = [];
		$output = "";
		//if($this->gsp_model->check_allocation_instance($staff_no, $session)){
			$output .= '<div class="form-group">
					<label>Select Course:</label>
					<select class="form-control select2" style="width: 100%;" name="course" id="courseField" onchange="spawn_allocated_programmes_enrollment()" required> 
					<option selected disabled>- Select Course -</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		/*}else{
			$output .= "<br/><br/><strong><h4>There is no course allocation for this session</h4></strong>";
		}*/
				
		echo $output;
	}

	//Enrolled Students
	function get_allocated_program_enrollment($course_code, $session)
	{

		$course_code = urldecode($course_code);
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		//$staff_no = $this->session->get('id');
		$programme = $this->gsp_model->get_allocated_programmes($course_code, $session);
		
		$value = [];
		$output = "";
		
		if($programme){
			$output .= '<div class="form-group">
					<label><b>Select Programme:</b></label><br/>
					<select class="form-control select2" name="programme" id="programmesField" onchange="spawn_enrollment_list()" required> 
					<option selected disabled>- Select Programme -</option>';
			foreach($programme as $prog){
				$output .= "<option value = ".$prog->awarded_programme.">".$prog->title."</option>";                             
			}
			$output .= "</select></div>";
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> No student enrollment in the course ('.$course_code.') for the selected session</div>';
		}
				
		echo $output;
	}

	//Enrolled students
	function get_allocated_courses_students($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('id');
		$course = $this->gsp_model->get_course_allocation($staff_no, $session);
		
		$value = [];
		$output = "";
		if($this->gsp_model->check_allocation_instance($staff_no, $session)){
			$output .= '<div class="form-group">
					<label><b>Select Course:</b></label>
					<label class="select">                                                                                        
					<select class="form-control select2" name="course" id="courseField" onchange="spawn_allocated_programmes()" required> 
					<option>Course</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		}else{
			$output .= "<br/><br/><strong><h4>There is no course allocation for this session</h4></strong>";
		}
				
		echo $output;
	}


	//View download sheet template
	function get_allocated_programme_upload($course_code, $session)
	{

		$course_code = urldecode($course_code);
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$programmes = $this->gsp_model->get_programmes($course_code, $session);
		
		$output = "";
		
		if($programmes){
			$output .= '<div class="form-group">
					<label>Select Programme:</label>
					<select class="form-control select2" name="programme" id="programmesField" onchange="spawn_upload_button_direct(), spawn_upload_button_sheet()" required> 
						<option selected disabled>- Select Programme -</option>';
			//$program = explode(',',$programme['programmes_allocated_to']);
			foreach($programmes as $prog){                            
				$output .= "<option value = ".$prog->awarded_programme.">".$prog->title."</option>";                                   
			}
			$output .= "</select></div>";
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> No student enrollment in this course for the selected session</div>';
		}
				
		echo $output;
	}

	function get_allocated_courses_upload($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('id');
		$course = $this->gsp_model->get_course_allocation($staff_no, $session);
		
		$value = [];
		$output = "";
		if($this->gsp_model->check_allocation_instance($staff_no, $session)){
			$output .= '<div class="form-group">
						<label class="label"><b>Select Course:</b></label><br/>
						<select class="form-control select2" name="course" id="courseField" onchange="spawn_allocated_programmes_upload()" required> 
						<option>Course</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		}else{
			$output .= "<br/><br/><strong><h4>There is not result for this session yet</h4></strong>";
		}
				
		echo $output;
	}

	
	public function get_course_allocations($session){
		
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
        $id = $this->session->get('id');
		$list = $this->gsp_model->get_course_allocation($id, $session);
		
		$output = "";
		$view_dialog = "";
		if($list){	
			$output .= "<div class='row'  >
	
			<div class='col-md-12 table-responsive' > 
			<table id='example1' class='table table-bordered table-striped'>
					<thead>
				    <tr>
						<th>S/N</th> 
						<th>Course Code</th>
						<th>Course Title</th>
						<th>Semester</th>
						<th>Level</th>
						<th>Programmes</th>
						
					</tr>
			   </thead>
			<tbody>";
			 $i = 1;
                             
                    foreach($list as $l):
                    
						$output .= "<tr>";
						$output .= "<td>".$i++."</td>";                     
						$output .= "<td>".$l->id."</td>";
						$output .= "<td>".$l->title."</td>";
						$output .= "<td>".$l->semester."</td>";
						$output .= "<td>".$l->level."</td>";
						$output .= "<td>";
						$programmes_array = explode(",", $l->programmes_allocated_to);
						$array_lenth = count($programmes_array);
						$counter = 1;
						foreach($programmes_array as $prog){
							$value = "#".$prog;
							
							if($array_lenth == $counter){
								$output .= "<a href = ".$value." data-toggle='modal'>".$prog."</a>";
							}else{
								$output .= "<a href = ".$value." data-toggle='modal'>".$prog."</a>, ";
							}
							$counter++;

							//Students enrollment per programme
							$programme_id = $this->gsp_model->get_programme_detail_by_ccode($prog);
							$students_enrollemnt = $this->gsp_model->get_enrolled_students($programme_id['id'], $l->id, $session);
							
							$view_dialog .= '<div class="modal fade" id='.$prog.'>
							<div class="modal-dialog modal-lg">
							  <div class="modal-content">
								<div class="modal-header">
								  <h5 class="modal-title"><span class="badge badge-secondary">Course: </span> '.$l->id.': '.$l->title.'<br/><span class="badge badge-secondary">
								  Programme: </span> '.$programme_id['title'].'<br/><span class="badge badge-secondary">Session: </span> '.$session.'</h5>
								  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								  </button>
								</div>
								<div class="modal-body">
								
								<table id="example1" class="table table-bordered table-striped">
								<thead>
								<tr>
									<th>S/N</th> 
									<th style="width:15%" >Registration Number</th>
									<th style="width:45%" >Full Name</th>
									<th>Level</th>
									<th>Email</th>
									<th>Phone No.</th>
								</tr>
								</thead>
								<tbody>';

								$index = 1;
								foreach($students_enrollemnt as $se){
									$view_dialog .= "<tr>";
									$view_dialog .= "<td>".$index++."</td>";                  
									$view_dialog .= "<td>".$se->registration_no."</td>";
									$view_dialog .= "<td>".$se->first_name." ".$se->last_name." ".$se->middle_name."</td>";
									$view_dialog .= "<td>".$se->level."</td>";
									$view_dialog .= "<td>".$se->email."</td>";
									$view_dialog .= "<td>".$se->phone."</td>";
									$view_dialog .= "</tr>";
								}
								
								$view_dialog .="</tbody>
								</table>
								</div>
								</div>
								</div>
								</div>";
								//End of students enrollment per programme
						}
						$output .= "<t/d>";
						$output .= "</tr>";

						
								
                   
                    endforeach; 
                       		
			$output .="</tbody>
			</table>
			</div>
			</div>";
	}else {
		$output .= "No course allocation for this session";
	}
		
		echo $output;
		echo $view_dialog;

	}

	public function get_uploaded_results($session){
		
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
		$list = $this->gsp_model->get_uploaded_results($session);
		
		$output = "";
		$view_dialog = "";
		$edit_dialog = "";
		
		if($list){
			
			
			$output .= "<div class='row'  >
	
			<div class='col-md-12 table-responsive' > 
			<table id='example1' class='table table-bordered table-striped'>
					<thead>
				    	<tr>
							<th>S/N</th>
							<th>Course Code</th>
							<th>Course Title</th>
							<th>Programme</th> 						
							<th>Session</th>
							<th>Created at</th>											
							<th>Updated at</th>
							<th>Status</th>	
							<th class='text-center'>Action</th>
						</tr>
			        </thead>
			<tbody>";
			 $index = 1;
                             
                    foreach($list as $l):
						
						$view_id = $l->id."_view";
						$edit_id = $l->id."_edit";

						$view_value = "#".$l->id."_view";
						$edit_value = "#".$l->id."_edit";

						$output .= "<tr>";
						$output .= "<td>".$index++."</td>";                  
						$output .= "<td>".$l->course_id."</td>";
						$output .= "<td>".$l->title."</td>";
						$output .= "<td>".$l->programme_title."</td>"; 						
						$output .= "<td>".$l->session."</td>";
						$output .= "<td>".$l->created_at."</td>";
						$output .= "<td>".$l->updated_at."</td>";
						if($l->submission_status == 'Pending' || $l->submission_status == 'Rejected'){
						    $stat = $l->submission_status == 'Pending'? 'warning' : 'danger';
							$output .= "<td><span class='badge badge-".$stat."'>".$l->submission_status."</span></td>";						
							$output .= '<td class="text-center"><a title="View" class="btn btn-info btn-xs" href = '.$view_value.'  data-toggle="modal" disabled><i class="fas fa-eye"></i></a>';				
							$output .= ' <a title="Edit" class="btn btn-warning btn-xs"  href = '.$edit_value.'  data-toggle="modal" ><i class="fas fa-edit"></i></a>';
							$output .= ' <a title="Submit" class="btn btn-success btn-xs submit_btn" data-id='.$l->id.'><i class="fas fa-check"></i></a>';
							$output .= ' <a title="Delete" class="btn btn-danger btn-xs delete_btn" data-id='.$l->id.'><i class="fas fa-trash"></i></a></td>';
						}else{
							$output .= "<td><span class='badge badge-success'>".$l->submission_status."</span></td>";												
							$output .= '<td class="text-center"><a class="btn btn-info btn-xs" href = '.$view_value.'  data-toggle="modal" ><i class="fas fa-eye"></i></a></td>';
						}
						$output .= '</td>';
						$output .= "</tr>";
						
						$view_dialog .= '<div class="modal fade" id='.$view_id.' >
							<div class="modal-dialog modal-lg">
							  <div class="modal-content">
								<div class="modal-header">
								  <h5 class="modal-title"><span class="badge badge-secondary">Course: </span>'.$l->course_id.': '.$l->title.'<br/>
								  <span class="badge badge-secondary">Programme: </span>'.$l->programme_title.'<br/>
								  <span class="badge badge-secondary">Session: </span>'.$l->session.'</h5>
								  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								  </button>
								</div>
								<div class="modal-body">
								
								<table id="example11" class="table table-bordered table-striped">
								<thead>
								<tr>
									<th>S/N</th> 
									<th >Registration Number</th>
									<th>Full Name</th>
									<th>Score</th>
									<th>Grade</th>
								</tr>
								</thead>
								<tbody>';
			
								$result = $this->gsp_model->get_marks($l->id);
								$i = 1;
								foreach($result as $res){
									$view_dialog .= '<td>'.$i++.'</td>';
									$view_dialog .= '<td>'.$res->reg_no.'</td>';
									$view_dialog .= '<td>'.$res->first_name.' '.$res->middle_name.' '.$res->last_name.'</td>';
									$view_dialog .= '<td>'.$res->exam_marks.'</td>';
									$view_dialog .= '<td>'.$res->grade.'</td>';
									$view_dialog .= '</tr>';
								}
								
								$view_dialog .="</tbody>
								</table>
								</div>
								</div>
								</div>
								</div>";
								
								$edit_dialog .= '<div class="modal fade" id='.$edit_id.' >
							<div class="modal-dialog modal-xl">
							  <div class="modal-content">
								<div class="modal-header">
								  <h5 class="modal-title"><span class="badge badge-secondary">Course: </span>'.$l->course_id.': '.$l->title.'<br/>
								  <span class="badge badge-secondary">Programme: </span>'.$l->programme_title.'<br/>
								  <span class="badge badge-secondary">Session: </span>'.$l->session.'</h5>
								  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								  </button>
								</div>
								<div class="modal-body">';
								$edit_dialog .= '<table id="example1" class="table table-bordered table-striped">
								<thead>
								<tr>
									<th>S/N</th> 
									<th style="width:15%" >Registration Number</th>
									<th style="width:45%" >Full Name</th>
									<th>Score</th>
									<th>Grade</th>
								</tr>
								</thead>
								<tbody>';
			
								$result = $this->gsp_model->get_marks($l->id);
								$i = 1;
								
								foreach($result as $res){
									$fullname = $res->first_name." ".$res->middle_name." ".$res->last_name;
									$edit_dialog .= '<td>'.$i++.'</td>';
									$edit_dialog .= "<td><input type = 'text' name = 'reg_no' class='form-control' value = ".$res->reg_no."  readonly></td>";
									$edit_dialog .= "<td><input type = 'text' name = 'name' class='form-control' value = '".$fullname."'  readonly></td>";
									$edit_dialog .= "<td><input type = 'text' name = '".$res->reg_no."_exam' class='form-control' id = '".$res->reg_no."_exam' onchange = exam_validation('".$res->reg_no."') value = ".$res->exam_marks." ></td>";
									$edit_dialog .= "<td><input type = 'text' name = '".$res->reg_no."_grade' class='form-control' id = '".$res->reg_no."_grade' value = ".$res->grade." readonly></td>";
									
									$edit_dialog .= '</tr>';
								}
								
								$edit_dialog .="</tbody>
								</table>
								
								</div>
								<div class='modal-footer justify-content-between'>
								<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
								<button class='btn btn-primary save' type = 'submit' name = 'edit_result' value = '".$l->id."'>Save Changes</button>
								</div>
								</div>
								</div>
								</div>";
						
                    endforeach; 
                       		
			$output .="</tbody>
			</table>
			</div>
			</div>";

			

	}else {
		$output .= '<div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> No result(s) submitted for this session</div>';
	}  
		
		echo $output;
		echo $view_dialog;
		echo $edit_dialog;

	}

    //View list of enrolled students
	function get_students_enrolled($session, $course, $programme)
	{
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
		$course = urldecode($course);
		$programme = urldecode($programme);
		
		$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session);
		$output = "";
		$output .= "<div class='row'  >

		<div class='col-md-12 table-responsive' > 
		<table id='example1' class='table table-bordered table-striped'>
				<thead>
               <tr>
                    <th>S/N</th> 
					<th>Full Name</th>
					<th>Registration Number</th>
					<th>Level</th>
					<th>Email</th>
					<th>Phone No.</th>
					
                  </tr>
           </thead>
		<tbody>";
		$i = 1;
		foreach($student as $stud){		
			$output .= "<tr><td>".$i."</td>";
			$output .= "<td>".$stud->first_name." ".$stud->last_name." ".$stud->middle_name."</td>";
			$output .= "<td>".$stud->registration_no."</td>";
			$output .= "<td>".$stud->level."</td>";
			$output .= "<td>".$stud->email."</td>";
			$output .= "<td>".$stud->phone."</td></tr>";
			$i++;
		}							

		$output .="</tbody>
		</table>
		</div>
		</div>";
		echo $output;
	}

	public function download_button($session, $course, $programme)
	{
		$programme = urldecode($programme);
		$course = urldecode($course);
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
		$output = "";

		$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session);

		if($student){
			$output .= "<button type='submit' class='btn btn-primary btn-lg btn-block'><i class='fas fa-download'></i> Download</button>";	
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible">No student enrollment from the selected programme for the course '.$course.'</div>';
		}		
		echo $output;
		
	}

	public function upload_sheet_button($programme, $course, $session)
	{	

		$programme = urldecode($programme);
		$course = urldecode($course);
		$session = urldecode($session);
		$session_value = str_replace("_", "/", $session);

		$output = "";
		$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session_value);
		if($student){

			$prog_detail = $this->gsp_model->get_programme_details($programme);
			
			$faculty = $prog_detail[0]->ftitle;
			$department = $prog_detail[0]->dtitle;
			$programme_title = $prog_detail[0]->ptitle;


			$ccode = $this->lecturer_model->get_programme_detail($programme)['ccode'];
			$year = (int) substr($session, 2, 2);
			$username = $ccode.$year;

			$id = $course."_".$programme."_".$username."_".$session;

			//$id = $course."_".$programme."_GSP_".$session;

			$course_detail = $this->lecturer_model->get_course_detail($course);

			if(!$this->lecturer_model->check_result_submitted($id)){

				$output .= '<div class="row">
				
				<div class="col-md-12">
				 
						<div class="form-group">				
							<button type = "button" class="btn btn-primary btn-lg btn-block" data-toggle="modal" data-target="#direct_modal"><i class="fas fa-upload"></i> Upload Result Sheet</button>
						</div>
					
				  </div>
				  </div>

				<div class="row">
				  <div class="col-md-12">
				 
				  <div class="modal fade" id="direct_modal">
				  <div class="modal-dialog modal-lg">
					<div class="modal-content">
					  <div class="modal-header">
						<h4 class="modal-title">Upload Result Sheet</h4>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						  <span aria-hidden="true">&times;</span>
						</button>
					  </div>
					  <div class="modal-body">
					  <input type = "text" name = "session" value = '.$session_value.' hidden>
					  <input type = "text" name = "course" value = '.$course.' hidden>
					  <input type = "text" name = "programme" value = '.$programme.' hidden>
						<div class="form-group">
						<label class="label"><b>Select Excel Sheet:</b></label><br/>
								  <div class="form-line">
									  <input type="file" name="xlsFileToUpload" id="xlsFileToUpload" class="form-control" data-validate="required" data-message-required="Required" required accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
								  </div>
						  </div>
					  </div>
					  <div class="modal-footer justify-content-between">
						<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
						<button type = "submit" name = "save_excel" class="btn btn-primary">Submit</button>
					  </div>
					</div>
					<!-- /.modal-content -->
				  </div>
				  <!-- /.modal-dialog -->
				</div>	
			
				  </div>
					</div>

					<div class="modal fade" id="modal-xl">
	        <div class="modal-dialog modal-xl">
	          <div class="modal-content">
	            <div class="modal-header">
	              <h4 class="modal-title">Result Sheet <br/>'.$course.'  '.$course_detail['title'].'<br>'.$programme_title.' Programme'.'<br/>'.$session.' Session'.'</h4>
	              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
	                <span aria-hidden="true">&times;</span>
	              </button>
	            </div>
	            <div class="modal-body">
				';
		   
		   $output .= '
	            </div>
	            <div class="modal-footer justify-content-between">
	              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	              <button type="submit" name = "save_individual" class="btn btn-primary">Submit</button>
	            </div>
	          </div>
	          <!-- /.modal-content -->
	        </div>
	        <!-- /.modal-dialog -->
	      </div>';

			}else{
				$output .= '<br/><div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> You have already uploaded result for this course</div>';
			}			
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible">No student enrollment from the selected programme for the course '.$course.'</div>';
		}	
		
		echo $output;
		
	}

	public function upload_direct_button($programme, $course, $session)
	{	

		$programme = urldecode($programme);
		$course = urldecode($course);
		$session = urldecode($session);
		$session_value = str_replace("_", "/", $session);

		$output = "";
		$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session_value);
		if($student){

			$prog_detail = $this->gsp_model->get_programme_details($programme);
			
			$faculty = $prog_detail[0]->ftitle;
			$department = $prog_detail[0]->dtitle;
			$programme_title = $prog_detail[0]->ptitle;

			$ccode = $this->lecturer_model->get_programme_detail($programme)['ccode'];
			$year = (int) substr($session, 2, 2);
			$username = $ccode.$year;

			$id = $course."_".$programme."_".$username."_".$session;

			//$id = $course."_".$programme."_GSP_".$session;

			$course_detail = $this->lecturer_model->get_course_detail($course);


			if(!$this->lecturer_model->check_result_submitted($id)){

				$output .= '<div class="row">
				
				<div class="col-md-12">
				  </div>
				  </div>
				<div class="row">
				  <div class="col-md-12">
						<div class="form-group">				
							<button type = "button" class="btn btn-primary btn-lg btn-block" data-toggle="modal" data-target="#modal-xl"><i class="fas fa-list"></i> Populate Result Direct</button>
						</div>
				  </div>
					</div>

					<div class="modal fade" id="modal-xl">
	        <div class="modal-dialog modal-xl">
	          <div class="modal-content">
	            <div class="modal-header">
	              <h5 class="modal-title">RESULT SHEET <br/><span class="badge badge-secondary">Course: </span> '.$course.':  '.$course_detail['title'].'<br><span class="badge badge-secondary">Programme: </span> '.$programme_title.' Programme'.'<br/><span class="badge badge-secondary">Session: </span> '.$session_value.'<br/><small><span class="badge badge-danger">Exam Entry: </span> NUMBERS and ABS=ABSENT, I=INCOMPLETE, AR=AWAIT RESULT </small></h5>
	              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
	                <span aria-hidden="true">&times;</span>
	              </button>
	            </div>
	            <div class="modal-body">
				<input type = "text" name = "session" value = '.$session_value.' hidden>
				<input type = "text" name = "course" value = '.$course.' hidden>
				<input type = "text" name = "programme" value = '.$programme.' hidden>
				<table id="example1" class="table table-bordered table-striped">
				<thead>
				<tr>
					<th>S/N</th> 
					<th style="width:15%" >Registration Number</th>
					<th style="width:45%" >Full Name</th>
					<th>Score</th>
					<th>Grade</th>
				</tr>
		   </thead>
		   <tbody>';
		   $i = 1;
					foreach($student as $stud){

						$fullname = $stud->first_name." ".$stud->middle_name." ".$stud->last_name;
						
						$output .= "<input type = 'text' name = 'course' class='form-control' value = ".$course." hidden>";
						$output .= '<tr><td>'. $i++.'</td>';

						$output .= "<td><input type = 'text' name = 'reg_no' class='form-control' value = ".$stud->registration_no."  readonly></td>";
						$output .= "<td><input type = 'text' name = 'name' class='form-control' value = '".$fullname."'  readonly></td>";
						$output .= "<td><input type = 'text' name = '".$stud->registration_no."_exam' class='form-control' id = '".$stud->registration_no."_exam'  onchange = exam_validation('".$stud->registration_no."') required style='text-transform: uppercase' maxlength='3'></td>";
						$output .= "<td><input type = 'text' name = '".$stud->registration_no."_grade' class='form-control' id = '".$stud->registration_no."_grade'  readonly></td>";
						$output .= '</tr>';
					
					}
		   $output .= '</tbody>
		   </table>
	            </div>
	            <div class="modal-footer justify-content-between">
	              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	              <button type="submit" name = "save_individual" class="btn btn-primary">Submit</button>
	            </div>
	          </div>
	        </div>
	      </div>';

			}else{
				$output .= '<br/><div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> You have already uploaded result for this course</div>';
			}				
		}

		echo $output;
		
	}


	public function result_action(){

		if($this->request->getMethod() == 'post'){
			if($this->request->getPost('action') == 'submit'){
	            $error = '';
	            $success = '';
				
				if($this->gsp_model->submit_result_instance($this->request->getPost('id'))){
					$success = "Result submitted successfully";
				}else{
					$error = "Oops! Something went wrong. Try later.";
				}
    
	            $output = array(
	                'error'		=>	$error,
	                'success'	=>	$success
	            );
            	echo json_encode($output);

			}

			if($this->request->getPost('action') == 'delete'){
	            $error = '';
	            $success = '';
				
				if($this->gsp_model->delete_marks($this->request->getPost('id'))){
					if($this->gsp_model->delete_result_instance($this->request->getPost('id'))){
						$success = "Examinations Officer deleted successfully";
					}
					
				}else{
					$error = "Oops! Something went wrong. Try later.";
				}
    
	            $output = array(
	                'error'		=>	$error,
	                'success'	=>	$success
	            );
            	echo json_encode($output);

			}

			/*if($this->request->getPost('action') == 'edit'){
	            $error = '';
	            $success = '';

				$result_id = $this->request->getPost('id');
				$current_result = $this->gsp_model->get_current_result($result_id);

					
				$update_data = "";
				foreach($current_result as $res){

					$reg_no = $res->reg_no;
					$ca = $reg_no.'_ca';
					$exam = $reg_no.'_exam';
					$total = $reg_no.'_total';
					$grade = $reg_no.'_grade';

					$ca_marks = $this->request->getVar($ca);
					$exam_marks = $this->request->getVar($exam);
					$total_marks = $this->request->getVar($total);
					$grade = $this->request->getVar($grade);
					
					$this->gsp_model->update_marks($result_id, $reg_no, $ca_marks, $exam_marks, $total_marks, $grade);
					//echo $reg_no." ".$ca_marks."  ".$exam_marks. " ".$total_marks." ".$result_id."<br/>";
					
				}
				$date_time = date('Y-m-d H:i:s');
				
				if($this->gsp_model->update_result_instance($result_id, $date_time)){
					
						$success = "Result Edited successfully";
					
				}else{
					$error = "Oops! Something went wrong. Try later.";
				}
    
	            $output = array(
	                'error'		=>	$error,
	                'success'	=>	$success
	            );
            	echo json_encode($output);

			}*/

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

				$error = '';
	            $success = '';

				$result_id = $this->request->getVar("edit_result");
				$current_result = $this->gsp_model->get_current_result($result_id);
	
				$update_data = "";
				foreach($current_result as $res){
	
					$reg_no = $res->reg_no;
					//$ca = $reg_no.'_ca';
					$exam = $reg_no.'_exam';
					//$total = $reg_no.'_total';
					$grade = $reg_no.'_grade';
	
					//$ca_marks = $this->request->getVar($ca);
					$exam_marks = $this->request->getVar($exam);
					$total_marks = $this->request->getVar($exam);
					$grade = $this->request->getVar($grade);
					
					$update_data = $this->gsp_model->update_marks($result_id, $reg_no, 0, $exam_marks, $total_marks, $grade);
					//echo $reg_no." ".$ca_marks."  ".$exam_marks. " ".$total_marks." ".$result_id."<br/>";
					//echo $result_id."<br/>";
					if($update_data){
						//return redirect()->to('track_uploaded_results');
					}else{
						//return redirect()->to('dashboard');
					}
	
				}
				$date_time = date('Y-m-d H:i:s');
				if($this->gsp_model->update_result_instance($result_id, $date_time)){
					return redirect()->to(base_url('gsp/track_uploaded_results'))->with('editSuccess', 'Saved Successfully');
				}else{
					return redirect()->to(base_url('gsp/track_uploaded_results'))->with('editError', 'Oops! Something went wrong');
				}

				$output = array(
	                'error'		=>	$error,
	                'success'	=>	$success
	            );
            	echo json_encode($output);
	
			}
			
		}

		/*else if(isset($_POST['submit_result'])){

			$result_id = $this->request->getVar("submit_result");
			
			if($this->gsp_model->submit_result_instance($result_id)){
				return redirect()->to('track_uploaded_results');
			}else{
				return redirect()->to('track_uploaded_results');
			}

		}else if(isset($_POST['delete_result'])){
			
			$result_id = $this->request->getVar("delete_result");

			if($this->gsp_model->delete_marks($result_id)){
				
				if($this->gsp_model->delete_result_instance($result_id)){
					return redirect()->to('track_uploaded_results');
				}else{
					return redirect()->to('track_uploaded_results');
				}
			}else{

			}
			
		}*/

		
	}

	public function upload_sheet(){

		$programme = $this->request->getPost("programme");
		$course = $this->request->getPost("course");
		$session = $this->request->getPost("session");
		$session_value = str_replace("/", "_", $session);
		$staff_id = $this->session->get('id');

		$insert_data = "";
		
		$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session);

		$allocation_detail = $this->gsp_model->get_allocation_detail($course, $staff_id, $session);
		
		$ccode = $this->lecturer_model->get_programme_detail($programme)['ccode'];
		//$year = $allocation_detail['programme_username'];

		//$username = $ccode."20";

		$year = (int) substr($session, 2, 2);
		$username = $ccode.$year;
		$level = $this->lecturer_model->get_course_detail($course)['level'];
		$semester = $this->lecturer_model->get_course_detail($course)['semester'];
		$dept_id = 0;
		$id = $course."_".$programme."_".$username."_".$session_value;
		
		$data_instance = [
			'id' => $id,
			'lecturer_id' => 'GSP',
			'course_id' => $course,
			'programme_id' => $programme,
			'dept_id' => $dept_id,
			'to_dept_id' => $this->lecturer_model->get_programme_detail($programme)['department_id'],
			'programme_username' => $username,
			'semester' => $semester,
			'level' => $level,
			'session' => $session,
			'submission_status' => 'Pending',
			'eo_status' => 'Pending',
			'hod_status' => 'Pending',
			'created_at' => date('Y-m-d H:i:s'),
			'updated_at' => date('Y-m-d H:i:s')							
		];
		
		
			$rules = [
				'xlsFileToUpload' => 'required'
			];
				
				$markSheet = $this->request->getFile('xlsFileToUpload');

				if($markSheet->isValid() && !$markSheet->hasMoved()){       

					$name = "File.xlsx";
					$path = './uploads/Staff/';
					$get_file = $path.$name;
					
					if(file_exists($get_file)){
						unlink($get_file);

					}

					if($markSheet->move(FCPATH.'uploads/Staff',$name)){
						$inputFileName = './uploads/Staff/File.xlsx';
						$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
						//$course_code = $spreadsheet->getActiveSheet()->getCell('D10')->getValue();
						//$session = $spreadsheet->getActiveSheet()->getCell('B10')->getValue(); 
						$sheet = $spreadsheet->getActiveSheet()->toArray(null,true,true,true);

						$totalrows = count($sheet);
						$insert_data = "";
						$i = 1;

											
						if($this->gsp_model->save_result_instance($data_instance)){
							foreach($sheet as $row){
								if($i >= 14){
									$reg_no      = $row['B'];;
									$ca_marks    = 0;
									$exam_marks  = $row['D'];
									$total_marks = $exam_marks;
									$grade       = $row['E'];

						
									$data = [
										'course_id' => $course,
										'reg_no' => $reg_no,
										'ca_marks' => $ca_marks,
										'exam_marks' => $exam_marks,
										'total_marks' => $exam_marks,
										'grade' => $grade,
										'result_instance_id' => $id						
									];
						
									$insert_data = $this->gsp_model->save_marks($data);

								
							}
								$i++;
							}//end foreach
						
						}
						
					}else{
						echo $image->getErrorString().' '.$image->getError();
					}

				}
			

        if ($insert_data) {
            return redirect()->to(base_url('gsp/track_uploaded_results'))->with('uploadSuccess', 'Result Uploaded Successfully');
        }else{
            return redirect()->to(base_url('gsp/track_uploaded_results'))->with('uploadError', 'Oops! Something went wrong');
        }
	}

   public function upload_direct(){

		$programme = $this->request->getPost("programme");
		$course = $this->request->getPost("course");
		$session = $this->request->getPost("session");
		$session_value = str_replace("/", "_", $session);
		$staff_id = $this->session->get('id');

		$insert_data = "";
		
		$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session);

		//$allocation_detail = $this->gsp_model->get_allocation_detail($course, $staff_id);
		
		$ccode = $this->lecturer_model->get_programme_detail($programme)['ccode'];
		//$year = $allocation_detail['programme_username'];

		$username = $ccode."20";
		$level = $this->lecturer_model->get_course_detail($course)['level'];
		$semester = $this->lecturer_model->get_course_detail($course)['semester'];
		$dept_id = $this->session->get('dept_id');
		$id = $course."_".$programme."_".$username."_".$session_value;
		
		$data_instance = [
			'id' => $id,
			'lecturer_id' => 'GSP',
			'course_id' => $course,
			'programme_id' => $programme,
			'dept_id' => 0,
			'to_dept_id' => $this->lecturer_model->get_programme_detail($programme)['department_id'],
			'programme_username' => $username,
			'semester' => $semester,
			'level' => $level,
			'session' => $session,
			'submission_status' => 'Pending',
			'eo_status' => 'Pending',
			'hod_status' => 'Pending',
			'created_at' => date('Y-m-d H:i:s'),
			'updated_at' => date('Y-m-d H:i:s')							
		];

		//$student = $this->gsp_model->get_enrolled_students($programme, $course, $session_value);
				
		
		if($this->gsp_model->save_result_instance($data_instance)){
		
			foreach($student as $stud){

				$reg_no = $stud->registration_no;
				//$ca = $reg_no.'_ca';
				$exam = $reg_no.'_exam';
				//$total = $reg_no.'_total';
				$grade = $reg_no.'_grade';

				//$ca_marks = $this->request->getVar($ca);
				$exam_marks = $this->request->getVar($exam);
				//$total_marks = $this->request->getVar($total);
				$grade = $this->request->getVar($grade);

				$data = [
					'course_id' => $course,
					'reg_no' => $reg_no,
					'ca_marks' => 0,
					'exam_marks' => $exam_marks,
					'total_marks' => $exam_marks,
					'grade' => $grade,
					'result_instance_id' => $id					
				];

				$insert_data = $this->gsp_model->save_marks($data);
			}
		}

		if ($insert_data) {
            return redirect()->to(base_url('gsp/track_uploaded_results'))->with('uploadSuccess', 'Result Uploaded Successfully');
        }else{
            return redirect()->to(base_url('gsp/track_uploaded_results'))->with('uploadError', 'Oops! Something went wrong');
        }


   }

	public function download_sheet(){

		if($this->request->getMethod() == 'post'){

			$session = $this->request->getPost("session");
			$session = str_replace("_", "/", $session);
			$programme = $this->request->getPost("programme");
			$course = $this->request->getPost("course");
			
			//$gsp_id = $this->session->get("id");
			
			//$allocation_detail = $this->gsp_model->get_allocation_detail($course, $gsp_id, $session);

			//$programme_title = $this->gsp_model->get_programme_detail($programme)['title'];
			$prog_detail = $this->gsp_model->get_programme_details($programme);
			
			$faculty = $prog_detail[0]->ftitle;
			$department = $prog_detail[0]->dtitle;
			$programme_title = $prog_detail[0]->ptitle;

			$course_detail = $this->lecturer_model->get_course_detail($course);

			$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session);
			
			$spreadsheet = new Spreadsheet();

			$row_counter =14;
			//STYLING THE PAGE
			$spreadsheet->getActiveSheet()->setShowGridlines(true);
			$spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(13, 13);
			$spreadsheet->getActiveSheet()->getStyle('A13:E13')->getFill()
				->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
				->getStartColor()->setARGB('B2BEB5');
			$spreadsheet->getDefaultStyle()->getFont()->setSize(12);
			$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
			$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
			$spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
			//$spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
			//$spreadsheet->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
			//$spreadsheet->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
			//$spreadsheet->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);

			//$spreadsheet->getActiveSheet()->mergeCells('A18:E22');
			$spreadsheet->getActiveSheet()->getCell('A1')->setValue('YUSUF MAITAMA SULE UNIVERSITY, KANO');
			$spreadsheet->getActiveSheet()->mergeCells('A1:E1');

			$spreadsheet->getActiveSheet()->getCell('A2')->setValue('GENERAL STUDIES PROGRAMME (GSP) UNIT');
			$spreadsheet->getActiveSheet()->mergeCells('A2:E2');
			$spreadsheet->getActiveSheet()->mergeCells('A3:E3');

			$spreadsheet->getActiveSheet()->getCell('A4')->setValue("FACULTY OF ".strtoupper($faculty));
			$spreadsheet->getActiveSheet()->mergeCells('A4:E4');
			$spreadsheet->getActiveSheet()->getCell('A5')->setValue("DEPARTMENT OF ".strtoupper($department));
			$spreadsheet->getActiveSheet()->mergeCells('A5:E5');

			$spreadsheet->getActiveSheet()->getCell('A6')->setValue('RESULT SHEET');
			$spreadsheet->getActiveSheet()->mergeCells('A6:E6');
			$spreadsheet->getActiveSheet()->mergeCells('A7:E7');

			$spreadsheet->getActiveSheet()->getCell('A8')->setValue("COURSE TITLE: ".$course_detail['title']);
			$spreadsheet->getActiveSheet()->mergeCells('A8:E8');

			$spreadsheet->getActiveSheet()->getCell('A9')->setValue('');
			$spreadsheet->getActiveSheet()->mergeCells('A9:C9');

			$spreadsheet->getActiveSheet()->getCell('B10')->setValue('Session: '.$session);
			$spreadsheet->getActiveSheet()->getCell('C10')->setValue('Semester: '.$course_detail['semester']);
			$spreadsheet->getActiveSheet()->getCell('D9')->setValue('Date: '.date("d/m/Y")); // Date Downloaded
			$spreadsheet->getActiveSheet()->mergeCells('D9:E9');
			$spreadsheet->getActiveSheet()->getCell('D10')->setValue('CODE: '.$course);
			$spreadsheet->getActiveSheet()->mergeCells('D10:E10');

			//$spreadsheet->getActiveSheet()->getCell('A11')->setValue('      CA Entry: NUMBERS ONLY');
			$spreadsheet->getActiveSheet()->getCell('A11')->setValue('');
			$spreadsheet->getActiveSheet()->mergeCells('A11:E11');

			$spreadsheet->getActiveSheet()->getCell('A12')->setValue('      EXAM Entry: NUMBERS and    ABSENT=ABS,    INCOMPLETE=I,    AWAIT RESULT=AR');
			$spreadsheet->getActiveSheet()->mergeCells('A12:E12');
			// END OF STYLES

			// SET SHEET SECURITY 

			$spreadsheet->getActiveSheet()
				->getProtection()->setPassword('123');
			$spreadsheet->getActiveSheet()
				->getProtection()->setSheet(true);
			$spreadsheet->getActiveSheet()
				->getProtection()->setSort(true);
			$spreadsheet->getActiveSheet()
				->getProtection()->setInsertRows(true);
			$spreadsheet->getActiveSheet()
				->getProtection()->setFormatCells(true);

			// END OF SECURITY

			$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooterDrawing();
			$drawing->setName('PhpSpreadsheet logo');
			$drawing->setPath('assets/img/yumsuk_logo.jpg');
			$drawing->setHeight(100);
			$drawing->setWidth(100);
			//$spreadsheet->getActiveSheet()->getHeaderFooter()->addImage($drawing, \PhpOffice\PhpSpreadsheet\Worksheet\HeaderFooter::IMAGE_HEADER_LEFT);
			$drawing->setCoordinates('A1');
			$drawing->setWorksheet($spreadsheet->getActiveSheet());
			//

			$worksheet = $spreadsheet->getActiveSheet(); 
			// set excel headers  

			$worksheet->getCell('A13')->setValue('S/No.');
			$worksheet->getCell('B13')->setValue('Registration No.');
			$worksheet->getCell('C13')->setValue('Name');
			$worksheet->getCell('D13')->setValue('Score');
			$worksheet->getCell('E13')->setValue('Grade');
			/*$worksheet->getCell('F13')->setValue('Total');
			$worksheet->getCell('G13')->setValue('Grade');*/
				//end of headers
			$count =1;
			//$row_counter =14;

			foreach($student as $stud){

				$worksheet->getCell('A'.$row_counter)->setValue($count);
				$worksheet->getCell('B'.$row_counter)->setValue($stud->registration_no);
				$worksheet->getCell('C'.$row_counter)->setValue($stud->middle_name." ".$stud->last_name." ".$stud->first_name);
				//$worksheet->getCell('D'.$row_counter)->setValue($row['ca_marks']);
				//$worksheet->getCell('E'.$row_counter)->setValue($row['exam_marks']);
				// calculating total marks
				
				/*$worksheet->getCell('F'.$row_counter)->setValue('=IF(E'.$row_counter.'="ABS","ABS",IF(E'.$row_counter.'="AR","AR",IF(E'.$row_counter.'="I","I",IF(E'.$row_counter.'="","-",D'.$row_counter.'+E'.$row_counter.'))))');*/
				/*$worksheet->getCell('E'.$row_counter)->setValue('=IF(OR(D'.$row_counter.'="ABS",D'.$row_counter.'="I",D'.$row_counter.'="AR",D'.$row_counter.'="-",D'.$row_counter.'=""),"-",IF(D'.$row_counter.'>=70,"A",IF(D'.$row_counter.'>=60,"B",IF(D'.$row_counter.'>=50,"C",IF(D'.$row_counter.'>=45,"D",IF(D'.$row_counter.'>=40,"E",IF(D'.$row_counter.'>=0,"F","-")))))))');*/
				$worksheet->getCell('E'.$row_counter)->setValue('=IF(D'.$row_counter.'="ABS", "ABS", IF(D'.$row_counter.'="I", "I", IF(D'.$row_counter.'="AR", "AR", IF(D'.$row_counter.'="", "-", IF(D'.$row_counter.'>=70,"A",IF(D'.$row_counter.'>=60,"B",IF(D'.$row_counter.'>=50,"C",IF(D'.$row_counter.'>=45,"D",IF(D'.$row_counter.'>=40,"E",IF(D'.$row_counter.'>=0,"F","-"))))))))))');
				
				// $worksheet->getCell('G'.$row_counter)->setValue($row['grade']);
					
				// CONDITIONAL STYLILNG / expected to color all F students as red.
				$conditional1 = new \PhpOffice\PhpSpreadsheet\Style\Conditional();
				$conditional1->setConditionType(\PhpOffice\PhpSpreadsheet\Style\Conditional::CONDITION_CELLIS);
				$conditional1->setOperatorType(\PhpOffice\PhpSpreadsheet\Style\Conditional::OPERATOR_LESSTHAN);
				$conditional1->addCondition('40');
				$conditional1->getStyle()->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);
				$conditional1->getStyle()->getFont()->setBold(true);

				$conditionalStyles = $spreadsheet->getActiveSheet()->getStyle('D'.$row_counter.'')->getConditionalStyles();
				$conditionalStyles[] = $conditional1;

				$spreadsheet->getActiveSheet()->getStyle('D'.$row_counter.'')->setConditionalStyles($conditionalStyles);
				// END CONDITIONAL STYLING
				$count = $count + 1;
				$row_counter = $row_counter + 1;
		}

			$row_counter = $row_counter - 1;
			// ENABLE EDITING OF CA AND EXAMS MARKS
			$spreadsheet->getActiveSheet()->getStyle('D14:D'.$row_counter) // CA MARKS
				->getProtection()
				->setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED);

			/*$spreadsheet->getActiveSheet()->getStyle('E14:E'.$row_counter) // EXAM MARKS
				->getProtection()
				->setLocked(\PhpOffice\PhpSpreadsheet\Style\Protection::PROTECTION_UNPROTECTED);*/

			// END OF EDITING CA AND EXAM MARKS

			//Input Validation for CA
			/*$ca_validation = $spreadsheet->getActiveSheet()->getCell('D14')->getDataValidation();
			$ca_validation->setSqref('D14:D1048576');
			$ca_validation->setType(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_WHOLE );
            $ca_validation->setErrorStyle(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_STOP );
            $ca_validation->setAllowBlank(false);
            $ca_validation->setShowInputMessage(false);
            $ca_validation->setShowErrorMessage(true);
            $ca_validation->setErrorTitle("Error");
            $ca_validation->setError("Only Numbers within 0 and ".$allocation_detail['ca_range']." is allowed for Exam");
            $ca_validation->setPromptTitle('Validation de données');
            $ca_validation->setPrompt('Not allowed.');
            $ca_validation->setFormula1(0);
            $ca_validation->setFormula2($allocation_detail['ca_range']);*/
            //$ca_validation->setDataValidation("D14:D1048576");

			//Input Validation for Exam
			//$exam_validation = $spreadsheet->getActiveSheet()->getCell('D14')->getDataValidation();
			$exam_validation = $spreadsheet->getActiveSheet()->getDataValidation('D14:D1048576');
			//$exam_validation->setSqref('D14:D1048576');
			$exam_validation->setType(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_CUSTOM );
            $exam_validation->setErrorStyle(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::STYLE_STOP );
            $exam_validation->setAllowBlank(false);
            $exam_validation->setShowInputMessage(false);
            $exam_validation->setShowErrorMessage(true);
            $exam_validation->setErrorTitle("Error");
            $exam_validation->setError("Only Numbers between 0 and 100 is allowed for Exam");
            /*$exam_validation->setError("Only Numbers within 0 and ".$allocation_detail['exam_range']." is allowed for Exam");*/
            $exam_validation->setPromptTitle('Validation');
            $exam_validation->setPrompt('Not allowed.');
            /*$exam_validation->setFormula1(0);
            $exam_validation->setFormula2(100);*/
            $exam_validation->setFormula1('OR(D14="ABS", D14="I", AND(D14>=0, D14<=100))');
            //$exam_validation->setFormula2($allocation_detail['exam_range']);
			// BORDER AND ALIGNMENT
			$spreadsheet->getActiveSheet()->getStyle('A13:C'.$row_counter.'')
				->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_LEFT);
			$spreadsheet->getActiveSheet()->getStyle('D13:E'.$row_counter.'')
				->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
				// SET HEADERS TO CENTER
			$spreadsheet->getActiveSheet()->getStyle('A1:E9')
				->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

			$spreadsheet->getActiveSheet()->getStyle('A13:E'.$row_counter.'')    
				->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:E'.$row_counter.'') 
					->getBorders()->getBottom()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:E'.$row_counter.'') 
					->getBorders()->getLeft()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:E'.$row_counter.'') 
					->getBorders()->getRight()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:E'.$row_counter.'') 
					->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
			$spreadsheet->getActiveSheet()->getStyle('A13:E'.$row_counter.'')    
					->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A10:E10')    
					->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
						// SET FONT BOLD
				$spreadsheet->getActiveSheet()->getStyle('A1:E13')->getFont()->setBold(true);

					//END OF BORDER

				
			$writer = new Xlsx($spreadsheet);
			//$writer->save('hideMe123.xlsx');

			//header('Content-Type: Application/vnd.ms-excel');
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			//header('Content-Disposition: attachment; filename="hideMeTest5.xlsx"');
			header('Content-Disposition: attachment; filename= '.$course." ".$programme_title." ".$session." Result Sheet.xlsx");
			ob_end_clean();
			$writer->save('php://output');
			exit;

	}

	}

}
