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

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

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

            $this->logged_module = $this->session->userdata('module_data');
		}else{
			redirect(base_url());
		}
	}

	function index()
	{
        $data['forms']      = $this->model_form->getForms();
        $data['categories'] = $this->model_general->fetchAll('hr__form_category', array(), array('is_delete' => 0));
        
        $data['branches'] 	 = $this->model_company->getBranches();
		$data['departments'] = $this->model_company->getDepartments();

		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Forms');
		$this->template->view('hr/form/index', $data);
    }

    function setting()
    {
        $data['forms']      = $this->model_form->getForms();
        $data['categories'] = $this->model_general->fetchAll('hr__form_category', array(), array('is_delete' => 0));
        
        $data['branches'] 	 = $this->model_company->getBranches();
		$data['departments'] = $this->model_company->getDepartments();

		$data['page_setup'] = $this->template->pageSetup('HR', 'home', 'Forms Setting');
		$this->template->view('hr/form/setting', $data);
    }
    
    // API
    function getForms()
    {
        $data = $this->input->post();

        if(isset($data['id']))
		{
            $form = $this->model_form->getForms(array('a.id' => $data['id']))[0];

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

            $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__form", $data);

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

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

		if(isset($data['id']))
		{
			$id = $data['id'];
			unset($data['id']);

            if(isset($_FILES['form'])){
                $file_data = $this->upload("document", "form", 'hr/Form/form/');
    
                $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__form', $data, array('id'=>$id));

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

	function deleteForm()
	{
		$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__form', $data, array('id'=>$data['id']));

			if($ok)
			{
				print json_encode(array(
					"status" => "Success",
					"msg"	 => "Form deleted successfully."
				));
			}
			else
			{
				print json_encode(array(
					"status" => "Error",
					"msg"	 => "Failed to delete Form."
				));
			}
		}
		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;
	}
}