<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
Expert panel user story view
Author @deepak saini
*/


class Students extends CI_Controller {	 
	public function __construct() {
     parent::__construct();
		if($this->session->userdata('mapmyadmin')['Logged_In']){			 
			$this->load->model('webadmin/Custom_model','model');
			 
		}else{
			redirect(ADMIN_URL);
		}		         
    }
	
	
	public function index(){		
		redirect(ADMIN_URL);
	}
	 /* ["SectionId"]=> string(1) "1" ["SectionName"]=> string(20) "Operational Aptitude" ["marks"]=> string(2) "21" ["SGrade"]=> string(1) "H"  */
	 
	
	public function records($testId){
		$data['test']=$this->model->get_test_details($testId);
		$data['students'] = $this->model->get_students_list($testId);
		$this->load->view('webadmin/includes/mapmycareer_header',$data);
		if($this->session->userdata('mapmyadmin')['RoleId']==1){	
			$this->load->view('webadmin/student_list_view');
		}else{		
			$this->load->view('webadmin/consular_student_list_view');
		}
		$this->load->view('webadmin/includes/mapmycareer_footer');
	}
	
	function report($tid="", $sid=""){
		if($tid!="" && $sid!=""){
			$exitS=$this->model->get_exit_student($tid,$sid);
			if($exitS){					 
				$data=$this->skills_logic($tid,$sid);			 
				$data['TestId']=$tid;
				$data['StudentId'] =$sid;
				$data['test']=$this->model->get_test_details($tid);
				//var_dump($data['test']);die;
				$this->load->view('webadmin/includes/mapmycareer_header',$data);
				$this->load->view('webadmin/student_report_view');
				$this->load->view('webadmin/includes/mapmycareer_footer');
			}else{
				redirect(ADMIN_URL);
			}
		}else{
			redirect(ADMIN_URL);
		}
		
	}
	
	function skills_logic($tid,$sid){
		$data=array();
		$student_result = $this->get_student_record($tid,$sid);
		$data['Reports'] = $student_result;
		 /* echo '<pre>';
		print_r($student_result);die;   */
		
		$TotalHighFit=0;
		$Recommendation_array = array();
		$master_grade=array();
		$master_score=array();
		foreach($student_result as $row){
			$array=$row['GroupScore_array'];
			$maxs = array_search(max($array), $array);
			$master_score[] = $maxs;
			$master_grade = $master_grade + $row['GroupGrade_array'];
			//$master_score[] = array('GroupId'=>$maxs,'GroupScore'=>max($array));
		}
		
		/* echo '<pre>';
			print_r($master_score);  die;  */
		//student interest strat
		$student_interests = $this->model->get_student_career_interest($tid, $sid);
		
		$student_interests_array=array();
		foreach($student_interests as $interest){
			$intrest_group = $this->model->get_career_interest_map($tid, $interest['VocationalCareerId']);
			$mH=0;$mM=0;$mL=0;
			foreach($intrest_group as $groups_row){
				$m_h=0;$m_m=0;$m_l=0;
				foreach($groups_row as $group){
					if(isset($master_grade[$group['GroupId']])){
						if($master_grade[$group['GroupId']]=='L'){
							$m_l++;
						}
						if($master_grade[$group['GroupId']]=='H'){
							$m_h++;
						}
						if($master_grade[$group['GroupId']]=='M'){
							$m_m++;
						}
					}
				}
				if($m_l>0){
					$mL++;
				}else{
					if($m_h>0){
						$mH++;
						
					}else{
						$mM++;
					}
				}
			}
			$int_p='';
			if($mL>0){
				$int_p='L';
			}else{
				if($mH>0){
					$int_p='H'; 
					$TotalHighFit++;
					$Recommendation_array[$interest['VocationalCareerId']] = $interest;
				}else{
					$int_p='M';
				}
			}
			
			$interest['Priority']=$int_p;
			$student_interests_array[]=$interest;
			
		}
		
	/* 	echo '<pre>';
			print_r($Recommendation_array); */
		// Only high fit record
		if($TotalHighFit<3){
			$recomms=$this->model->get_recommendation_list($tid, $master_score);
			foreach($recomms as $rm){
				if(isset($Recommendation_array[$rm['VocationalCareerId']])){
				}else{
					if($TotalHighFit<3){
						$Recommendation_array[$rm['VocationalCareerId']]=$rm;
						$TotalHighFit++;
					}
				}
			}
		}
		
		//both hight and Moderate fit
		if($TotalHighFit<3){
			$recomms=$this->model->get_recommendation_list($tid, $master_score,1);
			foreach($recomms as $rm){
				if(isset($Recommendation_array[$rm['VocationalCareerId']])){
				}else{
					if($TotalHighFit<3){
						$Recommendation_array[$rm['VocationalCareerId']]=$rm;
						$TotalHighFit++;
					}
				}
			}
		}
		
		/* echo '<pre>';
		print_r($student_interests_array);die; */
		
		
		$data['Interests']=$student_interests_array;
		$data['Recommendations']=$Recommendation_array;
		
		return $data;
	}
	
