<?php

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

class Hod extends BaseController
{
	public $session;
	public $fpdf;

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

	public function login(){
		return view("hod/login");
	}
	
	public function login_checker()
	{
		if($this->request->getMethod() == 'post'){
			$email = $this->request->getPost("email");
			$password = $this->request->getPost("password");

			$check_login = $this->hod_model->verify_hod($email);

			if($check_login){
				if(password_verify($password, $check_login['password'])){
					//$portal_config = $this->hod_model->get_portal_config(1);
					
					$this->session->set('hod_logged', true);
					$this->session->set('id', $check_login['id']);
					$this->session->set('name', $check_login['title']);
					$this->session->set('faculty', $check_login['faculty_id']);
					$this->session->set('session', $this->portal_config['reg_session']);
					$this->session->set('current_session', $this->portal_config['reg_session']);

					$name = $this->hod_model->get_faculty_name($check_login['faculty_id']);

					$this->session->set('faculty_name',  $name['title']);
				
					return redirect()->to(base_url().'/head-index');
					
				}else{
					$this->session->setTempdata('loginError', 'Incorrect Password', 3);
					return redirect()->to(base_url().'/head-login');
				}
				
			}else{
				$this->session->setTempdata('loginError', 'Invalid Email Address', 3);
				return redirect()->to(base_url().'/head-login');
			}
	}

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

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		$data = [
			'page_title' => 'Dashboard',
			'page_subtitle' => '',
			'user' => $this->session->get('name')
		];

		$id = $this->session->get('id');
		$department = $this->session->get('name');
		$data['staff'] = $this->hod_model->get_staffs($id) == false ? 0 : count($this->hod_model->get_staffs($id));
		$data['students'] = $this->hod_model->get_all_students($id) == false ? 0 : count($this->hod_model->get_all_students($id));
		$data['programmes'] = $this->hod_model->get_programmes($id) == false ? 0 : count($this->hod_model->get_programmes($id));
		$data['courses'] = $this->hod_model->get_courses($department) == false ? 0 : count($this->hod_model->get_courses($department));
		$data['plist'] = $this->hod_model->get_programmes($id);
		$data['clist'] = $this->hod_model->get_courses($department);
		//$data['user'] = $this->session->get('logged_hod');
		return view('hod/dashboard', $data);
		
	}
	
	public function password(){

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		if($this->request->getMethod() == 'post'){
		    $pass = password_hash($this->request->getVar('pass1'), PASSWORD_BCRYPT);
            $error = '';
            $success = '';
			if($this->hod_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' => 'Manage Profile',
    			'page_subtitle' => 'Change Password',
    			'user' => $this->session->get('name')
    		];
    		
    		return view('hod/change_password', $data);
		}
		
	}
	
