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


class Myprofile_arep extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		if(empty($this->session->userdata('user')['id'])) redirect(base_url());
		else 
			$this->logged_user = $this->session->userdata('user');
		
		$this->load->model('admin/model_company');
		$this->load->model('admin/Model_user');
		
		$this->load->model('crm/model_crm');
		$this->load->model('crm/country');
		$this->load->model('crm/general_model');
		
		$this->load->model('hr/model_user_license','license');
		$this->load->model('hr/model_user_license_attachment','license_attachment');
		$this->load->model('hr/model_user_address','address');
		$this->load->model('hr/model_user_family','family');
		$this->load->model('hr/model_academic_qualification','academic');
		$this->load->model('hr/model_academic_qualification_attachment','academic_attachment');
		$this->load->model('hr/model_professional_membership','promember');
		$this->load->model('hr/model_professional_membership_attachment','promember_attachment');
		$this->load->model('hr/model_job_history','jobs');
		$this->load->model('hr/model_bank','bank');
		$this->load->model('hr/model_recognition','recognition');
		$this->load->model('hr/model_recognition_attachment','recognition_attachment');
		$this->load->model('hr/model_staff_action','staff_action');
		$this->load->model('hr/model_user_contract_element','contract');
		$this->load->model('hr/model_third_party_payment','thirdParty');
		$this->load->model('hr/model_personal_attachment','attachment');
		$this->load->model('hr/model_user_pcb','pcb');
		$this->load->model('hr/model_action_type','action');
		$this->load->model('hr/model_basic_pay','basic_pay');
		$this->load->model('hr/model_statutory_detail','stats');
		$this->load->model('hr/model_joining_group','join_group');
		$this->load->model('hr/model_user_recurring','recurring');

		/* newly add */
		$this->load->model('hr/model_user_pursuing_study','pursuing_study');
		$this->load->model('hr/model_user_case_emergency','case_emergency');
		/* end of newly add */

		if($this->logged_user)
		{
			$this->login->checkModuleAccess(4);
			$this->logged_module = $this->session->userdata('module_data');

			if($this->logged_module['role'] != 'admin'){
				redirect(base_url('/hr'));
			}
			// die(debug($this->logged_module));
		}
		else
		{
			redirect(base_url());
		}	 
	}

	private function get_profiling_id($profiling_id=0){
		if($profiling_id ==0) {
			$this->db->query('insert into  user__profiling (user_id, staff_id, title_id, gender_id, ic_no, passport_expired_date, working_expired_date, place_issue, birth_date, birth_place, hobby, citizen_id, religion_id, race_id, residential_id, marital_status, married_date, primary_email, secondary_email, action_type_id, action_efective_date)  select user_id, staff_id, title_id, gender_id, ic_no, passport_expired_date, working_expired_date, place_issue, birth_date, birth_place, hobby, citizen_id, religion_id, race_id, residential_id, marital_status, married_date, primary_email, secondary_email, 10000, now() from user__profiling where user_id = '.$this->session->userdata('user')['id'].' order by id desc limit 1',false);
			$new_profiling_id = $this->db->insert_id();
			return($new_profiling_id);
		}else return $profiling_id; 	
	}

	private function upload($type, $file, $file_location){
		$fcpath = str_replace('\\','/',FCPATH);
		$dir = str_replace('\\','/',$fcpath.'application/storage/'.$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|xlsx';
			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'] = 'application/storage/'.$file_location;
				}
				else
				{
					if($type=="image")
					{
						$data['file_name'] 	   = 'default.png';
						$data['file_location'] = 'application/storage/defaults';
					}
				}
			}
			else
			{
				if($type=="image")
				{
					$data['file_name'] 	   = 'default.png';
					$data['file_location'] = 'application/storage/defaults';
				}
			}
		}

		return $data;
	}

	function getLicense()
	{
		$license_id  	= $this->input->post('license_id');
		$profiling_id   	= $this->input->post('profiling_id');

		$licenseData 	= $this->license->fetchLicense(null,false,$profiling_id,$license_id);

		$query = $this->db->last_query();

		if($licenseData)
        {
          	print json_encode(array(
                "status" 			=> "success",
                "license"		=> $licenseData,
                "query"				=> $query
            ));

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

	function saveLicense()
	{
		$upload_path = 'hr/profiling/action/staff/'.$this->session->userdata('user')['id'].'/infotype/7/'.$this->input->post('attachment_name');

		$insertData = array(
			'profiling_id' 			=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'				=> $this->session->userdata('user')['id'],
			'profession'   			=> $this->input->post('license_profession'),
	        'license_no' 			=> $this->input->post('license_no'),
	        'registration_date'  	=> ($this->input->post('license_registration_date'))?date('Y-m-d',strtotime($this->input->post('license_registration_date'))):'0000-00-00',
	        'renewal_date'  		=> ($this->input->post('license_renewal_date'))?date('Y-m-d',strtotime($this->input->post('license_renewal_date'))):'0000-00-00',
	        'created_at'			=> date('Y-m-d H:i:s')
		);
        
		$newLicense = $this->license->createLicense($insertData);

        if($newLicense)
        {
        	if(isset($_FILES['attachment_file']))
        	{
        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'license_id'					=> $newLicense,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> $upload_path,
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '7'.$newLicense.''.date('Ymd').''.uniqid(),
        		);
        		$save_attachment = $this->license_attachment->createAttachment($data_attachment);

				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);
			}

			print json_encode(array(
			    "status"     		=> "success",
				"message" 			=> "successfully add academic qualification",
			    "newLicense" 	=> $newLicense,
			    "redirect"		=> base_url('hr/Myprofile/index/'.$insertData['profiling_id'])
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"message" 	=> "failed to add academic qualification",
				"redirect"		=> base_url('hr/Myprofile/index/'.$insertData['profiling_id'])
			));
        }
	}

	function save_editLicense()
	{
		$license_id =  $this->input->post('id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

		$deleteLicense = $this->license->editLicense($updateData,$license_id);
		$deleteLicenseAttachment = $this->license_attachment->editAttachment(array(
			'is_delete' => 1),null,$license_id);

		$upload_path = 'hr/profiling/action/staff/'.$this->session->userdata('user')['id'].'/infotype/7/'.$this->input->post('attachment_name');

		$insertData = array(
			'profiling_id' 			=> $this->get_profiling_id($this->input->post('profiling_id')),
			'user_id'				=> $this->session->userdata('user')['id'],
			'profession'   			=> $this->input->post('license_profession'),
	        'license_no' 			=> $this->input->post('license_no'),
	        'registration_date'  	=> ($this->input->post('license_registration_date'))?date('Y-m-d',strtotime($this->input->post('license_registration_date'))):'0000-00-00',
	        'renewal_date'  		=> ($this->input->post('license_renewal_date'))?date('Y-m-d',strtotime($this->input->post('license_renewal_date'))):'0000-00-00',
	        'created_at'			=> date('Y-m-d H:i:s')
		);
        
		$newLicense = $this->license->createLicense($insertData);

        if($newLicense)
        {
        	if(isset($_FILES['attachment_file']))
        	{
        		$data_attachment = array
        		(
        			'user_id'						=> $this->session->userdata('user')['id'],
        			'license_id'					=> $newLicense,
        			'attachment_name'				=> $_FILES['attachment_file']['name'],
        			'location'						=> $upload_path,
        			'file_type'						=> $_FILES['attachment_file']['type'],
        			'file_ext'						=> $_FILES['attachment_file']['type'],
        			'mask_id' 						=> '7'.$newLicense.''.date('Ymd').''.uniqid(),
        		);
        		$save_attachment = $this->license_attachment->createAttachment($data_attachment);

				$upload_image = $this->upload("attachment", "attachment_file", $upload_path);
			}

			print json_encode(array(
			    "status"     	=> "success",
			    "updateLicense" => $newLicense,
			    "redirect"		=> base_url('hr/Myprofile/index/'.$insertData['profiling_id'])
			));

        } else {
			print json_encode(array(
				"status" 	=> "failed",
				"message" 	=> "failed",
				"redirect"		=> base_url('hr/Myprofile/index/'.$insertData['profiling_id'])
			));
        }
	}

	function deleteLicense()
	{
		$license_id =  $this->input->post('id');
		$profiling_id =  $this->input->post('profiling_id');

		$updateData = array(
			'is_delete' 	=> 1,
			'deleted_at'	=> date('Y-m-d H:i:s')
		);

		$deleteLicense = $this->license->editLicense($updateData,$license_id);
		$deleteLicenseAttachment = $this->license_attachment->editAttachment(array(
			'is_delete' => 1),null,$license_id);

		if($deleteLicense)
        {
          print json_encode(array(
                "status"     			=> "success",
                "deleteLicense" 	=> $deleteLicense,
                "msg" 		    		=> "Academic qualification deleted.",
                "redirect"		=> base_url('hr/Myprofile/index/'.$profiling_id)
            ));

        }
        else
        {
        	 print json_encode(array(
                "status" 	=> "failed",
                "msg" 		=> "failed",
                "redirect"		=> base_url('hr/Myprofile/index/'.$profiling_id)
            ));
        }
	}

	
}
?>