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

class Upload extends MY_Controller {
	var $secure = false;
	function __construct()
	{
		parent::__construct();
		date_default_timezone_set('Asia/Jakarta');
		$this->load->library('session');
		$this->load->model('attachment_model');
	}
	
	public function index()
	{
		$key = decode($this->input->get('key'));
		$attachment_description = decode($this->input->get('ad'));
		if(!$attachment_description)
		$attachment_description = 'Upload attachment for '.$key;
		$token = decode($this->input->get('t'));
		$ism = $this->input->get('ism')?1:0;

		$this->attachment_model->set_where(array('transNumRef'=>$key));

		$data = Array(
			'content' => 'upload/main',
			'key' => $key,
			'token' => $token,
			'attachment_description' => $attachment_description,
			'ism' => $ism
		);
		$this->load->view($data['content'],$data);
	}

	public function modal()
	{
		$key = decode($this->input->get('key'));
		$attachment_description = decode($this->input->get('ad'));
		if(!$attachment_description)
		$attachment_description = 'Upload attachment untuk dokumen '.$key;
		$token = decode($this->input->get('t'));
		$ism = $this->input->get('ism')?1:0;

		$this->attachment_model->set_where(array('transNumRef'=>$key));

		$data = Array(
			'content' => 'upload/modal',
			'key' => $key,
			'token' => $token,
			'attachment_description' => $attachment_description,
			'ism' => $ism
		);
		$this->load->view($data['content'],$data);
	}

	public function qr_scan()
	{
		$this->load->library('ciqrcode');

		// waktu link upload available
		$seconds_expire = 3600;

		$key = $this->input->get('key');

		$token = encode(date('Y-m-d h:i:s A', time()+$seconds_expire));

		$link_to_scan = base_url().'up?key='.$key.'&ism=0&t='.$token;

		$data = Array(
			'content' => 'upload/qr_scan',
			'link_to_scan' => $link_to_scan
		);

		$this->load->view($data['content'],$data);
	}

	public function list_attachment()
	{
		$key = $this->input->post('key');

		$this->attachment_model->set_where(array('transNumRef'=>$key,'attachmentType'=>1));
		$attachment_list = $this->attachment_model->get_list();
		$data = Array(
			'content' => 'upload/list',
			'key' => $key,
			'attachment_list' => $attachment_list,
		);
		$this->load->view($data['content'],$data);
	}

	public function upload_attachment()
	{
		$key = $this->input->post('key');
		$remark = $this->input->post('remark');

		if(!$remark)
		$this->error('Deskripsi belum di isi');
		
		$config['upload_path']="./".getAttachmentUploadPath();
		$config['allowed_types']='*';
		$config['encrypt_name'] = TRUE;
		$config['max_size'] = 7000;
		
		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload('userfile'))
		{   
			$error = $this->upload->display_errors();
			echo $error;
		}
		else
		{
			$data_upload_raw = $this->upload->data();
			$data_upload = array();
			$data_upload['idAttachment']	= 0;
			$data_upload['transNumRef']		= $key;
			$data_upload['remark']				= $remark;
			$data_upload['clientName']		= $data_upload_raw['client_name'];
			$data_upload['fileExt']				= $data_upload_raw['file_ext'];
			$data_upload['fileName']			= $data_upload_raw['file_name'];
			$data_upload['filePath']			= $data_upload_raw['file_path'];
			$data_upload['fileSize']			= $data_upload_raw['file_size'];
			$data_upload['fileType']			= $data_upload_raw['file_type'];
			$data_upload['fullPath']			= $data_upload_raw['full_path'];
			$data_upload['serverFilePath']= getAttachmentUploadPath();
			$data_upload['serverFullPath']= getAttachmentUploadPath().$data_upload_raw['file_name'];
			$data_upload['imageHeight']		= $data_upload_raw['image_height'];
			$data_upload['imageSizeStr']	= $data_upload_raw['image_size_str'];
			$data_upload['imageType']			= $data_upload_raw['image_type'];
			$data_upload['imageWidth']		= $data_upload_raw['image_width'];
			$data_upload['isImage']				= $data_upload_raw['is_image']?1:0;
			$data_upload['origName']			= $data_upload_raw['orig_name'];
			$data_upload['rawName']				= $data_upload_raw['raw_name'];
			$data_upload['uploadBy']			= $this->session->userdata('idOperator'); 
			$data_upload['attachmentType']		= 1; 

			// Compress Image
			// jika image width lbh besar dari width yang ditentukan maka di resize, jika ukuran width sudah kecil maka tidak usah di resize
			$new_width = 300;
			if($data_upload['imageWidth']>$new_width)
			{
				$new_height = ceil($data_upload['imageHeight'] * ($new_width/$data_upload['imageWidth']));
				$config_resize['image_library']='gd2';
				$config_resize['source_image']= getAttachmentUploadPath().$data_upload_raw['file_name'];
				$config_resize['create_thumb']= TRUE;
				$config_resize['maintain_ratio']= TRUE;
				$config_resize['quality']= '50%';
				$config_resize['width']= $new_width;
				$config_resize['height']= $new_height;
				$config_resize['new_image']= getAttachmentUploadPath().$data_upload_raw['file_name'];
				$this->load->library('image_lib', $config_resize);
				$this->image_lib->resize();
			}

			$this->attachment_model->set_clean_data(false);
			$this->attachment_model->saveTo($data_upload);
			$this->success('upload success');
		}
	}

	public function download_attachment($id='')
	{
		$attachment = $this->attachment_model->get(decode($id));

		header('Content-Type: '.$attachment['fileType'].'');
		header('Content-Disposition: inline; filename="'.$attachment['origName'].'"');
		// header('Content-Disposition: attachment; filename="'.$attachment['origName'].'"');

		readfile(base_url($attachment['serverFullPath']));
		exit;
	}

	public function download_attachment_zip($refnum)
	{
		$this->attachment_model->set_where(array('transNumRef'=>decode($refnum)));
		$attachment_list = $this->attachment_model->get_list();
		$zipname = decode($refnum).'.zip';
		$zip = new ZipArchive;
		$zip->open($zipname, ZipArchive::CREATE);
		foreach ($attachment_list->result_array() as $file) {
		  $zip->addFile($file['serverFullPath']);
		}
		$zip->close();
		header('Content-Type: application/zip');
		header('Content-disposition: attachment; filename='.$zipname);
		header('Content-Length: ' . filesize($zipname));
		header('Cache-Control: no-cache', TRUE);
		readfile($zipname);
	}

	public function remove_attachment($id)
	{
		$file_to_delete = $this->attachment_model->get(array('idAttachment'=>$id));
		$thumb_image = $file_to_delete['filePath'].$file_to_delete['rawName'].'_thumb'.$file_to_delete['fileExt'];
		if(!file_exists($file_to_delete['fullPath']))
			$this->error('file tidak ditemukan..!');
		if(!unlink($file_to_delete['fullPath']))
			$this->error('failed remove attachment');
		if(file_exists($thumb_image))
		unlink($thumb_image);
		$this->attachment_model->delete(array('idAttachment'=>$id));
		$this->success('Attachment removed');
	}
}