<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Alumni extends MY_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->model('crm/country');
		$this->load->model('crm/general_model');
		$this->load->model('hr/model_alumni');

		if($this->logged_user = $this->session->userdata('user')){
			$this->login->checkModuleAccess(4);
			$this->logged_module = $_SESSION['module_data'];
		} else {
			redirect(base_url());
		}
	}

	public function index()
	{
		$this->alumniList();
	}

	public function alumniList()
	{

		$data = array(
			'alumni_list' 	=> $this->model_alumni->get_alumni_list(),
			'page_setup' 	=> $this->template->pageSetup('HR', '', 'Alumni List'),
			'states'		=> $this->general_model->get_all('_ref__state'),
			'countries'		=> $this->country->country_all(),
		);

		$this->template->view('hr/alumni/alumni_list', $data);	
	}

	public function save_alumni()
	{

		$insert_data = array(
			'name' 			=> $this->input->post('alumni_name'), 
			'address'		=> $this->input->post('alumni_address'),
			'postcode' 		=> $this->input->post('alumni_postcode'),
			'city' 			=> $this->input->post('alumni_city'),
			'state_id' 		=> $this->input->post('alumni_state'),
			'country_id' 	=> $this->input->post('alumni_country'),
			'contact_no' 	=> $this->input->post('alumni_contact'),
			'email' 		=> $this->input->post('alumni_email'),
			'dob' 			=> date("Y-m-d", strtotime($this->input->post('alumni_dob'))),
			'year_resigned' => $this->input->post('alumni_resign_year'),
			'curr_employer' => $this->input->post('alumni_curr_employer'),
			'createdBy' 	=> $_SESSION['user']['id'],
		);

		$insert_alumni = $this->model_alumni->save_alumni($insert_data);

		if($insert_alumni){
			$this->session->set_flashdata('success',"Successfully save Alumni.");
		}else{
			$this->session->set_flashdata('error',"System failed to save Alumni.");
		}

		redirect(base_url('hr/alumni'));

	}

	public function get_alumni_details()
	{	
		$alumni_id 	= $this->input->post('alumni_id');
		$alumniData = $this->model_alumni->get_alumni_details_byID($alumni_id);

		if($alumniData)
        {
          	print json_encode(array(
                "status" 	=> "success",
                "alumni"	=> $alumniData
            ));

        }
        else
        {
        	print json_encode(array(
                "status" 	=> "failed",
                "message" 	=>  "failed"
            ));
        }
	}

	public function edit_alumni()
	{
		$set = array(
			'name' 			=> $this->input->post('alumni_name_edit'), 
			'address'		=> $this->input->post('alumni_address_edit'),
			'postcode' 		=> $this->input->post('alumni_postcode_edit'),
			'city' 			=> $this->input->post('alumni_city_edit'),
			'state_id' 		=> $this->input->post('alumni_state_edit'),
			'country_id' 	=> $this->input->post('alumni_country_edit'),
			'contact_no' 	=> $this->input->post('alumni_contact_edit'),
			'email' 		=> $this->input->post('alumni_email_edit'),
			'dob' 			=> date("Y-m-d", strtotime($this->input->post('alumni_dob_edit'))),
			'year_resigned' => $this->input->post('alumni_resign_year_edit'),
			'curr_employer' => $this->input->post('alumni_curr_employer_edit'),
			'updatedBy' 	=> $_SESSION['user']['id'],
		);

		$where = array
        (
            'id' => $this->input->post('alumni_id_edit'),
        );

		$update_alumni = $this->model_alumni->update_alumni($set, $where);

		if($update_alumni){
			$this->session->set_flashdata('success',"Successfully update Alumni.");
		}else{
			$this->session->set_flashdata('error',"System failed to update Alumni.");
		}

		redirect(base_url('hr/alumni'));
	}

	public function delete_alumni()
	{
		$set = array(
			'is_delete' => 1,
			'updatedBy' => $_SESSION['user']['id'],
		);

		$where = array
        (
            'id' => $this->input->post('alumni_id'),
        );

		$delete_alumni = $this->model_alumni->update_alumni($set, $where);

		if($delete_alumni)
		{
			print json_encode(array(
				"status" => "Success",
				"msg"	 => "Successfully delete Alumni."
			));
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "System failed to delete Alumni."
			));
		}
	}


	public function upload_profile_pic()
	{
		if(isset($_FILES['attachment'])){

			$data 			= $this->input->post();
			$file_location  = '/hr/Alumni/'.$data['alumni_id'].'/'.'pics/';
			$data_pic 		= $this->upload("image", "attachment", $file_location);

			$set = array
	        (
	        	'file_name' 	=> $_FILES['attachment']['name'], 
				'file_location'	=> 'assets/uploads/'.$file_location,
	            'updatedBy' 	=> $_SESSION['user']['id'],
	        );

	        $where = array
	        (
	            'id' => $data['alumni_id'],
	        );

	        $update_pic = $this->model_alumni->update_alumni($set, $where);

			if($update_pic)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Profile Picture uploaded successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to upload Profile Picture."
				));
			}
		}
	}

	private function upload($type, $file, $file_location){
		$fcpath = str_replace('\\','/',FCPATH);
		$dir = str_replace('\\','/',$fcpath.'assets/uploads/'.$file_location);
		$dir = str_replace('\\','/',$dir);
		$file_name = str_replace(' ', '_', trim(addslashes(substr($_FILES[$file]['name'],-50))));
		$url = NULL;

		(!file_exists($dir))?mkdir($dir, 0777, true):chmod($dir, 0777);

		if (is_uploaded_file($_FILES[$file]['tmp_name']))
		{
			if($type == 'document') $file_types = 'pdf|doc|docx';
			if($type == 'image') $file_types = 'jpg|jpeg|bmp|png|gif|svg|ico';
			if($type == 'attachment') $file_types = 'pdf|doc|docx|jpg|jpeg|bmp|png|gif|svg|ico';

			$config = array(
				'allowed_types' => $file_types,
				'upload_path' => $dir,
				'file_name' => $file_name,
				'max_size' => 0,
				'overwrite' => TRUE
			);

			$this->load->library('upload', $config);

			if ($this->upload->do_upload($file))
			{
				if($upload_data = $this->upload->data())
				{
					if($type=="image")
					{
						// GET WIDTH & HEIGHT TO RESIZE & CROP
						$oriWidth  = (isset($upload_data['image_width']) > 0) ? $upload_data['image_width'] : 1; // ORIGINAL WIDTH
						$oriHeight = $upload_data['image_height'];											     // ORIGINAL HEIGHT
						$resWidth  = floor(($oriWidth > 500) ? 500 : $oriWidth); 							     // WIDTH TO RESIZE
						$resHeight = floor(($resWidth/$oriWidth)*$oriHeight); 								     // HEIGHT TO RESIZE

						if ($resHeight > 500)
						{
							$resWidth = floor((500/$resHeight)*$resWidth);
							$resHeight = 500;
						}

						// MANIPULATION CONFIGURATION FOR RESIZING
						$manipulate['image_library']  = 'gd2';
						$manipulate['source_image']   = $upload_data['full_path'];
						$manipulate['maintain_ratio'] = TRUE;
						$manipulate['width']     	  = $resWidth;
						$manipulate['height']   	  = $resHeight;

						$this->load->library('image_lib', $manipulate);
						$this->image_lib->resize();
					}

					$data['file_name'] 	   = $upload_data['file_name'];
					$data['file_location'] = 'assets/uploads/'.$file_location;
				}
				else
				{
					if($type=="image")
					{
						$data['file_name'] 	   = 'default.png';
						$data['file_location'] = 'assets/uploads/defaults';
					}
				}
			}
			else
			{
				if($type=="image")
				{
					$data['file_name'] 	   = 'default.png';
					$data['file_location'] = 'assets/uploads/defaults';
				}
			}
		}

		return $data;
	}

	public function get_alumni_filter()
	{
		$year 	= (!empty($this->input->post('alumni_filter_year')))? $this->input->post('alumni_filter_year'):null;

		if (!empty($year) && $year > 0) {
			$this->session->set_userdata('alumni_filter_year',$year);
		} else {
			$this->session->set_userdata('alumni_filter_year','ALL');
		}

		$table 	= $this->model_alumni->get_alumni_list($year);
		
		$data 	= array
		(
			'status' 				=> 'success',
			'message'				=> '',
			'table'					=> $table,
			'alumni_filter_year' 	=> $this->input->post('alumni_filter_year'),
		);

		$this->session->set_userdata('hr__filter_alumni', $data['table']);
		echo json_encode($data);
		return true;
	}

	public function print_alumniList()
	{
		$this->load->model('hr/model_alumni');

		$date = date("d-m-Y");
		$year = $this->session->userdata('alumni_filter_year');

		if(!empty($this->session->userdata('hr__filter_alumni')) && $this->session->userdata('alumni_filter_year') != 'ALL')
		{
			$data['alumni_list'] = $this->model_alumni->get_alumni_list($year);
		} else {
			$data['alumni_list'] = $this->model_alumni->get_alumni_list();
		}

		$data['title'] = 'SALIHIN ALUMNI LIST AS AT ' . $date;

		$this->load->view('hr/report/header.php', $data);
		$this->load->view('hr/alumni/report/alumni_list.php', $data);
		$this->load->view('hr/report/footer.php');
	}
}

?>