	function get_student_record($tid,$sid){
		$result_array=array();
		$master_type_grade=array();
		$tesType=$this->model->get_ext_test_type($tid);
		foreach($tesType as $test_type){
			$result_array[$test_type['id']]['Type']=$test_type;
			$sectionData=$this->model->get_ext_test_type_section_grade($sid,$tid,$test_type['id']);
			 
			$result_array[$test_type['id']]['Section']=$sectionData;
			//var_dump($sectionData[0]);die;
			$tempSectiom_grade=array();
			$tempSectiom_marks=array();
			foreach($sectionData as $type_section){
				$tempSectiom_grade[$type_section['SectionId']]=$type_section['SGrade'];
				$tempSectiom_marks[$type_section['SectionId']]=$type_section['Marks'];
			}
			 
			$result_array[$test_type['id']]['SectionGrade'] = $tempSectiom_grade;
			$result_array[$test_type['id']]['SectionMarks'] = $tempSectiom_marks;
			
			$Section_grade = array();
			$groupData=$this->model->get_ext_test_type_group_grade($tid,$test_type['id']);
			//var_dump($groupData[0]);die;
			$tempGroup_grade=array();
			$tempGroup_marks=array();
			foreach($groupData as $group){
				$grGrade = $this->model->get_group_grade($tempSectiom_grade,$group['SectionIds']);
				$grSroce = $this->model->get_group_score($tempSectiom_marks,$group['SectionIds']);
				$tempGroup_grade[$group['GroupId']] = $grGrade;
				$tempGroup_marks[$group['GroupId']] = $grSroce;
				
				$group['GroupGrade'] = $grGrade;
				$group['GroupScore'] = $grSroce;
				$Section_grade[]=$group;
			}
			
			$result_array[$test_type['id']]['Group']=$Section_grade;
			$result_array[$test_type['id']]['GroupGrade_array'] = $tempGroup_grade;
			$result_array[$test_type['id']]['GroupScore_array'] = $tempGroup_marks;
			
			//$result_array[$test_type['id']]['GroupGrade']=$tempSection_grade;
		}
		//$result_array['UserGrades'] = $master_type_grade;
		
		/* echo '<pre>';
		print_r($master_type_grade); die;  */
		return $result_array;
	}
	