	public function profile(){

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		if($this->request->getMethod() == 'post'){
		    if($this->request->getVar('action') == 'sign'){
            	$id = $this->session->get('id');
            	
                $file = $this->request->getFile('image');
                
                if($file->move("uploads/signature/", $id)){
                    $success = 'Profile Image has been Updated Successfully';
            		$output = 1;
                }else{
            		$error = 'Server Error Occured while Uploading Image !';
            		$output = 0;
                }
            
            	echo $output;
		    }
		    
		    if($this->request->getVar('action') == 'password'){
    		    $pass = password_hash($this->request->getVar('pass1'), PASSWORD_BCRYPT);
                $error = '';
                $success = '';
    			if($this->hod_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' => 'Manage Profile',
    			'page_subtitle' => '',
    			'user' => $this->session->get('name')
    		];
    		
    		return view('hod/manage_profile', $data);
		}
		
	}

	public function course_allocation()
	{

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		$data = [
			'page_title' => 'Courses',
			'page_subtitle' => 'Course Allocations',
			'user' => $this->session->get('name')
		];
		$faculty = $this->session->get('faculty');
		$department = $this->session->get('name');
		$id = $this->session->get('id');
		$session = $this->session->get('session');
		$data['staff'] = $this->hod_model->get_staffs($id);
		$data['course'] = $this->hod_model->get_courses($department);
		$data['allocations'] = $this->hod_model->get_course_allocation($id, $session);

		$data['user'] = $department;
		//$data['value'] = $values;
		//dd($values);
		return view('hod/course_allocation', $data);
		
		
	}
	
	public function course_allocation_action(){
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		if($this->request->getMethod() == 'post'){
			
			if($this->request->getPost('action') == 'delete_allocation'){
	            $error = '';
	            $success = '';
				$data = [
					'status' => 'deleted'
				];
				if($this->hod_model->delete_course_allocation($this->request->getPost('id'))){
					$success = "Course Allocation 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 = '';
				$data = [
					'status' => 'edited'
				];
				if($this->hod_model->delete_course_allocation($this->request->getPost('id'))){
					$success = "Level Coordinator deleted successfully";
				}else{
					$error = "Oops! Something went wrong. Try later.";
				}
    
	            $output = array(
	                'error'		=>	$error,
	                'success'	=>	$success
	            );
            	echo json_encode($output);
			}
		}
	}

	public function allocate_course(){
	    
		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$data = [
			'page_title' => 'Courses',
			'page_subtitle' => 'Allocate Courses',
			'user' => $this->session->get('name')
		];
		$department = $this->session->get('name');
		$id = $this->session->get('id');
		$session = $this->session->get('session');
		//$data['staff'] = $this->hod_model->get_staffs($id);
		$data['staff'] = $this->hod_model->get_faculty_staffs($faculty);
		$data['course'] = $this->hod_model->get_courses($department);
		$data['allocations'] = $this->hod_model->get_course_allocation($id, $session);

		$data['user'] = $department;
		
		return view('hod/allocate_course', $data);
		
	}

	public function get_course_allocations($session){
		
		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$session = urldecode($session);
		$session = str_replace("_", "/", $session);
        $id = $this->session->get('id');
		$list = $this->hod_model->get_course_allocation($id, $session);
		
		$output = "";
		$edit_dialog = "";
		$view_dialog = "";
		if($list){	
			$output .= "<div class='row'  >
	
			<div class='col-md-12 table-responsive' > 
			<table id='example1' class='table table-striped table-bordered'>
					<thead>
				   <tr>
						<th>S/N</th> 
						<th>Course Code</th>
						<th>Course Title</th>
						<th>Lecturer</th>
						<th>Semester</th>
						<th>Level</th>
						<th>Programmes (No. of Stud.)</th>
						<th>Session</th>
						<th>Action</th>
						
					  </tr>
			   </thead>
			<tbody>";
			 $i = 1;
                             
                     foreach($list as $l):
                         
                        $programmes_array = explode(",", $l->programmes_allocated_to);
						$array_lenth = count($programmes_array);
                         
                        $output .= "<input type='hidden' name='action' value='delete_allocation'/>";
                    	$output .= "<tr>";
						$output .= "<td>".$i++."</td>";                     
						$output .= "<td>".$l->course_id."</td>";
						$output .= "<td>".$l->title."</td>";
						$output .= "<td>".$l->name."</td>";
						$output .= "<td>".$l->semester."</td>";
						$output .= "<td>".$l->level."</td>";
						//$output .= $pall;
						//$output .="<td><a href = '' class='btn btn-info' data-toggle='modal'>".$l->programmes_allocated_to."</a></td>";
						
						//echo $l->id;
						$output .= "<td>";
						$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->course_id, $session);	
                            
                            $sess = str_replace("/", "_", $session);
							if($students_enrollemnt){
								$value = "#".$prog."_".$l->course_id."_".$sess;
								$ext = " = ".$num;
								$num = count($students_enrollemnt);
							
								if($array_lenth == $counter){
									$output .= "<a href = ".$value." class='btn btn-info' data-toggle='modal'>".$prog."<strong>(".$num.")</strong></a>";
								}else{
									$output .= "<a href = ".$value." class='btn btn-info' data-toggle='modal'>".$prog."<strong>(".$num.")<strong></a><br/><br/>";
								}
							
							    
							    $value_id = $prog."_".$l->course_id."_".$sess;
								$view_dialog .= '<div class="modal fade" id='.$value_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> '.$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{
								    $num = 0;
									if($array_lenth == $counter){
									    //$num = count($students_enrollemnt);
										$output .= "<a href ='javascript:void(0);' class='btn btn-info btn-no-data' data-toggle='modal'>".$prog."<strong>".$num."</strong></a>";
									}else{
										$output .= "<a href ='javascript:void(0);' class='btn btn-info btn-no-data' data-toggle='modal'>".$prog."<strong>".$num."</strong></a><br/><br/>";
									}
									
								}
								
								$counter++;
						}
						$output .= "</td>";
						
						$output .= "<td>".$l->session."</td>";
						$output .= "<td class='text-center'><button class='btn btn-success btn-xs edit_btn' href = '#mo' data-toggle='modal'><i class='fas fa-edit'></i></button> <button class='btn btn-danger btn-xs delete_allocation' data-id='$l->id'><i class='fas fa-trash'></i></button></td>";
						$output .= "</tr>";
						
                		$programme = $this->hod_model->get_programs_allocated($l->id);
                		/*$prog = "";
                		foreach($programme as $p){
                		    $prog = $prog.$p->programmes_allocated_to;
                		}*/
                        $all_programmes = explode(",", $programme['programmes_allocated_to']);
                        
                		//$output = "";
                		$values = array();
                			
                		foreach($all_programmes as $al){
                			array_push($values, $this->hod_model->get_program_details_by_ccode($al));
                		}
                        //print_r($values);
                        //echo "\n";
                		//$i = 0;	
						/*
						$edit_dialog = '<div id="mo" class="modal hide fade in" data-backdrop="static">
							<div class="modal-dialog modal-lg">
							  <div class="modal-content">
								<div class="modal-header">
								  <h5 class="modal-title">Course Allocation</h5>
								  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								  </button>
								</div>
								<div class="modal-body">
								<div class="form-group">
								<label class="label"><b>Select Programmes to allocate to:</b></label><br/>';
								$ck = true;
								foreach($values as $val): 
									//$arr = $val[0];
								
									$edit_dialog .= "<input type='checkbox' name = 'code[]' value = ".$val[0]->ccode."> ".$val[0]->ccode."<br/>";
									
									//$i++;
								endforeach;

							

									$edit_dialog .= '</div>

									<p><div class="form-group">
								<label class="label"><b>Enter CA Marks Range:</b></label><br/>
								<input type = "number" min = "0" max = "50" step = "1" class="form-control" name="ca_range"  required '.(($ck) ? '' : 'disabled').'>
								
									</div>
									</p>

									<p><div class="form-group">
								<label class="label"><b>Enter Exam Marks Range:</b></label><br/>
								<input type = "number" min = "0" max = "70" step = "1" class="form-control" name="exam_range" required '.(($ck) ? '' : 'disabled').'>
								
									</div>
									</p>
								';
			
								$edit_dialog .="
								<div class='modal-footer justify-content-between'>
								<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
								<button type='submit' name = 'add_course' class='btn btn-primary' ".(($ck) ? '' : 'hidden').">Save Allocation</button>
								</div>
								</div>
								</div>
								</div>
								</div>";*/
                   
                    	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;
		//echo $edit_dialog;

	}	

	function get_program_course($course_code)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
	    
		$course_code = urldecode($course_code);
		$session = $this->session->get('session');
		//echo $course_code;
		$programme = $this->hod_model->get_program_course($course_code, $session);
        
		$output = "";
		$values = [];
		if($programme){
			
			foreach($programme as $l){
				array_push($values, $this->hod_model->get_program_details($l->awarded_programme));
			}
			$output .= "<div class='row'><section class='col-md-12'>";
			$i = 0;
			foreach($values as $val): 
		        $arr = $val[$i];
		        $output .= "<input type='checkbox' name = 'code[]' value = ".$arr->ccode."> ".$arr->title."<br/>";
				//$i++;
			endforeach;
			$output .= "</section>
			</div>           
			<div class='row'>		
			<section class='col-md-12'>
			<div class='col-md-6'>
			<button class='btn-u pull-right' type='submit'>Save Course Allocation</button>                        
			</div>
			</section>
			</div>";  
		}else{
			$output .= "There is no student enrollment for this course";
		}
		echo $output;

	}
	
