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

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

		if($this->logged_user = $this->session->userdata('user')){
            $this->login->checkModuleAccess(4);
            
            $this->load->model('hr/model_policy');

            $this->logged_module = $this->session->userdata('module_data');
		}else{
			redirect(base_url());
		}
    }
    
    function index()
    {
		$data['policies']   = $this->model_policy->getPolicy();
        $data['categories'] = $this->model_general->fetchAll('hr__policyprocedure_category', array(), array('is_delete' => 0));
        // $data['categories'] = $this->model_general->fetchAll('hr__policyprocedure_category', array(), array('parent_id' => 0, 'is_delete' => 0));
        // $data['sub_categories'] = $this->model_general->fetchAll('hr__policyprocedure_category', array(), array('parent_id !=' => 0, 'is_delete' => 0));

		$data['page_setup'] = $this->template->pageSetup('HR', '', 'Company Policies');
		$this->template->view('hr/policy/index', $data);
    }

    function setting()
    {
        $data['page_setup'] = $this->template->pageSetup('Policies & Procedures', '', 'Setting');
		$this->template->view('hr/policy/setting', $data);
    }
    
    // API
    function getPolicies()
    {
        $data = $this->input->post();

        if(isset($data['id']))
		{
            $policy = $this->model_policy->getPolicy(array('a.id' => $data['id']))[0];

            print json_encode(array(
				"status" => "Success",
				"policy" => $policy,
			));
        }
        else
        {
            print json_encode(array(
				"status" => "Error",
				"data"	 => "Data is missing."
			));
        }
    }
    
    function uploadPolicy()
	{
		if(isset($_FILES['policy'])){
            $file_data = $this->upload("document", "policy", 'hr/policy/');

            $data = $this->input->post();
			$data['file_name']     = $file_data['file_name'];
			$data['file_location'] = $file_data['file_location'];
			$data['created_by'] = $this->logged_user['id'];

			$id = $this->model_general->insert("hr__policy", $data);

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

	function updatePolicy()
	{
		$data = $this->input->post();

		if(isset($data['id']))
		{
			$id = $data['id'];
			unset($data['id']);
			
            if(isset($_FILES['policy'])){
                $file_data = $this->upload("document", "policy", 'hr/policy/');
    
                $data['file_name']     = $file_data['file_name'];
                $data['file_location'] = $file_data['file_location'];
            }

			$data['updated_by'] = $this->logged_user['id'];
			$data['updated_ts'] = date('Y-m-d H:i:s');

			$ok = $this->model_general->update('hr__policy', $data, array('id'=>$id));

			if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Policy updated successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "System failed to update Policy."
				));
			}
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "Data is missing."
			));
		}
	}

	function deletePolicy()
	{
		$data = $this->input->post();

		if(isset($data['id']))
		{
			$data['is_delete']  = 1;
			$data['deleted_by'] = $this->logged_user['id'];
			$data['deleted_ts'] = date('Y-m-d H:i:s');

			$ok = $this->model_general->update('hr__policy', $data, array('id'=>$data['id']));

			if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Policy deleted successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "Failed to delete Policy."
				));
			}
		}
		else
		{
			print json_encode(array(
				"status" => "Error",
				"msg"	 => "Data is missing."
			));
		}
    }
    
    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|xls|xlsx|pptx|jpg|jpeg|bmp|png';
			if($type == 'image') $file_types = '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;
	}
}