	/* SELECT `id`, `StudentCode`, `ParticipateTestId`, `Name`, `ParentsName`, `EmailId`, `DoB`, `Education`, `LastExaminationMarks`, `DistrictCode`, `TrainingCenterCode`, `State`, `IsActive`, `CreatedDate` FROM `tblstudents` WHERE 1 */
	/* SELECT `id`, `StudentId`, `TestId`, `TestTypeId`, `QuestionId`, `QuestionMarks`, `IsActive`, `MarksDate` FROM `tblstudent_marks` WHERE 1 */
	function uploads(){
		$data=array();
		if($this->input->post()){
			$this->load->library('PHPExcel');
			//var_dump($_FILES['student_excel_file']['name']);die;
			if(!empty($_FILES['student_excel_file']['name'])) {	
				$ext = pathinfo($_FILES['student_excel_file']['name'], PATHINFO_EXTENSION);
				if($ext=='xlsx'){
					$file_name=$this->do_upload_excel_file();  
					if(isset($file_name['error'])){
						$data['error'] = $file_name['error'].' <a href="'.ADMIN_URL.'students/uploads" ><b>OK</b></a>';
					}else{
						$xl_obj = new PHPExcel();
						$reader = PHPExcel_IOFactory::createReader('Excel2007');
						$reader->setReadDataOnly(true);
						$objPHPExcel = $reader->load('assets/uploads/'.$file_name);
						$sheetNames = $objPHPExcel->getSheetNames();
						$data_results = array();
						foreach($sheetNames as $key=>$value){
							$totalrows=0;
							if($value=="Profile"){
								$totalrows=$objPHPExcel->setActiveSheetIndex($key)->getHighestRow();  
								 
								$objWorksheet=$objPHPExcel->setActiveSheetIndex($key);  
								for($i=2;$i<=$totalrows;$i++) {
									if(!empty($objWorksheet->getCellByColumnAndRow(0,$i)->getValue())){
										$code	= $objWorksheet->getCellByColumnAndRow(0,$i)->getValue();
										$name	= $objWorksheet->getCellByColumnAndRow(1,$i)->getValue(); 
										$f_name	= $objWorksheet->getCellByColumnAndRow(2,$i)->getValue();  
										$dob	= $objWorksheet->getCellByColumnAndRow(3,$i)->getValue();  
										$edu	= $objWorksheet->getCellByColumnAndRow(4,$i)->getValue();  
										$l_mark	= $objWorksheet->getCellByColumnAndRow(5,$i)->getValue();  
										$d_code	= $objWorksheet->getCellByColumnAndRow(6,$i)->getValue();  
										$t_code	= $objWorksheet->getCellByColumnAndRow(7,$i)->getValue();  
										$state	= $objWorksheet->getCellByColumnAndRow(8,$i)->getValue();  

										$email	= $code .'@gmail.com';			 
										$data_user=array(
											'StudentCode'		=> $code, 
											'ParticipateTestId'	=> 1,				
											'Name'				=> $name,
											'ParentsName'		=> $f_name,
											'EmailId'			=> $email,
											'DoB'				=> $dob,
											'Education'			=> $edu,
											'LastExaminationMarks'	=> $l_mark,
											'DistrictCode'			=> $d_code,
											'TrainingCenterCode'	=> $t_code,
											'State'					=> $state
										); 
										
										$this->db->insert('tblstudents',$data_user);
										$data_user['Id'] = $this->db->insert_id();
										$data_results[$code] = $data_user;
									}
								}
							}
							if($value=="Aptitude" || $value=="Personality"){
								if($value=="Aptitude"){
									$test_typee = 1;
								}
								if($value=="Personality"){
									$test_typee = 2;
								}
								
								$totalrows=$objPHPExcel->setActiveSheetIndex($key)->getHighestRow();  
								$objWorksheet=$objPHPExcel->setActiveSheetIndex($key);
								for($i=2;$i<=$totalrows;$i++) {
									if(!empty($objWorksheet->getCellByColumnAndRow(0,$i)->getValue())){
										
										$code	= $objWorksheet->getCellByColumnAndRow(0,$i)->getValue();
										$q=1;
										$bulk_ans_array=array();
										for($j=2;$j<51;$j++){
											$data_user=array(
												'StudentId'		=> $data_results[$code]['Id'], 
												'TestId'		=> 1,				
												'TestTypeId'	=> $test_typee,
												'QuestionId'	=> $q++,
												'QuestionMarks'	=> $objWorksheet->getCellByColumnAndRow($j,$i)->getValue()
											 
											);
											$bulk_ans_array[]=$data_user;
										}
										$this->db->insert_batch('tblstudent_marks', $bulk_ans_array); 
									}
								}
								
							}
						}
						 
						redirect(ADMIN_URL); exit;
					}
				}else{
					$data['error'] = '<h3 style="text-align:center;margin-top:50px;">Please select excel file with (xlsx) format</h3><p style="text-align:center; "><a href="'.ADMIN_URL.'students/uploads" ><b>OK</b></a></p>';
					 
				}
			}else{
				$data['error'] = '<h3 style="text-align:center;margin-top:50px;">Please select excel file with (xlsx) format</h3>';
			}
		}
		
		
		$this->load->view('webadmin/includes/mapmycareer_header',$data);
		$this->load->view('webadmin/upload_student_excel_view');
		$this->load->view('webadmin/includes/mapmycareer_footer');
	}
	
	
 
