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

class Payslip extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		$this->load->model('hr/payslip_model');
		$this->load->model('admin/model_general');
		$this->load->model('Admin/model_user');
		$this->load->model('Admin/model_company');
		$this->load->helper('excel_helper');
		$this->lang->load('num_to_word');
		$this->load->helper('num_to_word');
		$this->load->helper('stringformat_helper');
		$this->load->model('analysis/model_analysis','model_analysis'); //Fakru Add for analysis purpose

		$this->logged_user = $this->session->userdata('user');

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

		/*
		//open for certain people only
		if($this->logged_user['id'] == 144 || $this->logged_user['id'] == 240 || $this->logged_user['id'] == 137 || $this->logged_user['id'] == 265)
		{
			// debug('sepatutnya boleh akses');
		}else{
			die(debug($this->logged_user['name'].', your are not allowed to access payslip module for the moment'));
		}
		*/
		
	}

	public function index()
	{
		
	}

	
	
	public function view($id = null)
	{	
		$role = $_SESSION['module_data']['role'];
		$user_id = $_SESSION['log_data']['user_id'];

		$users = $this->model_user->getUsers($user_id);
		
		if($id != null && $role != 'user'){
			$data['table'] = $this->payslip_model->getPayslipDetail($id);
			$data['allowance'] = $this->payslip_model->getAllowance($id);
			$data['deduction'] = $this->payslip_model->getDeduction($id);
			$data['deductionEPF'] = $this->payslip_model->getDeductionEPF($id); 
			$data['deductionSOCSO'] = $this->payslip_model->getDeductionSOCSO($id);
			$data['deductionSIP'] = $this->payslip_model->getDeductionSIP($id);
			$data['employer'] = $this->payslip_model->getEmployerContribution($id);
			$data['basic_pay'] = 0;
			
			$data['netWord'] = num_to_word($data['table'][0]->netPay,$this->lang->line('dictionary'),'Ringgit Malaysia');
			
		}else{
			$data['table'] = $this->payslip_model->getPayslipDetail($id,$users['ic_no']);
			$data['allowance'] = $this->payslip_model->getAllowance($id);
			$data['deduction'] = $this->payslip_model->getDeduction($id);
			$data['deductionEPF'] = $this->payslip_model->getDeductionEPF($id);
			$data['deductionSOCSO'] = $this->payslip_model->getDeductionSOCSO($id);
			$data['deductionSIP'] = $this->payslip_model->getDeductionSIP($id);
			$data['employer'] = $this->payslip_model->getEmployerContribution($id);
			$data['basic_pay'] = 0;
			if($data['table']){
				$data['netWord'] = num_to_word($data['table'][0]->netPay,$this->lang->line('dictionary'),'Ringgit Malaysia');
			}
		}
		
		if (($data['table'][0]->year==2021 && $data['table'][0]->month==12) || ($data['table'][0]->year==2022 && $data['table'][0]->month==1)) {
			/*
			1 - SALIHIN Consulting Group Sdn Bhd
			2 - SALIHIN
			3 - Aljafree Salihin Kuzaimi 
			4 - SALIHIN Tax Advisory Sdn Bhd
			5 - SALIHIN Shariah Advisory Sdn Bhd
			7 - MYSA Business Management Sdn Bhd (formerly known as SALIHIN Business Management Sdn Bhd)
			8 - SALIHIN Training and Consultancy Sdn Bhd
			13 - SALIHIN IT Curation Sdn Bhd (formerly known as SALIHIN GST Services Sdn Bhd)
			14 - MYSA Corporate Services Sdn. Bhd.
			*/
			
			$company_subsidi = array(1,2,3,4,5,7,8,13,14);
			$payslipData =  $this->payslip_model->getPayslipData($id);
			if ($payslipData!=null && in_array($payslipData[0]->companyID, $company_subsidi)) {
				$data['extraInfo']=$data['table'][0]->company_name.' merupakan penerima bantuan subsidi upah daripada kerajaan melalui Program Subsidi Upah (PSU)';
			}
		}
		
		$header = array();
		$header['title'] = 'CUSTOMER LIST REPORT';

		// debug($data['deductionEPFSOCSOSIP']);
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/printList2.php',$data);
		$this->load->view('hr/report/footer.php');
	}

	public function mypayslip(){
		
		$userid = $_SESSION['log_data']['user_id'];
		$userDetail = $this->model_user->getUsers($userid);
		$empic = $userDetail['ic_no'];
		$empic = strtoupper(rmvSpecialCharacter($empic));
		$userpicture = $this->model_user->getPictures($userid);

		$data = array(
			'page_setup' 	=> $this->template->pageSetup('HR', 'Payslip', 'Pay Slip'),
			'payslips' 		=> $this->payslip_model->getEmployeePayslips($empic),
			'user_name' 	=> $_SESSION['user']['name'],
			'department' 	=> $userDetail['department_name'],
		);
		if($userpicture) $data['picture'] = $userpicture[0]['file_location'].$userpicture[0]['file_name'];
		$this->model_analysis->add_access($userid,5); //Fakru Add for analysis purpose
		$this->template->view('hr/Payroll/my_pay_slip.php',$data);
	}
	
	public function viewuploadpayslip($id = null){
		if($this->isRoleUser()){
			redirect(base_url('/hr/payslip/mypayslip'));
		}

		$data = array(
			'page_setup' 	=> $this->template->pageSetup('HR', 'Payslip','Pay Slip'),
			'companies'		=> $this->payslip_model->company_all(),
			'payslip_id'	=> $id
		);
		

		if ($id != null) {
			$data['table'] = $this->payslip_model->getPayslip($id);
			// die(debug($data));
		}

		$this->template->view('hr/Payroll/upload_pay_slip.php',$data);
		
	}

	public function ajxUploadPayslip()
	{
		if($this->isRoleUser()){
			redirect(base_url('/hr/payslip/mypayslip'));
		}
		$this->load->helper('file');
		$config['upload_path'] = './assets/uploads/hr/payroll';
		$config['allowed_types'] = 'xls|xlsx';
		$this->load->library('upload',$config);

		$data['status'] = 'success';
		$data['status_code'] = 200;
		$data['salaryWage'] = $this->input->post('salaryWage');
		$data['salaryWage'] = explode('/', $data['salaryWage']);

		$data['company'] = $this->input->post('company');
		$data['companyCode'] = $this->input->post('companycode');
		
		if(!$this->upload->do_upload('payslip')){
			$data['status_code'] = 500;
			$data['status'] = 'Internal Server Error';
			$data['error'] = $this->upload->display_errors(); 

			$this->load->helper('file');
			$log_payslip = read_file(APPPATH.'storage/log/payslip_upload_error'.date('Y-m-d').'.php');
			$log_payslip .= serialize($data['error']).PHP_EOL;
			write_file(APPPATH.'storage/log/payslip_upload_error'.date('Y-m-d').'.php',$log_payslip);

		}else{
			$data['payslip'] = $this->upload->data();
		}

		if($data['content'] = excelToArray($config['upload_path'],$data['payslip']['file_name'],0,1)){
			if(unlink($config['upload_path'].'/'.$data['payslip']['file_name'])){
				$data['isDelete'] = true;
			}else{
				$data['isDelete'] = false;
			}
		}

		
		// log_message('error', json_encode($data['content']));
		
		
		$employeeId = array();
		$employeeIc = array();
		foreach ($data['content'][0][1] as $row	) {
			array_push($employeeId, $row['A']);
			array_push($employeeIc,$row['B']);
			// $msg .= $employeeIc;
		}
		
		log_message('error', json_encode($employeeIc));

		// $data['duplicateStaff'] = $this->payslip_model->getUploadPayslipByEmployeeId($employeeId,$data);
		$data['duplicateStaff'] = $this->payslip_model->getPayslipsByIC($employeeIc,$data);
		$data['unknownStaff']	= $this->payslip_model->getUnknownUsers($employeeIc);

		// die(debug($data));
		// log_message('error',json_encode($data['unknownStaff']));
		echo json_encode($data);
		return true;
	}

	public function ajxApprovePayslip()
	{
		if($this->isRoleUser()){
			redirect(base_url('/hr/payslip/mypayslip'));
		}
		$data = array();
		$data['status'] = 'success';
		$data['status_code'] = 200;
		
		$data['salaryWage'] = explode('/', $this->input->post('salaryWage'));
		$data['companyId'] = $this->input->post('companyId');
		$data['companyCode'] = $this->input->post('companyCode');
		$tabledata	= $this->input->post('tableData');
		$data['tableData']	= json_decode($tabledata);

		// debug($data);
		// die();
		
		if(sizeof($data['salaryWage']) > 1 && !empty($data['companyId']) && !empty($data['tableData'])){
			$data['companyData'] = $this->model_company->getBusinesses(null,intval($data['companyId']));
			
			$status = $this->payslip_model->saveBulkPayslip($data);
			$data['saveStatus'] = $status;

		}else{
			$error = ' ';
			$data['status'] = $error;

			if(sizeof($data['salaryWage']) <= 1){
				$error = 'Salary / Wage Month is empty. ';
				$data['status'] .=  $error;
				$data['status_code'] = 412;
			}

			if($data['companyId'] == '' || $data['companyId'] == null || $data['companyId'] == '-1'){
				$error = 'Company have not been Choosen. ';
				$data['status'] .=  $error;
				$data['status_code'] = 412;
			}

			if($data['companyCode'] == null || $data['companyCode'] == ''){
				$error = 'Please enter Company No. ';
				$data['status'] .= $error;
				$data['status_code'] = 412;
			}
		}		
		echo json_encode($data);
		return true;
	}

	
	public	function payslip_upload_list(){
		$this->session->unset_userdata('search_company_id');
		$this->session->unset_userdata('search_company_name');
		$this->session->unset_userdata('salary_wage');
		if($this->isRoleUser()){
			redirect(base_url('/hr/payslip/mypayslip'));
		}
		$data = array(
			'page_setup' 	=> $this->template->pageSetup('HR', 'Payslip','Pay Slip'),
			'table'		 	=> $this->payslip_model->getUploadedPayslip(),
			'companies'		=> $this->payslip_model->company_all(),
			'yearPayslips'	=> $this->payslip_model->countYearPayslip(),
			'monthPayslips' => $this->payslip_model->countMonthPayslip(),
			'yearNet'		=> $this->payslip_model->yearNetPay(),
			'monthNet'		=> $this->payslip_model->monthNetPay()
		);
		
		$this->template->view('hr/Payroll/pay_slip_upload_list.php',$data);
	}

	public function print_payslip_upload_list($id = null){
		if($this->isRoleUser()){
			redirect(base_url('/hr/payslip/mypayslip'));
		}

		$header = array();

		if ($id != null)$data['body'] = $this->payslip_model->getPayslip($id);
		// die(debug($data));
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/print_uploadPaySlip.php',$data);
		$this->load->view('hr/report/footer.php');

	}

	public function view3()
	{	
		$companyId = $this->session->search_company_id;
		$month = $this->session->month;
		$year = $this->session->year;

		$header = array();
		if($companyId != null || $month != null || $year != null){
			if (empty($month)) {
				$month = -1;
				$data['month'] = '';
			}else{
				$data['month'] = strtoupper(date('F',mktime(0,0,0,intval($month),10)));
			}

			if (empty($year)) {
				$year = -1;
				$data['year'] = '';
			}else{
				$data['year'] = $year;
			}

			if (empty($companyId)) {
				$data['companyName'] = 'All Company';	
			}else{
				$company = $this->model_company->getCompanies($companyId);
				$data['companyName'] = '';
			}

			$data['body'] = $this->payslip_model->getUploadedPayslip($companyId,intval($month),intval($year));
		}else{
			$data['companyName'] = 'All Company';
			$data['month'] = strtoupper(date('F'));
			$data['year'] = date('Y');
			$data['body'] = $this->payslip_model->getUploadedPayslip();
		}
		
		// die(debug($data));
		$this->load->view('hr/report/header.php', $header);
		$this->load->view('hr/report/print_paySlipUploadList.php',$data);
		$this->load->view('hr/report/footer.php');
	}

	public function ajxRemovePayslip()
	{
		if($this->isRoleUser()){
			redirect(base_url('/hr/payslip/mypayslip'));
		}
		$data = array(
			'status' 		=> 'success',
			'status_code' 	=> 200,
			'payslipid'		=>	$this->input->post('payslipid')
		);

		if(!$this->payslip_model->isDelPSlipUpload($data['payslipid'])){
			$data['status'] = 'failed';
			$data['status_code'] = 412;
			$data['error_message'] = 'Unable to remove payslip';
		}

		echo json_encode($data);
		return true;
	}

	public function ajxFilterPayslips()
	{
		$companyId 		= $this->input->post('companyId');
		$month 			= $this->input->post('month');
		$year 			= $this->input->post('year');
		$salaryWage		= array($month,$year);

		// $companyName = 
		//write session
		$sess = array(
			'search_company_id' 	=> $companyId,
			'search_company_name'	=>	'',
			'month'					=> $month,
			'year'					=> $year,
		);

		$this->session->set_userdata($sess);
		// die(debug($_SESSION));

		if (empty($month)) {
			$month = -1;
		}

		if (empty($year)) {
			$year = -1;
		}
		
		$data = array(
			'status'		=> 'success',
			'status_code'	=> 200,
			'companyId'		=> $companyId,
			'salary wage'	=> $salaryWage,
			'table'			=>	$this->payslip_model->getUploadedPayslip($companyId,$month,$year)
		);
		echo json_encode($data);
		return true;
	}

	public function uploadpayslip()
	{
		$this->load->view('hr/report/header.php');
		$this->load->view('hr/report/payslip.php');
		$this->load->view('hr/report/footer.php');
	}

	private function isRoleUser()
	{
		//only admin can open and do this function
		if($_SESSION['module_data']['role'] == 'admin'){
			return false;
		}
		return true; //moderator and user
	}

}