<?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 Lecturer extends BaseController
{
	public $session;
	public $encrypter;
	public $fpdf;

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

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

	public function logout(){
		$this->session->remove('logged_lecturer');
		$this->session->remove('name');
		$this->session->remove('department');
		$this->session->remove('uid');
		$this->session->remove('id');
		$this->session->remove('staff_id');
		$this->session->remove('rank');
		$this->session->remove('email');
		$this->session->destroy();
		return redirect()->to(base_url()."/lecturer-login");		
	}
	
	public function login_checker()
	{
		if($this->request->getMethod() == 'post'){
			$staff_no = $this->request->getVar("staff_no");
			$password = $this->request->getVar("password");

			$check_login = $this->lecturer_model->verify_lecturer($staff_no);

			if($check_login){
				if(password_verify($password, $check_login[0]->password)){
					$this->session->set('lecturer_logged', true);
					$this->session->set('id', $check_login[0]->id);
					$this->session->set('uid', $check_login[0]->id);
					$this->session->set('staff_id', $check_login[0]->staff_id);
					$this->session->set('name', $check_login[0]->name);
					$this->session->set('rank', $check_login[0]->rank);
					$this->session->set('email', $staff_no);
					
					$dept_id = $check_login[0]->department;
					$department = $this->lecturer_model->get_department_name($dept_id);
					$faculty = $this->lecturer_model->get_faculty_name($dept_id);
					//$portal_config = $this->lecturer_model->get_portal_config();
					
					$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(base_url().'/lecturer-index');
				}else{
					$this->session->setTempdata('loginError', 'Incorrect Password', 3);
					return redirect()->to(base_url().'/lecturer-login');
				}
				
			}else{
				$this->session->setTempdata('loginError', 'Invalid Email or Staff No.', 3);
				return redirect()->to(base_url().'/lecturer-login');
			}
	}

	} // end of login checker

	public function dashboard()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$data = [
			'page_title' => 'Dashboard',
			'page_subtitle' => '',
			'user' => $this->session->get('name'),
			'lecturer_model' => $this->lecturer_model,
			'id' => $this->session->get('id'),
			'list' => $this->lecturer_model->get_course_allocation($this->session->get('uid'), $this->session->get('current_session'))
		];
		//$data['user'] = $this->session->get('logged_hod');
		return view("lecturer/dashboard", $data);
		
	}
	
	public function attendance(){

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$resultlist = false;
		$att = '';
		if($this->request->getMethod() == 'post'){
		    if($this->request->getVar('action') == 'search'){
    		    $att_date = $this->request->getVar('attdate');
    		    $course = $this->request->getVar('course');
    		    
    		    if($this->lecturer_model->check_attendance($course, $att_date)){
    		        $att = '<div class="alert alert-danger">Attendance already submitted. You can edit record</div>';
    		    }
    		    
        		$prog_ids = [];
        		$programme = $this->lecturer_model->get_allocated_programmes($this->session->get('uid'), $course, $this->session->get('current_session'));
        		$program = explode(',',$programme['programmes_allocated_to']);
        		foreach($program as $prog){
        			$res = $this->lecturer_model->get_program_ccode($prog);
        			array_push($prog_ids, $res[0]->id);                                           
        		}
        		$resultlist  = $this->lecturer_model->get_registered_students(implode(',', $prog_ids), $course, $this->session->get('current_session'));
		    }
		}
		$data = [
			'page_title' => 'Attendance',
			'page_subtitle' => 'Mark Attendance',
			'user' => $this->session->get('name'),
			'lecturer_model' => $this->lecturer_model,
			'id' => $this->session->get('id'),
			'resultlist' => $resultlist,
			'att' => $att,
			'courses' => $this->lecturer_model->get_course_allocation($this->session->get('uid'), $this->session->get('current_session'))
		];
		return view("lecturer/attendance", $data);
		
	}

	public function password(){

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		if($this->request->getMethod() == 'post'){
		    $pass = password_hash($this->request->getVar('pass1'), PASSWORD_BCRYPT);
            $error = '';
            $success = '';
			if($this->lecturer_model->update_password($this->session->get('uid'), $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('lecturer/change_password', $data);
		}
		
	}

	public function track_uploaded_results()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$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->lecturer_model->get_course_allocation($staff_no, '2020/2021');
		
		return view("lecturer/track_uploaded_results", $data);

	}

	public function course_submitted($result_id)
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$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->lecturer_model->get_marks($id);
		$data['detail'] = $this->lecturer_model->get_course_detail_($id);

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

	}

	public function view_course_allocations()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$data = [
			'page_title' => 'My Courses',
			'page_subtitle' => 'View My Courses',
			'user' => $this->session->get('name'),
			'id' => $this->session->get('id')
		];
		$staff_no = $this->session->get('uid');
		$data['result'] = $this->lecturer_model->get_course_allocation($staff_no, $this->session->get('current_session'));
		
		return view("lecturer/view_course_allocations", $data);
	}

	public function view_previous_courses()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$data = [
			'page_title' => 'My Previous Courses',
			'user' => $this->session->get('name')
		];
		$staff_no = $this->session->get('id');
		$data['result'] = $this->lecturer_model->get_previous_course_allocation($staff_no, '2020/2021');
		//$data['user'] = $this->session->get('logged_hod');
		echo view('templates/lecturer_header', $data);
		echo view('lecturer/view_previous_courses');
		echo view('templates/lecturer_footer');
		
	}

	public function view_student_enrollments()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$data = [
			'page_title' => 'My Courses',
			'page_subtitle' => 'My Students',
			'user' => $this->session->get('name'),
			'id' => $this->session->get('id')
		];

		$staff_no = $this->session->get('id');
		
		//$data['course'] = $this->lecturer_model->get_course_allocation($staff_no, '2020/2021');
		
		return view("lecturer/view_student_enrollments", $data);
		
	}

	public function download_result_sheet()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$data = [
			'page_title' => 'My Results',
			'page_subtitle' => 'Download Sheet',
			'user' => $this->session->get('name'),
			'id' => $this->session->get('id')
		];
		$staff_no = $this->session->get('id');
		
		//$data['course'] = $this->lecturer_model->get_course_allocation($staff_no, '2020/2021');
		
		return view("lecturer/download_result_sheet", $data);
		
	}

	public function upload_exam_result()
	{

		if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer/login");	
		}
		$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 = date("d F, Y", strtotime($this->portal_config['erps_upload_deadline']));
        }
		$data = [
			'page_title' => 'My Results',
			'page_subtitle' => 'Upload Result',
			'user' => $this->session->get('name'),
			'upload_status' => $this->portal_config['erps_upload_status'],
			'upload_deadline' => $upload_deadline,
			'id' => $this->session->get('id')
		];
		$staff_no = $this->session->get('id');
		
		$data['course'] = $this->lecturer_model->get_course_allocation($staff_no, '2020/2021');
		
		return view("lecturer/upload_exam_result", $data);
		
	}


	//List of enrolled students
	function get_program_enrolled($course_code)
	{
	    
	    if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

		$course_code = urldecode($course_code);
		$staff_no = $this->session->get('uid');
		$programme = $this->lecturer_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> 
					gsp</option>';
		$program = explode(',',$programme['programmes_allocated_to']);
		foreach($program as $prog){
			$name = $this->lecturer_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)
	{
	    
	    if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

		$course_code = urldecode($course_code);
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('uid');
		$programme = $this->lecturer_model->get_allocated_programmes($staff_no, $course_code, $session);
		
		$value = [];
		$output = "";
		
		$output .= '<div class="form-group">
				<label>Select Programme:</label>                                                                                     
				<select class="form-control select2" name="programme" id="programmesField" onchange="spawn_button()" required width="100%"> 
				<option selected disabled>- Programme -</option>';
		$program = explode(',',$programme['programmes_allocated_to']);
		foreach($program as $prog){
			$name = $this->lecturer_model->get_program_ccode($prog);
			$title =  $name[0]->title;
			$programme_id =  $name[0]->id;                               
			$output .= "<option value = ".$programme_id.">".$title."</option>";                                            
		}
		$output .= "</select> <i></i><b class='tooltip tooltip-bottom-right'>Labels</b></label></div>";
				
		echo $output;
	}

	function get_allocated_courses_enrolled($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('uid');
		$course = $this->lecturer_model->get_course_allocation($staff_no, $session);
		
		$value = [];
		$output = "";
		if($this->lecturer_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 selected disabled>Course</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"> No course allocation for the selected session</div>';
		}
				
		echo $output;
	}

	//Enrolled students
	function get_allocated_courses_enrolled_students($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('uid');
		$course = $this->lecturer_model->get_course_allocation($staff_no, $session);
		
		$value = [];
		$output = "";
		if($this->lecturer_model->check_allocation_instance($staff_no, $session)){
			$output .= '<div class="form-group">
					<label><b>Select Course:</b></label><br/>
					<select class="form-control select2" style="width: 100%;" name="course" id="courseField" onchange="spawn_allocated_programmes_enrollment()" required> 
					<option selected disabled>Course</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"> No course allocation for the selected session</div>';
		}
				
		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('uid');
		$programme = $this->lecturer_model->get_allocated_programmes($staff_no, $course_code, $session);
		
		$value = [];
		$output = "";
		
		$output .= '<div class="form-group">
				<label>Select Programme:</label>
				<select class="form-control select2" name="programme" id="programmesField" onchange="spawn_enrollment_list()" required width="100%"> 
				<option selected disabled>- Programme -</option>';
		$program = explode(',',$programme['programmes_allocated_to']);
		foreach($program as $prog){
			$name = $this->lecturer_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;
	}

	//Enrolled students
	function get_allocated_courses_students($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('uid');
		$course = $this->lecturer_model->get_course_allocation($staff_no, $session);
		
		$value = [];
		$output = "";
		if($this->lecturer_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 selected disabled>Course</option>';
		
			foreach($course as $co){
										
				$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";                                            
			}
			$output .= "</select></div>";	
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"> No course allocation for the selected session</div>';
		}
				
		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);
		$staff_no = $this->session->get('uid');
		$programme = $this->lecturer_model->get_allocated_programmes($staff_no, $course_code, $session);
		
		$value = [];
		$output = "";
		
		$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  width="100%"> 
				<option selected disabled>- Programme -</option>';
		$program = explode(',',$programme['programmes_allocated_to']);
		foreach($program as $prog){
			$name = $this->lecturer_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;
	}

	function get_allocated_courses_upload($session)
	{

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('uid');
		$course = $this->lecturer_model->get_course_allocation($staff_no, $session);
		
		$value = [];
		$output = "";
		if($this->lecturer_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 selected disabled>Course</option>';
		
			foreach($course as $co){
				if($co->level == 100){	
					$output .= "<option value = ".$co->id.">".$co->id. " ".$co->title."</option>";
				}                                            
			}
			$output .= "</select></div>";	
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"> No result for the selected session</div>';
		}
				
		echo $output;
	}

	
	public function get_course_allocations($session){
		
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
        $id = $this->session->get('uid');
		$list = $this->lecturer_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){

							//Students enrollment per programme
							$programme_id = $this->lecturer_model->get_programme_detail_by_ccode($prog);
							$students_enrollemnt = $this->lecturer_model->get_enrolled_students($programme_id['id'], $l->id, $session);				

							if($students_enrollemnt){
								$value = "#".$prog;
							
								if($array_lenth == $counter){
									$output .= "<a href = ".$value." class='btn btn-info' data-toggle='modal'>".$prog."</a>";
								}else{
									$output .= "<a href = ".$value." class='btn btn-info' data-toggle='modal'>".$prog."</a>, ";
								}
							
								$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-responsive">
									
									<table id="example11" class="table table1 table-bordered table-striped" style="font-size:13px" width="100%">
									<thead>
									<tr>
										<th>S/N</th> 
										<th>Registration Number</th>
										<th>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
								}else{
									if($array_lenth == $counter){
										$output .= "<a href ='javascript:void(0);' class='btn btn-info btn-no-data' data-toggle='modal'>".$prog."</a>";
									}else{
										$output .= "<a href ='javascript:void(0);' class='btn btn-info btn-no-data' data-toggle='modal'>".$prog."</a>, ";
									}
								}
								$counter++;
						}
						$output .= "<t/d>";
						$output .= "</tr>";

						
								
                   
                    endforeach; 
                       		
			$output .="</tbody>
			</table>
			</div>
			</div>";
	}else {
		$output .= '<br/><div class="alert alert-danger alert-dismissible"> No course allocation for the selected session</div>';
	}
		
		echo $output;
		echo $view_dialog;

	}

	public function get_uploaded_results($session){
		
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
        $id = $this->session->get('uid');
        $staff_id = $this->session->get('staff_id');
        
		$list = $this->lecturer_model->get_uploaded_results($id, $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 table1 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>CA</th>
									<th>Exam</th>
									<th>Total</th>
									<th>Grade</th>
								</tr>
								</thead>
								<tbody>';
			
								$result = $this->lecturer_model->get_marks($l->id);
								$i = 1;
								$color = '';
								if(!empty($result)){
    								foreach($result as $res){
    									if($res->grade == 'F'){
    										$color = 'text-danger';
    									}
    
    									$view_dialog .= '<tr class="'.$color.'">';
    									$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->ca_marks.'</td>';
    									$view_dialog .= '<td>'.$res->exam_marks.'</td>';
    									$view_dialog .= '<td>'.$res->total_marks.'</td>';
    									$view_dialog .= '<td>'.$res->grade.'</td>';
    									$view_dialog .= '</tr>';
    									$color = '';
    								}
								
		}
								
								$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>CA</th>
									<th>Exam</th>
									<th>Total</th>
									<th>Grade</th>
								</tr>
								</thead>
								<tbody>';
			
								$result = $this->lecturer_model->get_marks($l->id);
								$i = 1;
								
							if(!empty($result)){	
								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."_ca' class='form-control' id = '".$res->reg_no."_ca' onchange = ca_validation('".$res->reg_no."') value = ".$res->ca_marks." ></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."_total' class='form-control' id = '".$res->reg_no."_total' value = ".$res->total_marks." readonly></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 .= '<br/><div class="alert alert-danger alert-dismissible"> No result uploaded for the selected 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 = "";

		if($student){
			$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>";
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible">No student enrollment from the programme for this course</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){
		
			$lecturer_id = $this->session->get("uid");

			//$session = str_replace("_", "/", $session);
			
			//$id = $course."_".$programme.$session;
	        $allocation_detail = $this->lecturer_model->get_allocation_detail($course, $lecturer_id, $session_value);
			$ccode = $this->lecturer_model->get_programme_detail($programme)['ccode'];
			$year = $allocation_detail['programme_username'];

			$username = $ccode.$year;

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

			$programme_title = $this->lecturer_model->get_programme_detail($programme)['title'];
				
			$faculty = $this->session->get('faculty');
			$department = $this->session->get('department');

			$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"> Result already uploaded for the selected 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)
	{	
	    
	    if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

		$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);
		$portal_config = $this->lecturer_model->get_portal_config();
		if($student){
		    
		  if($portal_config['erps_upload_status']){
		
			$lecturer_id = $this->session->get("uid");

			//$session = str_replace("_", "/", $session);
			
			//$id = $course."_".$programme.$session;
	        $allocation_detail = $this->lecturer_model->get_allocation_detail($course, $lecturer_id, $session_value);
			$ccode = $this->lecturer_model->get_programme_detail($programme)['ccode'];
			$year = $allocation_detail['programme_username'];

			$username = $ccode.$year;

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

			$programme_title = $this->lecturer_model->get_programme_detail($programme)['title'];
				
			$faculty = $this->session->get('faculty');
			$department = $this->session->get('department');

			$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>CA</th>
					<th>Exam</th>
					<th>Total</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."_ca' class='form-control' id = '".$stud->registration_no."_ca' onchange = ca_validation('".$stud->registration_no."') required style='text-transform: uppercase' maxlength='4'></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='4'></td>";
						$output .= "<td><input type = 'text' name = '".$stud->registration_no."_total' class='form-control' id = '".$stud->registration_no."_total'  readonly></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>
	          <!-- /.modal-content -->
	        </div>
	        <!-- /.modal-dialog -->
	      </div>';

			}else{
				$output .= '<br/><div class="alert alert-danger alert-dismissible"> Result already uploaded for the selected course</div>';
			}	
			
		  }else{
		    $output .= '<br/><div class="alert alert-danger alert-dismissible">Result Uploaded is Closed</div>';
		  }
		}
		
		echo $output;
		
	}


	public function result_action(){
	    
	    if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

		if($this->request->getMethod() == 'post'){
			if($this->request->getPost('action') == 'submit'){
	            $error = '';
	            $success = '';
				
				if($this->lecturer_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->lecturer_model->delete_marks($this->request->getPost('id'))){
					if($this->lecturer_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->lecturer_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->lecturer_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->lecturer_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->lecturer_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);
					
					$update_data = $this->lecturer_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/>";
					//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->lecturer_model->update_result_instance($result_id, $date_time)){
					return redirect()->to(base_url('lecturer/track_uploaded_results'))->with('editSuccess', 'Saved Successfully');
				}else{
					return redirect()->to(base_url('lecturer/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->lecturer_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->lecturer_model->delete_marks($result_id)){
				
				if($this->lecturer_model->delete_result_instance($result_id)){
					return redirect()->to('track_uploaded_results');
				}else{
					return redirect()->to('track_uploaded_results');
				}
			}else{

			}
			
		}*/

		
	}

	public function upload_sheet(){
	    
	    if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

		$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('uid');

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

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

		$username = $ccode.$year;
		$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' => $staff_id,
			'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 = "";
						$data_result = array();
						
						$i = 1;
						
						
							foreach($sheet as $row){
								if($i >= 14){
								    
								    
									$reg_no      = $row['B'];
									//$ca_marks    = $row['D'];
									
									if($row['D'] == null){
									    $ca_marks = 0;
									}else{
									    $ca_marks = $row['D'];
									}
									if($row['E'] == null){
									   $exam_marks = 0; 
									}else{
									   $exam_marks = $row['E'];  
									}
									
									$total_marks = $row['F'];
									$grade       = $row['G'];
						
									$data = [
										'course_id' => $course,
										'reg_no' => $reg_no,
										'ca_marks' => $ca_marks,
										'exam_marks' => $exam_marks,
										'total_marks' => $total_marks,
										'grade' => $grade,
										'result_instance_id' => $id						
									];
									
									array_push($data_result, $data);
									
						
									//$insert_data = $this->lecturer_model->save_marks($data);
								
							}
								$i++;
							}//end foreach
							
							if(!$empty_flag){

        						if($this->lecturer_model->save_result_instance($data_instance)){
        						
        						    $insert_data = $this->lecturer_model->save_marks($data_result);
        						}
							} 
					}else{
						echo $image->getErrorString().' '.$image->getError();
					}

				}
			
            if(!$empty_flag){
                if($insert_data) {
                    return redirect()->to(base_url('lecturer-uploaded-results'))->with('uploadSuccess', 'Result Uploaded Successfully');
                }else{
                    return redirect()->to(base_url('lecturer-uploaded-results'))->with('uploadError', 'Oops! Something went wrong');
                }
	        }else{
	            return redirect()->to(base_url('lecturer-uploaded-results'))->with('uploadError', 'Oops! Empty Cell is not Allowed');
	        }
	}
	
   public function te(){
       $data[][] = "";
       $newdata =  array (
          'wpseo_title' => 'test',
          'wpseo_desc' => 'test',
          'wpseo_metakey' => 'test'
        );
        $newdata2 =  array (
          'wpseo_title' => 'test2',
          'wpseo_desc' => 'test2',
          'wpseo_metakey' => 'test2'
        );
        array_push($data, $newdata);
        array_push($data, $newdata2);
       
       print_r($data);
       
   }

   public function upload_direct(){
       
       if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

		$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('uid');

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

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

		$username = $ccode.$year;
		$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' => $staff_id,
			'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')							
		];

		//$student = $this->lecturer_model->get_enrolled_students($programme, $course, $session_value);
				
		
		if($this->lecturer_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' => $ca_marks,
					'exam_marks' => $exam_marks,
					'total_marks' => $total_marks,
					'grade' => $grade,
					'result_instance_id' => $id					
				];

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

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


   }

	public function download_sheet(){
	    
	    if(!session()->has('lecturer_logged')){
			return redirect()->to(base_url()."/lecturer-login");	
		}

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

			$session = $this->request->getPost("session");
			$session = str_replace("_", "/", $session);
			$programme = $this->request->getPost("programme");
			$course = $this->request->getPost("course");
			
			$lecturer_id = $this->session->get("uid");
			
			$allocation_detail = $this->lecturer_model->get_allocation_detail($course, $lecturer_id, $session);

			$programme_title = $this->lecturer_model->get_programme_detail($programme)['title'];
			
			$faculty = $this->session->get('faculty');
			$department = $this->session->get('department');

			$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:G13')->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:H1');

			$spreadsheet->getActiveSheet()->getCell('A2')->setValue('FACULTY OF '.$faculty);
			$spreadsheet->getActiveSheet()->mergeCells('A2:H2');
			$spreadsheet->getActiveSheet()->mergeCells('A3:H3');

			$spreadsheet->getActiveSheet()->getCell('A4')->setValue("DEPARTMENT OF ".$department);
			$spreadsheet->getActiveSheet()->mergeCells('A4:H4');
			$spreadsheet->getActiveSheet()->mergeCells('A5:H5');

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

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

			$spreadsheet->getActiveSheet()->getCell('A9')->setValue('STUDENTS YEAR: ...');
			$spreadsheet->getActiveSheet()->mergeCells('A9:H9');

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

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

			$spreadsheet->getActiveSheet()->getCell('A12')->setValue('      EXAM Entry: NUMBERS and    ABSENT=ABS,    INCOMPLETE=I,    AWAIT RESULT=AR');
			$spreadsheet->getActiveSheet()->mergeCells('A12:H12');
			// 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('CA');
			$worksheet->getCell('E13')->setValue('Exam');
			$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

				// $spreadsheet->getActiveSheet()->setCellValue('B8','=IF(C4>500,"profit","loss")');
				$e = $worksheet->getCell('F'.$row_counter)->getValue();
				$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.'="","-",round(D'.$row_counter.'+E'.$row_counter.',0)))))');
				/*$worksheet->getCell('G'.$row_counter)->setValue('=IF(OR(F'.$row_counter.'="ABS",F'.$row_counter.'="I",F'.$row_counter.'="AR",F'.$row_counter.'="-"),"-",IF(F'.$row_counter.'>=70,"A",IF(F'.$row_counter.'>=60,"B",IF(F'.$row_counter.'>=50,"C",IF(F'.$row_counter.'>=45,"D",IF(F'.$row_counter.'>=40,"E",IF(F'.$row_counter.'>=0,"F","-")))))))');*/

				$worksheet->getCell('G'.$row_counter)->setValue('=IF(F'.$row_counter.'="ABS", "ABS", IF(F'.$row_counter.'="I", "I", IF(F'.$row_counter.'="AR", "AR", IF(F'.$row_counter.'="-", "-", IF(F'.$row_counter.'>=69.5,"A",IF(F'.$row_counter.'>=59.5,"B",IF(F'.$row_counter.'>=49.5,"C",IF(F'.$row_counter.'>=44.5,"D",IF(F'.$row_counter.'>=39.5,"E",IF(F'.$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('F'.$row_counter.'')->getConditionalStyles();
				$conditionalStyles[] = $conditional1;

				$spreadsheet->getActiveSheet()->getStyle('F'.$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


			//$fm1 = '';
			//Input Validation for CA
			$ca_validation = $spreadsheet->getActiveSheet()->getDataValidation('D14:D1048576');
			//$ca_validation->setSqref('D14:D1048576');
			$ca_validation->setType(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_DECIMAL );
			//$ca_validation->setType(\PhpOffice\PhpSpreadsheet\Cell\DataValidation::TYPE_CUSTOM );
            $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 between 0 and ".$allocation_detail['ca_range']." is allowed for Exam");
            $ca_validation->setPromptTitle('Validation');
            $ca_validation->setPrompt('Not allowed.');
            
            //$ca_validation->setFormula1('OR(D14="ABS", D14="I", AND(D14>=0, D14<='.$allocation_detail['ca_range'].'))');
            $ca_validation->setFormula1(0);
            $ca_validation->setFormula2($allocation_detail['ca_range']);
            //$ca_validation->setDataValidation("D14:D1048576");

			//Input Validation for Exam
			$exam_validation = $spreadsheet->getActiveSheet()->getDataValidation('E14:E1048576');
			//$exam_validation->setSqref('E14: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 ".$allocation_detail['exam_range']." is allowed for Exam");
            $exam_validation->setPromptTitle('Validation');
            $exam_validation->setPrompt('Not allowed.');
            /*$exam_validation->setFormula1(0);
            $exam_validation->setFormula2($allocation_detail['exam_range']);*/
            $exam_validation->setFormula1('OR(E14="ABS", E14="I", AND(E14>=0, E14<='.$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:G'.$row_counter.'')
				->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
				// SET HEADERS TO CENTER
			$spreadsheet->getActiveSheet()->getStyle('A1:H9')
				->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);

			$spreadsheet->getActiveSheet()->getStyle('A13:G'.$row_counter.'')    
				->getBorders()->getTop()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:G'.$row_counter.'') 
					->getBorders()->getBottom()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:G'.$row_counter.'') 
					->getBorders()->getLeft()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:G'.$row_counter.'') 
					->getBorders()->getRight()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A13:G'.$row_counter.'') 
					->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID);
			$spreadsheet->getActiveSheet()->getStyle('A13:G'.$row_counter.'')    
					->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
			$spreadsheet->getActiveSheet()->getStyle('A10:H10')    
					->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN);
						// SET FONT BOLD
				$spreadsheet->getActiveSheet()->getStyle('A1:G13')->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;

	}

	}

}
