<?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('students')['Logged_In']){
			$this->load->model('mapmycareer/Custom_model','model');
			if($this->session->userdata('students')['Language']==1){
				$this->lang->load('information','english');
			}else{
				$this->lang->load('information','hindi');
			}
		}else{
			redirect(BASE_URL);
		}		         
    }
	
	
	public function index(){	
		
		$data['students'] = $this->model->get_students_details($this->session->userdata('students')['StudentId']);
		//var_dump($data['students']);die;
		if($data['students']->Gender==""){
			$this->load->view('mapmycareer/includes/mapmycareer_header',$data);
			$this->load->view('mapmycareer/student_update_profile');
			$this->load->view('mapmycareer/includes/mapmycareer_footer');
		}else{
		//	var_dump()die;
			$test_status=$this->model->get_students_test_status($this->session->userdata('students')['StudentId']);
			
			$ret = $this->set_completed_test($test_status);
			if($ret){
				$test_status=$this->model->get_students_test_status($this->session->userdata('students')['StudentId']);
			}
			
			//var_dump($test_status->ParticipateTestId);die;
			$data['test_status'] =$test_status;
			$data['tests']=$this->model->get_test_details($test_status->ParticipateTestId);
			//var_dump($data['tests']->Aptitude);die;
			$this->load->view('mapmycareer/includes/mapmycareer_header',$data);
			$this->load->view('mapmycareer/student_dashboard');
			$this->load->view('mapmycareer/includes/mapmycareer_footer');
		}
	}
	
	function set_completed_test($test_status){
		//var_dump($test_status);die;
		$set_status=false;
		if($test_status->ParticipateTestId==3){
			if($test_status->AptitudeStatus==1 && $test_status->PersonalityStatus==1){
			$set_status=true;
		}
		}
		if($test_status->AptitudeStatus==1 && $test_status->PersonalityStatus==1 && $test_status->InterestStatus==1){
			$set_status=true;
		}
		if($set_status){
			$ind_stu=array(
				'TestStatus' => 1
			);
			$this->db->where('id',$this->session->userdata('students')['StudentId']);
			$this->db->update('tblstudents',$ind_stu);
			$ses=$this->session->userdata('students');
			$ses['TestStatus']=1;
			$this->session->set_userdata('students',$ses);
			return true;
		}
		return false;
	}
	
	/* function set_completed_test($test_status){
		var_dump($test_status);
		$tests=$this->model->get_test_details($test_status->ParticipateTestId);
		var_dump($tests);die;
		$test_s=false;
		if($tests->Aptitude==1 && $tests->Personality==1 && $tests->Interest==0){
			$test_s=true;
		}
		if($test_status->AptitudeStatus==1 && $test_status->PersonalityStatus==1 && $test_status->InterestStatus==1){
			$test_s=true;
		}
		if($test_s){
			$ind_stu=array(
				'TestStatus' => 1
			);
			$this->db->where('id',$this->session->userdata('students')['StudentId']);
			$this->db->update('tblstudents',$ind_stu);
			$ses=$this->session->userdata('students');
			$ses['TestStatus']=1;
			$this->session->set_userdata('students',$ses);
			return true;
		}
		return false;
	} */
	 
	function profile(){
		//var_dump($this->input->post());die;
		$ind_stu=array(
			'Name' 		=>$this->input->post('f_name'),
			'ParentsName' => $this->input->post('l_name'),
			'DoB' 		=> $this->input->post('age'),
			'Gender'	=> $this->input->post('optradio'),
			'PreferredLanguage' => $this->input->post('language')
		);
		$this->db->where('id',$this->session->userdata('students')['StudentId']);
		$this->db->update('tblstudents',$ind_stu);
		
		
		$ses=$this->session->userdata('students');
		$ses['Name']=$this->input->post('f_name');
		$ses['Language']=$this->input->post('language');
		$this->session->set_userdata('students',$ses);
		/* $students_array = array(
			'StudentId'    => $data->id,
			'Name'   	   => $this->input->post('f_name'),
			'TestId'   	   => $data->ParticipateTestId,
			'TestStatus'   => $data->TestStatus,
			'EmailId'      => $data->EmailId,					 
			'Logged_In'    => TRUE
		);
				
				$this->session->set_userdata('students', $students_array); */
		
		echo json_encode(array('success'=>true));
		
	}
	
	
	function accept_test($type,$key){
		if($type==1){
			$up_data=array(
				'IsAptitudeAccept'=>1
			);
		}
		if($type==2){
			$up_data=array(
				'IsPersonalityAccept'=>1
			);
		}
		if($type==3){
			$up_data=array(
				'IsInterestAccept'=>1
			);
		}
		$userId = $this->session->userdata('students')['StudentId'];
		$status=$this->model->get_students_test_status($userId);
		if($status){
			$this->db->where('StudentId',$userId);
			$this->db->update('tblstudents_test_status',$up_data);
		}else{
			$up_data['StudentId'] = $userId;
			$this->db->insert('tblstudents_test_status',$up_data);
		}
				
		redirect(BASE_URL.'start/'.$key);
	}
	
	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;
	}
	
	 
	
 
	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('mapmycareer/user_download_pdf_report_view');
	}
	
	function download_pdf($tid="", $sid=""){
		if($tid!="" && $sid!=""){
			$exitS=$this->model->get_exit_student($tid,$sid);
			if($exitS){
				
				$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;
				$data['UserTestType'] = $this->model->get_ext_test_type($tid);
				
				//$this->load->view('mapmycareer/user_download_pdf_report_view', $data);
				$reportsData = $this->load->view('mapmycareer/user_download_pdf_report_view', $data, true);		 
				$get_url = $this->create_pdf($sid, $reportsData, $exitS); 
			}else{
				redirect(BASE_URL .'students');
			}
		}else{
			redirect(BASE_URL .'students');
		}
		
	}
	
	
	
	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(10, 15, 10, true); 
		$pdf->setColor('fill', 100, 120, 220);
		//$pdf->SetTopMargin(0);
		$banner='<img src="'.HTTP_IMAGES_PATH.'pdf/pdf_background.jpg"/>';
		$userTedxt='<h3 style="color:#a74453;width: 350px;">Full Name: <b style="  border-bottom: 2px solid;width: 260px;text-align: right;float: right;">'.$exitS->Name.'</b></h3><h1 style="color:#a74453;">SKILL EXPLORER REPORT</h1>';
		$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, 1, 1 , 250, $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, false, ''); 
		
		$pdf->lastPage();
		 
		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;
	 
	}
}