	public function view_courses()
	{

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url()."/hod/login");	
		}
		$semester = !empty($this->request->getVar('semester')) ? urldecode($this->request->getVar('semester')) : false;
		$data = [
			'page_title' => 'Courses',
			'page_subtitle' => 'View Courses',
			'semester' => $semester,
			'user' => $this->session->get('name')
		];
		
		$department = $this->session->get('name');
		$data['result'] = $this->hod_model->get_courses_filter($department, $semester);
		$data['user'] = $department;
		
		return view('hod/view_courses', $data);
		
	}

	public function view_staffs()
	{

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url()."/hod/login");	
		}
		$data = [
			'page_title' => 'Departmental Staff',
			'page_subtitle' => '',
			'user' => $this->session->get('name')
		];
		$department = $this->session->get('name');
		$id = $this->session->get('id');
		$data['result'] = $this->hod_model->get_staffs($id);
		$data['user'] = $department;
		
		return view('hod/view_staff', $data);
		
	}

	public function levelcoordinators(){

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url()."/hod/login");	
		}
		$data = [
			'page_title' => 'Level Coordinators',
			'page_subtitle' => '',
			'user' => $this->session->get('name')
		];

		$department = $this->session->get('name');
		$id = $this->session->get('id');
		$session = $this->session->get('session');
		$data['model'] = $this->hod_model;
		$data['lcs'] = $this->hod_model->get_level_coord($id);
		$data['staff'] = $this->hod_model->get_staffs($id);
		$data['programmes'] = $this->hod_model->get_programmes($id);

		return view('hod/level_coordinators', $data);
		
	}

	public function tests(){
		$prog = $this->hod_model->get_program_details('58');
		echo json_encode($prog[0]->ccode);
	}

	public function level_coordinators_action(){
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		if($this->request->getMethod() == 'post'){
			if($this->request->getPost('action') == 'add'){
				$session = $this->request->getVar('session');
				$staff_id = $this->request->getVar('staff');
				$level = $this->request->getVar('level');
				$staff = $this->hod_model->get_staff_details($staff_id);
				$programme = $this->request->getVar("programme");
				$year = (int) substr($session, 2, 2);
				$prog = $this->hod_model->get_program_details($programme);
				$pcode = $prog[0]->ccode;
				$username = $pcode.$year;
				if(!$this->hod_model->check_level_coord($programme, $level, $session)){
					$data = [
						'staff_id' => $staff_id,
						'stfn' => $staff['staff_id'],
						'email' => $staff['email'],
						'username' => $username,
						'password' => password_hash('123456', PASSWORD_BCRYPT),
						'dept_id' => $this->session->get('id'),
						'programme_id' => $programme,
						'session_started' => $session,
						'current_level' => $level,
						'created_at' => date('Y-m-d H:i:s')
					];

					if($this->hod_model->save_level_coord($data)){
						$this->session->setTempdata('saveSuccess','Level Coordinator Assigned Successfully. Email notification with  has been sent to the staff',3);
						return redirect()->to(base_url().'/head-levelcoordinators');
					}else{
						$this->session->setTempdata('saveError','Oops! Something went wrong',3);
						return redirect()->to(base_url().'/head-levelcoordinators');
					}
				}else{
					$this->session->setTempdata('saveError','Programme(s) already have Level Coordinator for the selected level and session',3);
					return redirect()->to(base_url().'/head-levelcoordinators');
				}
			}

			if($this->request->getPost('action') == 'delete'){
	            $error = '';
	            $success = '';
				$data = [
					'status' => 'deleted'
				];
				if($this->hod_model->delete_level_coord($this->request->getPost('id'))){
					$success = "Level Coordinator deleted successfully";
				}else{
					$error = "Oops! Something went wrong. Try later.";
				}
    
	            $output = array(
	                'error'		=>	$error,
	                'success'	=>	$success
	            );
            	echo json_encode($output);
			}
		}
	}

	public function examofficers(){

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		$data = [
			'page_title' => 'Exam Officers',
			'page_subtitle' => '',
			'user' => $this->session->get('name')
		];

		$department = $this->session->get('name');
		$id = $this->session->get('id');
		$data['model'] = $this->hod_model;
		$data['eos'] = $this->hod_model->get_exam_officers($id);
		$data['staff'] = $this->hod_model->get_staffs($id);
		$data['programmes'] = $this->hod_model->get_programmes($id);

		return view('hod/exam_officers', $data);
		
	}

	public function exam_officers_action(){
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		if($this->request->getMethod() == 'post'){
			if($this->request->getPost('action') == 'add'){
				$session = $this->request->getVar('session');
				$staff_id = $this->request->getVar('staff');
				$staff = $this->hod_model->get_staff_details($staff_id);
				$programmes = implode(",",$this->request->getVar("programmes"));
				if(!$this->hod_model->check_exam_officer($programmes, $session)){
					$data = [
						'staff_id' => $staff_id,
						'email' => $staff['email'],
						'password' => password_hash('123456', PASSWORD_BCRYPT),
						'dept_id' => $this->session->get('id'),
						'programme_id' => $programmes,
						'session' => $session,
						'created_at' => date('Y-m-d H:i:s')
					];

					if($this->hod_model->save_exam_officer($data)){
						$this->session->setTempdata('saveSuccess','Exam Officer Added Successfully. Email notification with  has been sent to the staff',3);
						return redirect()->to(base_url().'/head-examofficers');
					}else{
						$this->session->setTempdata('saveError','Oops! Something went wrong',3);
						return redirect()->to(base_url().'/head-examofficers');
					}
				}else{
					$this->session->setTempdata('saveError','Programme(s) already have Examination Officer for the selected session',3);
					return redirect()->to('examofficers');
				}
			}

			if($this->request->getPost('action') == 'delete'){
	            $error = '';
	            $success = '';
				if($this->hod_model->delete_exam_officer($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);
			}
		}
	}

	public function view_students_page()
	{

		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		$data = [
			'page_title' => 'Departmental Students',
			'page_subtitle' => '',
			'user' => $this->session->get('name')
		];
		$department = $this->session->get('name');
		$id = $this->session->get('id');

		$students = $this->hod_model->count_all_students($id);
		$data['active'] = 0;
		$data['graduated'] = 0;
		$data['suspended'] = 0;
		$data['expelled'] = 0;
		foreach($students as $cat){
			if($cat->status == 'Student'){
				$data['active'] += $cat->num;
			}
			if($cat->status == 'Graduated'){
				$data['graduated'] += $cat->num;
			}
			if($cat->status == 'Suspended'){
				$data['suspended'] += $cat->num;
			}
			if($cat->status == 'Expelled'){
				$data['expelled'] += $cat->num;
			}
		}
		
		$data['programmes'] = $this->hod_model->get_programmes($id);
	
		return view('hod/view_students', $data);
		
	}

	function get_students($programme, $level, $gender)
	{
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$programme = urldecode($programme);
		$level = urldecode($level);
		$gender = urldecode($gender);
		$session = $this->session->get('session');

		$student = $this->hod_model->get_registered_students($session, $programme, $level, $gender);
		$output = "";
		$course_registration_dialog = "";
		$profile_dialog = "";
		
		if($student){

			
			$output .= "<div class='row'  >
	
			<div class='col-md-12 table-responsive' > 
			<table id='student_tbl' class='table table-bordered table-striped'>
					<thead>
				   <tr>
						<th>S/N</th> 
						<th>Full Name<br/><small>Registration No.</small></th>
						<th>Gender</th>
						<th>Programme</th>
						<th>Admission Year</th>
						<th>Phone No.</th>
						<th>Action</th>
						
					  </tr>
			   </thead>
			<tbody>";
			$i = 1;
			foreach($student as $stud){	
                $gender = '';
                if($stud->gender == 'M'){
                    $gender = 'Male';
                }
                if($stud->gender == 'F'){
                    $gender = 'Female';
                }
				$reg_no = $stud->registration_no;
				$student_name = $stud->first_name." ".$stud->middle_name." ".$stud->last_name;
				$id_value = "#".$stud->registration_no;
				$output .= "<tr><td>".$i."</td>";
				$output .= "<td>".$student_name."<br/><small>".$stud->registration_no."</small></td>";
				$output .= "<td>".$gender."</td>";
				$output .= "<td>".$stud->title."</td>";
				$output .= "<td>".$stud->award_year."</td>";
				$output .= "<td>".$stud->phone."</td>";
				$output .= '<td><button class="btn btn-primary btn-sm view_student" data-id="'.$stud->id.'" > <i class="fas fa-user"> View Details</i></button></td>';
				$output .= "</tr>";
				$i++;
				
			}							
	
			$output .="</tbody>
			</table>
			</div>
			</div>";

		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"> No record found</div>';
		}
		echo $output;
	}

	function get_students_by_stat()
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}

		$students = $this->hod_model->get_students_by_stat($this->session->get('id'), $this->request->getVar("stat"));
		$output = "";
		
		if($students){

			$i = 1;
			foreach($students as $stud){	
                $gender = '';
                if($stud->gender == 'M'){
                    $gender = 'Male';
                }
                if($stud->gender == 'F'){
                    $gender = 'Female';
                }
				$reg_no = $stud->registration_no;
				$student_name = $stud->first_name." ".$stud->middle_name." ".$stud->last_name;
				$id_value = "#".$stud->registration_no;
				$output .= "<tr><td>".$i."</td>";
				$output .= "<td>".$student_name."<br/><small>".$stud->registration_no."</small></td>";
				$output .= "<td>".$gender."</td>";
				$output .= "<td>".$stud->title."</td>";
				$output .= "<td>".$stud->award_year."</td>";
				$output .= "<td>".$stud->phone."</td>";
				$output .= "</tr>";
				$i++;
				
			}

		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"> No record found</div>';
		}
		echo json_encode($output);
	}

	function get_student_details(){
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		if ($this->request->getPost()) {
			$my_id = $this->request->getPost("my_id");
			$student = $this->hod_model->get_student_details($my_id);
			$output = "";

			if($student){

				foreach($student as $stud){	
					$student_name = $stud->first_name." ".$stud->middle_name." ".$stud->last_name;
					$output .= '
		              	<div class="tab-content">
	  						<div class="active tab-pane" id="biodata">
	  							<div class="row text-center">
	  								<div class="col-md-12">
	  								<img class="profile-user-img img-fluid img-circle" src=" '.base_url('/assets_/img/nwu_logo.jpg').'" style="width: 120px;" alt="Student profile picture">
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-12">
	  								<div class="form-group">
									<label>Full Name</label>
									<input class="form-control" value = "'.$student_name.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>UTME No.</label>
									<input class="form-control" value = "'.$stud->utme_no.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>Registration No.</label>
									<input class="form-control" value = "'.$stud->registration_no.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>level</label>
									<input class="form-control" value = "'.$stud->level.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>Gender</label>
									<input class="form-control" value = "'.$stud->gender.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>Date of Birth</label>
									<input class="form-control" value = "'.$stud->birthdate.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>Marital</label>
									<input class="form-control" value = "'.$stud->marital_status.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>Religion</label>
									<input class="form-control" value = "'.$stud->religion.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>Tribe</label>
									<input class="form-control" value = "'.$stud->tribe.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-4">
	  								<div class="form-group">
									<label>State of Origin</label>
									<input class="form-control" value = "'.$stud->state_of_origin.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  						</div>
	  						<div class="tab-pane" id="contact">
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Email</label>
									<input class="form-control" value = "'.$stud->email.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Phone</label>
									<input class="form-control" value = "'.$stud->phone.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Contact Address</label>
									<textarea class="form-control" rows="3" disabled>'.$stud->contact_address.'</textarea>
	  								</div>
	  								</div>
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Permanent Address</label>
									<textarea class="form-control" rows="3" disabled>'.$stud->contact_address.'</textarea>
	  								</div>
	  								</div>
	  							</div>
	  						</div>
	  						<div class="tab-pane" id="nok">
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Name</label>
									<input class="form-control" value = "'.$stud->next_of_kin_name.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Phone</label>
									<input class="form-control" value = "'.$stud->next_of_kin_phone.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Address</label>
									<textarea class="form-control" rows="3" disabled>'.$stud->next_of_kin_address.'</textarea>
	  								</div>
	  								</div>
	  							</div>
	  						</div>
	  						<div class="tab-pane" id="sponsor">
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Sponsorship Type</label>
									<input class="form-control" value = "'.$stud->sponsorship_type.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Sponsor Name</label>
									<input class="form-control" value = "'.$stud->sponsor_name.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Sponsor Phone</label>
									<input class="form-control" value = "'.$stud->sponsor_phone.'" disabled/>
	  								</div>
	  								</div>
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Sponsor Email</label>
									<input class="form-control" value = "'.$stud->sponsor_email.'" disabled/>
	  								</div>
	  								</div>
	  							</div>
	  							<div class="row">
	  								<div class="col-md-6">
	  								<div class="form-group">
									<label>Sponsor Address</label>
									<textarea class="form-control" rows="3" disabled>'.$stud->sponsor_address.'</textarea>
	  								</div>
	  								</div>
	  							</div>
	  						</div>
		              	</div>';
				}
	    	}else{
				$output .= '<br/><div class="alert alert-danger alert-dismissible"> No record found</div>';
	    	}
	        echo json_encode($output);
		}
	}

	public function approve_submission()
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
	    
		$data = [
			'page_title' => 'Exam Results',
			'page_subtitle' => 'Approve Submissions',
			'user' => $this->session->get('name')
		];
		$department = $this->session->get('name');
		$id = $this->session->get('id');
		
		$data['programmes'] = $this->hod_model->get_programmes($id);
			
		return view('hod/approve_submission', $data);
		
	}

	public function results()
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
			$data = [
				'page_title' => 'Exam Results',
				'page_subtitle' => 'Results',
				'user' => $this->session->get('name')
			];
			$department = $this->session->get('name');
			$id = $this->session->get('id');
			
			$data['programmes'] = $this->hod_model->get_programmes($id);
			
		return view('hod/results', $data);
		
	}

	public function view_students()
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$data = [
			'page_title' => 'Departmental Students',
			'user' => $this->session->get('name')
		];
		$department = $this->session->get('name');
		$id = $this->session->get('id');
		
		$data['programmes'] = $this->hod_model->get_programmes($id);
			
		return view('hod/view_student', $data);
		
		
	}

	//View list of programmes
	function get_enrolled_programmes($course)
	{
		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$course = urldecode($course);
		$session = $this->session->get('session');
		$view_dialog = "";
		
								
	}

	//Enrolled students
	function get_lecturer($course)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$course = urldecode($course);
		$output = "";

		$id = $this->session->get('id');
		$faculty = $this->session->get('faculty');
		//$staff = $this->hod_model->get_staffs($id);
		$staff = $this->hod_model->get_faculty_staffs($faculty);

		$session = $this->session->get('session');
		//echo $course_code;
		$programme = $this->hod_model->get_program_course($course, $session);
        
		$output = "";
		$values = [];
		if($programme){
			$output .= '<div class="form-group">
				<label>Select Lecturer:<font style="color:#F00">*</font></label>
				<select class="form-control select2" name="lecturer" id="lecturerField" onchange="spawn_allocation_button()" required> 
				<option disabled selected>- Select Lecturer -</option>';

				foreach($staff as $st){
					$output .= '<option value = '.$st->id.'>'.$st->name.'</option>';
				}
			$output .= "</select></div>";
		}else{
			$output .= '<br/><div class="alert alert-danger alert-dismissible"><i class="icon fas fa-ban"></i> There is no student enrollment for this course!</div>';
		}
	
				
		echo $output;
	}

	public function allocation_button($course_code)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$view_dialog = "";
		$course_code = urldecode($course_code);
		$session = $this->session->get('session');
		//echo $course_code;
		$programme = $this->hod_model->get_program_course($course_code, $session);
		$allocated = $this->hod_model->get_allocated($course_code, $session);
		if($allocated){
			$prog = '';
			foreach($allocated as $al){
				$prog .= ','.$al->programmes_allocated_to;
			}
			$all_prog_array = explode(",", $prog);
		}else{
			$all_prog_array = array();
		}

        
		$output = "";
		$values = array();
			
		foreach($programme as $l){
			array_push($values, $this->hod_model->get_program_details($l->awarded_programme));
		}

		$i = 0;	
		
		$output = '<a class="btn btn-success btn-lg btn-block"  href = "#mo" data-toggle="modal" > Allocate</a>';			
		$view_dialog .= '<div id="mo" class="modal hide fade in" data-backdrop="static">
							<div class="modal-dialog modal-lg">
							  <div class="modal-content">
								<div class="modal-header">
								  <h5 class="modal-title">Course Allocation</h5>
								  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								  </button>
								</div>
								<div class="modal-body">
								<div class="form-group">
								<label class="label"><b>Select Programmes to allocate to:</b></label><br/>';
								$ck = false;
								foreach($values as $val): 
									$arr = $val[0];
									if(!in_array($arr->ccode, $all_prog_array)){
										$view_dialog .= "<input type='checkbox' name = 'code[]' value = ".$arr->ccode."> ".$arr->title."<br/>";
										$ck = true;
									}
									//$i++;
								endforeach;

								if(!$ck){
									$view_dialog .='<div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> No more programmes to allocate</div>';
								}

									$view_dialog .= '</div>

									<p><div class="form-group">
								<label class="label"><b>Enter CA Marks Range:</b></label><br/>
								<input type = "number" min = "0" max = "50" step = "1" class="form-control" name="ca_range"  required '.(($ck) ? '' : 'disabled').'>
								
									</div>
									</p>

									<p><div class="form-group">
								<label class="label"><b>Enter Exam Marks Range:</b></label><br/>
								<input type = "number" min = "0" max = "70" step = "1" class="form-control" name="exam_range" required '.(($ck) ? '' : 'disabled').'>
								
									</div>
									</p>
								';
			
								$view_dialog .="
								<div class='modal-footer justify-content-between'>
								<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
								<button type='submit' name = 'add_course' class='btn btn-primary' ".(($ck) ? '' : 'hidden').">Save Allocation</button>
								</div>
								</div>
								</div>
								</div>
								</div>";
		
		echo $output;
		echo $view_dialog;
		
	}
	
	public function edit_allocation_button($course_code)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}

		$view_dialog = "";
		$course_code = urldecode($course_code);
		$session = $this->session->get('session');
		//echo $course_code;
		$programme = $this->hod_model->get_program_course($course_code, $session);
		$allocated = $this->hod_model->get_allocated($course_code, $session);
		if($allocated){
			$prog = '';
			foreach($allocated as $al){
				$prog .= ','.$al->programmes_allocated_to;
			}
			$all_prog_array = explode(",", $prog);
		}else{
			$all_prog_array = array();
		}

        
		$output = "";
		$values = array();
			
		foreach($programme as $l){
			array_push($values, $this->hod_model->get_program_details($l->awarded_programme));
		}

		$i = 0;	
		
		$output = '<a class="btn btn-success btn-lg btn-block"  href = "#mo" data-toggle="modal" > Allocate</a>';			
		$view_dialog .= '<div id="mo" class="modal hide fade in" data-backdrop="static">
							<div class="modal-dialog modal-lg">
							  <div class="modal-content">
								<div class="modal-header">
								  <h5 class="modal-title">Course Allocation</h5>
								  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								  </button>
								</div>
								<div class="modal-body">
								<div class="form-group">
								<label class="label"><b>Select Programmes to allocate to:</b></label><br/>';
								$ck = false;
								foreach($values as $val): 
									$arr = $val[0];
									if(!in_array($arr->ccode, $all_prog_array)){
										$view_dialog .= "<input type='checkbox' name = 'code[]' value = ".$arr->ccode."> ".$arr->title."<br/>";
										$ck = true;
									}
									//$i++;
								endforeach;

								if(!$ck){
									$view_dialog .='<div class="alert alert-danger alert-dismissible"><i class="icon fas fa-exclamation-triangle"></i> No more programmes to allocate</div>';
								}

									$view_dialog .= '</div>

									<p><div class="form-group">
								<label class="label"><b>Enter CA Marks Range:</b></label><br/>
								<input type = "number" min = "0" max = "50" step = "1" class="form-control" name="ca_range"  required '.(($ck) ? '' : 'disabled').'>
								
									</div>
									</p>

									<p><div class="form-group">
								<label class="label"><b>Enter Exam Marks Range:</b></label><br/>
								<input type = "number" min = "0" max = "70" step = "1" class="form-control" name="exam_range" required '.(($ck) ? '' : 'disabled').'>
								
									</div>
									</p>
								';
			
								$view_dialog .="
								<div class='modal-footer justify-content-between'>
								<button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
								<button type='submit' name = 'add_course' class='btn btn-primary' ".(($ck) ? '' : 'hidden').">Save Allocation</button>
								</div>
								</div>
								</div>
								</div>
								</div>";
		
		echo $output;
		echo $view_dialog;
		
	}

	public function save_allocation(){	
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		if($this->request->getMethod() == 'post'){
			$id = 0;
			$action = '';

			$lecturer_id = $this->request->getVar('lecturer');
			$course_id = $this->request->getVar('course');
			$ca_range = $this->request->getVar('ca_range');
			$exam_range = $this->request->getVar('exam_range');
			$programmes = implode(",",$this->request->getVar("code"));
			$username = "";
			$session = $this->session->get('session');
			$year = (int) substr($session, 2, 2);
			
			$course_detail = $this->hod_model->get_course_details($course_id);
			$course_level = $course_detail['level'];
			
			if(substr($course_level,0,1) == 1){
				$username = $year."";
			}else if(substr($course_level,0,1) == 2){
				$username = ($year - 1)."";
			}else if(substr($course_level,0,1) == 3){
				$username = ($year - 2)."";
			}else if(substr($course_level,0,1) == 4){
				$username = ($year - 3)."";
			}
			
			//$username = "50";

			$allocated = $this->hod_model->check_allocation($lecturer_id, $course_id, $session);
			if($allocated){
				$action = 'update';
				$id = $allocated['id'];
				$programmes = $allocated['programmes_allocated_to'].','.$programmes;
				$data = [
					'programmes_allocated_to' => $programmes,
					'updated_at' => date('Y-m-d H:i:s')
				];

			}else{
				$action = 'save';
				$data = [
					'course_id' => $course_id,
					'dept_id' => $this->session->get('id'),
					'lecturer_id' => $lecturer_id,
					'programmes_allocated_to' => $programmes,
					'programme_username' => $username,
					'ca_range' => $ca_range,
					'exam_range' => $exam_range,
					'created_at' => date('Y-m-d H:i:s'),
					'session' => $session
				];
			}


			if($this->hod_model->save_allocation($id, $data, $action)){
			    $this->session->setTempdata('allocationSuccess', 'Course Allocation Saved Successfully');
				return redirect()->to(base_url().'/head-allocations')->with('allocationSuccess', 'Course Allocation Saved Successfully');
			    //return redirect()->to('examofficers');
				//return redirect()->to(base_url('hod/course_allocation'))->with('allocationSuccess', 'Course Allocation Saved Successfully');
			}else{
				//return redirect()->to(base_url('hod/course_allocation'))->with('allocationError', 'Failed to Allocate Course');
				$this->session->setTempdata('allocationError', 'Failed to Allocate Course');
				return redirect()->to(base_url().'/head-allocations');
			}
			
		}
	}

	//View list of students
	function get_students_list($programme, $level)
	{
		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		
		$programme = urldecode($programme);
		$level = urldecode($level);
		
		$output = "";
		if(!empty($programme)){
			
			//

			$list = $this->hod_model->get_students($programme, $level);

			$department = $this->session->get('name');
			$id = $this->session->get('id');
			
			$data['programmes'] = $this->hod_model->get_programmes($id);
			
			$values = [];
			foreach($list as $l){
			
			$i = $l->profile_id;
			$index = 'student'.$i;
			$data[$index] = $this->hod_model->get_student_details($i);
			//$values[$i] = $this->hod_model->get_student_details($i);
			array_push($values, $this->hod_model->get_student_details($i));	
		}
		
		$data['values'] = $values;

			//
			$output .= "<div class='row'  >
	
			<div class='col-md-12 table-responsive' > 
			<table id='dept_students_tbl1' class='table table-striped table-bordered'>
					<thead>
				   <tr>
						<th>S/N</th> 
						<th>Full Name</th>
						<th>Registration Number</th>
						<th>Level</th>
						<th>Gender</th>
						
					  </tr>
			   </thead>
			<tbody>";
			 $i = 1;
                             if(!empty($values)):    	
                   foreach($values as $stud): 
                     foreach($stud as $st):
                    	$output .= "<tr>";
                    $output .= "<td>".$i++."</td>";                     
                    $output .= "<td>".$st->first_name." ".$st->middle_name." ".$st->last_name."</td>";
                    $output .= "<td>".$st->registration_no."</td>";
                    $output .= "<td>".$st->level."</td>";
                    $output .= "<td>".$st->gender."</td>";
                    $output .= "</tr>";
                    endforeach;
                    	endforeach; 
                       		endif;					
	
			$output .="</tbody>
			</table>
			</div>
			</div>";
		}else{
			$output .= "List of Submmission";
		}
		
	
		echo $output;
	}

	function get_programme($session)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$dept_id = $this->session->get('id');
		$output = "";
		$programme = $this->hod_model->get_programmes(17);
		
		$output .= '<div class="form-group">
					<label class="label"><b>Select Programme:</b></label><br/>
					<select class="form-control select2" name="programme" id="programmeId" onchange="spawn_available_semester()" required> 
					<option>Programme</option>';
					foreach($programme as $prog){
						$output .= "<option value value = ".$prog->id.">".$prog->title."</ption>";
					}
		$output .= "</select></div>";	
		
				
		echo $output;
	}

	function get_submitted_semester($session)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$dept_id = $this->session->get('id');
		$output = "";
		$programme = $this->hod_model->get_programmes($dept_id);
		
		$output .= '<div class="form-group">
					<label class="label"><b>Select Programme:</b></label><br/>
					<select class="form-control select2" name="semester" id="semester" onchange="spawn_lecturers_submission()" required> 
					<option>Semester</option>
					<option value = "1st">1st</option>
					<option value = "2nd">2nd</option>';
					
		$output .= "</select></div>";	
		
				
		echo $output;
	}

	function get_departmental_programmes($session)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$dept_id = $this->session->get('id');
		$output = "";
		$programme = $this->hod_model->get_programmes($dept_id);
		
		$output .= '<div class="form-group">
					<label class="label"><b>Select Programme:</b></label><br/>
					<select class="form-control select2" name="programme" id="programme" onchange="spawn_available_semester_result()" required> 
					<option>Programme</option>
					';
				foreach($programme as $prog){
					$output .= "<option value = ".$prog->id.">".$prog->title."</option>";
				}
					
					
		$output .= "</select></div>";	
		
				
		echo $output;
	}

	function get_semester_results($session)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$dept_id = $this->session->get('id');
		$output = "";
		$programme = $this->hod_model->get_programmes($dept_id);
		
		$output .= '<div class="form-group">
					<label class="label"><b>Select Semester:</b></label><br/>
					<select class="form-control select2" name="semester" id="semester" onchange="spawn_students_result()" required> 
					<option>Semester</option>
					<option value = "1st">1st</option>
					<option value = "2nd">2nd</option>';
					
		$output .= "</select></div>";	
		
				
		echo $output;
	}

	//View list of Lecturers Submission
	function get_lecturers_submission($session, $programme, $semester)
	{
		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		$session = urldecode($session);
		$programme = urldecode($programme);
		$semester = urldecode($semester);
		$session = str_replace("_","/",$session);
		
		$department = $this->session->get('name');
		$id = $this->session->get('id');
		//$session = $this->session->get('session');
		$list = $this->hod_model->get_uploaded_results($id, $semester, $session);
		
		$output = "";
		$view_dialog = "";
		if(!empty($list)){
			foreach($list as $l){
				if(strpos($l->course_id, "GSP") !== false || strpos($l->course_id, "GST") !== false){
					$l->lecturer = "GSP Coordinator";
				}else{
					$details = $this->hod_model->get_staff_details($l->lecturer_id);
					$l->lecturer = $details['name']; 
				} 
			
				$details = $this->hod_model->get_course_details($l->course_id);
				$l->course_title = $details['title']; 
			}
			
		
			$output .= "
			    
			<div class='row'  >
	
			<div class='col-md-12 table-responsive' > 
			<table id='example1' class='table table-striped table-bordered'>
				<thead>
				   <tr>
				        <th> </th>
						<th>S/N</th> 
						<th>Course Code/Title</th>
						<th>Programme</th>
						<th>Lecturer</th>
						<th>Status</th>
						<th>Submitted On</th>
						<th class='text-center'>Action</th>
					</tr>
			   </thead>
			<tbody>";
			 $i = 1;
                             if(!empty($list)):
								    	
                   foreach($list as $li): 
    				    $stat = $li->hod_status == "Accepted" ? 'success' : ($li->hod_status == "Rejected" ? 'danger' : 'warning');
                     	$output .= "<tr>";
                     	$output .= "<td></td>";  
						$output .= "<td>".$i++."</td>";                     
						$output .= "<td>".$li->course_id."<br/>".$li->course_title."</td>";
						$output .= "<td>".$li->programme_title."</td>";
						$output .= "<td>".$li->lecturer."</td>";
						$output .= "<td><span class='badge badge-".$stat."'>".$li->hod_status."</span></td>";
						$output .= "<td>".$li->created_at."</td>";
						$id_value = "#".$li->id;
						$stt = $li->hod_status != "Pending" ? "hidden" : "";
						
						if($li->eo_status == 'Accepted'){
						    $output .= '<td class="text-center"><button title="View" class="btn btn-info btn-xs" data-target = '.$id_value.' data-toggle="modal" data-backdrop="static" data-keyboard="false"><i class="fas fa-eye"></i></button> <button '.$stt.' title="Accept" class="btn btn-success btn-xs accept_button" data-id='.$li->id.'><i class="fas fa-check"></i></button> <button '.$stt.' title="Reject" class="btn btn-danger btn-xs reject_button" data-id='.$li->id.'><i class="fas fa-ban"></i></button> <button title="Return to Lecturer" class="btn btn-warning btn-xs return_button" data-id='.$li->id.'><i class="fas fa-reply"></i></button></td>';
						}else{
						    $output .= '<td class="text-center"><button title="View" class="btn btn-info btn-xs" disabled><i class="fas fa-eye"></i></button></td>';
						}
					
						$output .= "</tr>";

						$view_dialog .= '<div class="modal fade" id='.$li->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> '.$li->course_id.': '.$li->course_title.'<br/>
								  <span class="badge badge-secondary">Programme:</span> '.$li->programme_title.'<br/>
								  <span class="badge badge-secondary">Session:</span> '.$session.'<br/></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" width="100%">
								<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($li->id);
								$index = 1;
								$color = '';
							if(!empty($result)){
								foreach($result as $res){
									if($res->grade == 'F'){
										$color = 'text-danger';
									}

									$view_dialog .= '<tr class="'.$color.'">';
									$view_dialog .= '<td>'.$index++.'</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>";

                    endforeach;
                    	
					
					
				
				endif;					
	
			$output .="</tbody>
			</table>
			</div>
			</div>";
		}else{
			$output .= '<div class="alert alert-danger alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                  <i class="icon fas fa-exclamation-triangle"></i> No submission yet!
                </div>';
		}
		
	
		echo $output;
		echo $view_dialog;
	}

	public function submission_action(){
		/*$error = '';
		$success = '';
		$id = "CSC1211_58_CSC20_2020_2021";*/
		if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
    	if($this->request->getMethod() == 'post'){
    		$error = '';
    		$success = '';
    		$id = $this->request->getPost("id");
    		if($this->request->getPost("action") == 'accept'){
    			$data = [
    				'hod_status'  => 'Accepted',
    			];
    			$st = $this->hod_model->edit_submission($data, $id);
    			if($st){
    				$success = "Result submission has been accepted";
    			}else{
    				$error = "Oops! Something went wrong. Try later.";
    			}
    
    			$output = array(
    				'error'		=>	$error,
    				'success'	=>	$success
    			);
    			echo json_encode($output);
    		}
    		if($this->request->getPost("action") == 'reject'){
    			$data = [
    				'submission_status'  => 'Rejected',
    				'eo_status'  => 'Rejected',
    				'hod_status'  => 'Rejected',
    			];
    			$st = $this->hod_model->edit_submission($data, $id);
    			if($st){
    				$success = "Result submission has been rejected";
    			}else{
    				$error = "Oops! Something went wrong. Try later.";
    			}
    
    			$output = array(
    				'error'		=>	$error,
    				'success'	=>	$success
    			);
    			echo json_encode($output);
    		}
    		if($this->request->getPost("action") == 'return'){
    			$data = [
    				'submission_status'  => 'Pending',
    				'eo_status'  => 'Pending',
    				'hod_status'  => 'Pending',
    			];
    			$st = $this->hod_model->edit_submission($data, $id);
    			if($st){
    				$success = "Result submission has been returned for editing";
    			}else{
    				$error = "Oops! Something went wrong. Try later.";
    			}
    
    			$output = array(
    				'error'		=>	$error,
    				'success'	=>	$success
    			);
    			echo json_encode($output);
    		}
    	}
    }


	public function course_submitted()
	{
	    
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}
		
		if($this->request->getMethod() == 'post'){
			
			//$id = $this->session->get('programme_id');
			//$level = $this->session->get('level')."";
			$programme = $this->request->getVar('progammes');
			//$programme = int
			$semester = $this->request->getVar('semester');

			$submission = $this->hod_model->get_programme_submitted_result($programme, $semester, '2020/2021');
			$data = [
				'page_title' => 'Course Submission',
				'user' => $this->session->get('name')
			];
			
			foreach($submission as $sub){
				if(isset($_POST[$sub->id])){
					$id = $_POST[$sub->id];	
					
					$data['submission'] = $this->levelcoordinator_model->get_marks($id);
					$data['detail'] = $this->levelcoordinator_model->get_course_detail_($id);
					
					echo view('templates/hod_header', $data);
					echo view('hod/course_submitted');
					echo view('templates/hod_footer');
					
				}else if(0){
					
				}else if(0){

				}
			}
			
		}
			

		
	}


	// get semesters available
	function get_semester_available($session)
	{
	    if(!session()->has('hod_logged')){
			return redirect()->to(base_url().'/head-login');
		}

		$session = urldecode($session);
		$session = str_replace("_","/",$session);
		$staff_no = $this->session->get('id');

		$username = $this->session->get('username');
		$programme = $this->levelcoordinator_model->get_semester($username, $session);
		
		$value = [];
		$output = "";
		if(!empty($programme)){
			$output .= '<div class="form-group">
					<label class="label"><b>Select Semester:</b></label>
					<select class="form-control select2" name="semester" id="semester" onchange="spawn_result()" required> 
					<option>Semester</option>';
			foreach($programme as $prog){
				$output .= "<option value = ".$prog->semester.">".$prog->semester."</option>";                                            
			}
			$output .= "</select>";
		}else{
			//$output .= "<br/><br/><h4>There is no result available for this session</h4>";
			$output .= '<div class="alert alert-danger alert-dismissible">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                  <i class="icon fas fa-exclamation-triangle"></i> No result available for this session yet!
                </div>';
		}
					
		echo $output;
	}
	
	public function logout(){
		$this->session->remove('logged_hod');
		$this->session->remove('name');
		$this->session->remove('faculty');
		$this->session->destroy();
		return redirect()->to(base_url()."/head-login");		
	}
}