	public function do_upload_excel_file(){
		$path="./assets/uploads/";	 
		$config['upload_path']          = $path;
		$config['allowed_types']        = 'xlsx';
		$config['encrypt_name']        = TRUE; 
		$config['remove_spaces']        = TRUE;
		$config['overwrite']            = TRUE;
		 
		
		$this->upload->initialize($config);
		if ( ! $this->upload->do_upload('student_excel_file')){
			$error = array('error' => $this->upload->display_errors());
			return $error;
				 
		}else{
			$upload_data = array('upload_data' => $this->upload->data());
			$file_name=$upload_data['upload_data']['file_name'];
			return $file_name;		
			
		}
	}
	
	function text(){
		$this->load->view('webadmin/user_download_pdf_report_view');
	}
	
	function download_pdf($tid="", $sid=""){
		if($tid!="" && $sid!=""){
			$exitS=$this->model->get_exit_student($tid,$sid);
			if($exitS){
				$data=$this->skills_logic($tid,$sid);
				
				$data['UserTestType'] = $this->model->get_ext_test_type($tid);
				//$this->load->view('webadmin/user_download_pdf_report_view', $data);
				$reportsData = $this->load->view('webadmin/user_download_pdf_report_view', $data, true);		 
				$get_url = $this->create_pdf($sid, $reportsData, $exitS); 
			}else{
				redirect(ADMIN_URL);
			}
		}else{
			redirect(ADMIN_URL);
		}
		
	}
	
	
	
	function create_pdf($UserId, $recipesData , $exitS){
		
		$this->load->library('Pdf');
		 
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		$pdf->SetCreator(PDF_CREATOR); 
		$pdf->setPrintHeader(false);
		$pdf->setPrintFooter(false);
		$pdf->SetHeaderMargin(0);
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
		
		$pdf->SetAutoPageBreak(TRUE, 10); 
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); 
		/* 
		$pdf->SetMargins(0, 0, 0,true); 
		$pdf->SetTopMargin(-10);  */
		
		/* if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
			require_once(dirname(__FILE__).'/lang/eng.php');
			$pdf->setLanguageArray($l);
		}  */
		$pdf->SetFont('helvetica', '', 11); 
		$pdf->AddPage();
		$pdf->SetMargins(15, 15, 15, true); 
		$pdf->setColor('fill', 100, 120, 220);
		//$pdf->SetTopMargin(0);
		$banner='<img src="'.HTTP_IMAGES_PATH.'pdf/pdf_background.jpg"/>';
		$userTedxt='<h1 style="color:#a74453;">SKILL EXPLORER REPORT</h1><h3 style="color:#a74453;width: 350px;">Name: <b style="  border-bottom: 2px solid;width: 260px;text-align: right;float: right;">'.$exitS->Name.'</b><br>Center: <b style="  border-bottom: 2px solid;width: 260px;text-align: right;float: right;">'.$exitS->TrainingCenterCode.'</b></h3>';
		$pdf->writeHTMLCell(215, 220, -1, 0, $banner, 0, 1, 0, 0, 0, 0);
		$banner_in='<img src="'.HTTP_IMAGES_PATH.'pdf/skiller_top.png"/>';
		$pdf->writeHTMLCell(100, 100, 55, 80, $banner_in, 0, 0, 0, 0, 0, 0);
		
		$pdf->writeHTMLCell(215, 35, 1 , 245, $userTedxt, 0, 1, false, true, 'C', true);
		//writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=false, $reseth=true, $align='', $autopadding=true)
		
		$pdf->writeHTML($recipesData, true, false, true, true, 'J');
		//$pdf->writeHTML($recipesData, true, false, true, 'J', ''); 
		
		$pdf->lastPage();
		ob_end_clean();
		//ob_clean();
		//$filename=md5('pdf_print'.$UserId).'.pdf';		
		$filename='StudentId_'.$UserId.'.pdf';	
		$pdf->Output($filename, 'D');
		 
		//return redirect('/');
		//$pdf->Output($_SERVER['DOCUMENT_ROOT'] .'gofor20/assets/pdf/'.$filename, 'F');
		//return HTTP_FOLDER_PATH . 'pdf/'.$filename;
	 
	}
}