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

class MY_Controller extends CI_Controller 
{
	var $template_data = array();
	var $result = array();
	var $title = '';
	var $secure = TRUE;
	var $api 	= FALSE;
	
	 public function __construct()
	{
		parent::__construct();
		$this->load->database();
		if($this->secure == false){
			
		}else{
			if($this->api == true){
				if(!is_cli())
				$auth = $this->get_auth();
			}else{
				$this->load->library('session');
				$this->load->library('menu');
				$bc = $this->load->library('mybreadcrumb',null,'bc');
				$modules = $this->load->library('mymodules',null,'modules');
				if (!$this->is_logged_in())
				{
					if(get_accept_header() == 'application/json')
					$this->error('Session expired, please reload the page');
					redirect('/login');
					die;
				}
			}
		}
		// $sms = $this->load->library('sms_gateway',null,'sms'); 
	}
		
	function set($name, $value)
	{
		$this->template_data[$name] = $value;
	}

	function load($template = '', $view = '' , $view_data = array(), $return = FALSE)
	{               
		if (!isset($view_data['title']))
			$view_data['title'] = $this->title;
			
		$this->CI =& get_instance();
		$this->set('contents', $this->CI->load->view($view, $view_data, TRUE));			
		return $this->CI->load->view($template, $this->template_data, $return);
	}
	
	public function is_logged_in()
	{
		return is_logged_in();
	}
	
	function success($msg='',$success_code='200',$success_header='OK')
	{
		success($msg,$success_code,$success_header);
	}
	
	function error($err,$error_code='400',$error_header='error')
	{
		error($err,$error_code,$error_header);
	}
	
	function success_redirect($msg='',$uri='')
	{
		redirect(get_language().'/'.$uri);
	}
	
	function gen_paging($page_data=array())
	{
		// exit;
		$func_name = "pageLoad";
		if (isset($page_data['load_func_name']))
		{
			if ($page_data['load_func_name'])
				$func_name = $page_data['load_func_name'];
		}
		// if ($page_data['count_row']>0)
			// $count = ceil($page_data['count_row'] / $page_data['limit']) ;
		
		$limit = $page_data['limit'];
		$limit = $limit?$limit:1;
		$count = ceil($page_data['count_row'] / $limit) ;
		$last_row = $limit*$page_data['current'];
		if ($last_row > $page_data['count_row'])
			$last_row = $page_data['count_row'];
		$page_result = '<div class="row">
							<div class="col-6">
								<div class="dataTables_info" id="DataTables_Table_0_warning" role="status" aria-live="polite">Showing '.(($limit*($page_data['current']-1))+1).' to '.$last_row.' of '.$page_data['count_row'].' entries
								</div>
							</div>
							';
		$previous = $page_data['current'] - 1;
		$next = $page_data['current'] + 1;
		$page_result .= '<div class="col-6">
							<div class="dataTables_paginate paging_simple_numbers float-md-right" id="DataTables_Table_0_paginate">
								<ul class="pagination" style="margin-top: 0rem;margin-bottom: 0rem;">
									<li class="paginate_button page-item previous '.($page_data['current']==1?'disabled':'').'"  id="DataTables_Table_0_previous">
										<a  class="page-link" href="javascript:void(0)" '.($page_data['current']==1?'':'onclick="'.$func_name.'(1)"').'>
											<i class="ft-skip-back"></i>
										</a>
									</li>
									<li class="paginate_button page-item previous '.($page_data['current']==1?'disabled':'').'">
										<a  class="page-link" href="javascript:void(0)" '.($page_data['current']==1?'':'onclick="'.$func_name.'('.$previous.')"').'>
											<i class="ft-rewind"></i>
										</a>
									</li>';
		
		$paging_show = 3;
		$page_start = $page_data['current'] - $paging_show;
		$page_start = $page_start<1?1:$page_start;
		//$page_end	= $count;
		$page_end = $page_data['current'] + $paging_show;
		$page_end = $count > $page_end ? $page_end : $count;
		$page_end = $count > 1 ? $page_end : 1;
		
		//
		// if ($page_start > 1)
		// {
			// $page_result .= '<li class="active")><a href="javascript:void(0)" >...</a></li>';
		// }
		// before current
		for($i=$page_start; $i<=$page_end; $i++)
		{ 
			$page_result .= '<li class="paginate_button page-item '.($page_data['current']==$i?'active':'').'">'
							.'<a  class="page-link" href="javascript:void(0)" '.($page_data['current']==$i?'':'onclick="'.$func_name.'('.$i.')"').'>'.$i.'</a>'
							.'</li>';
		}
		// after current
		// if ($page_end < $count)
		// {
			// $page_result .= '<li class="active")><a href="javascript:void(0)" >...</a></li>';
		// }
		
		$page_result .= '<li class="paginate_button page-item next '.($page_data['current']==$page_end?'disabled':'').'">
							<a class="page-link" href="javascript:void(0)" '.($page_data['current']==$page_end?'':'onclick="'.$func_name.'('.$next.')"').'>
											<i class="ft-fast-forward"></i> </a>
						</li>';
		$page_result .= '<li class="paginate_button page-item next '.($page_data['current']==$page_end?'disabled':'').'">
							<a class="page-link" href="javascript:void(0)" '.($page_data['current']==$page_end?'':'onclick="'.$func_name.'('.$count.')"').'>
											<i class="ft-skip-forward"></i> </a>
						</li>
							</ul>
						</div>';
		$page_result .= '
					</div>
				</div>';
		return $page_result;
	}
	
	function reject()
	{
		$this->load->view('rejected');
	}
	
	/*
	 * untuk mencari no transaksi yang baru	
	 */
	function _get_tr_no($pref=null,$model=null,$date=true)
	{
		if (!$pref)
			$pref = '';
		else
			$pref .= '.';			
		
		if ($date)
			$pref .= date('ym').'.';
			
		$pref_ln = strlen($pref);
		
		$tr_no = '';
		$no_last = $model->get_last_no($pref);
		$no_next = 1;
		if ($no_last)
		{
			$no_next = substr($no_last,$pref_ln,5)+1;
		}

		$tr_no = $pref.sprintf('%05s', $no_next);
		return $tr_no;
	}
	
	function gen_xml($data,$model,$schema='')
	{
		$data_start="<![CDATA["; 
		$data_end="]]>";
		$cr=chr(13).chr(10);
		$xmldump="";
		$xmldump.='<?xml version = "1.0" encoding="Windows-1252" standalone="yes"?>';
		$xmldump.=$cr."<VFPData>";
		$xmldump.=$model->gen_xml_structure($schema);
		
		foreach($data->result_array() as $row)
		{
			$xmldump = $xmldump."<crsoheader>";
			foreach($row as $field=>$value)
			{
				$xmldump = $xmldump."<".$field.">".str_replace('&','_amp',$value)."</".$field.">".chr(13);
			}
			$xmldump = $xmldump.$cr."</crsoheader>".chr(13);
				
		}
		
		$xmldump = $xmldump.$cr."</VFPData>";
		
		return $xmldump;
	}

	function key_validation($storeCode,$key,$modulName = 'bePOS')
	{
		$this->load->model('master/store_info_model');
		$this->load->model('master/store_log_access');
		$storeCode 	 = strtoupper($storeCode);
		$key		 = strtoupper($key);
		if(!$storeCode)
		{
			echo 'FAILED#Store Empty';
			return false;
			exit;
		}
		// validasi key untuk toko tersebut
		$storeInfo = $this->store_info_model->get($storeCode);
		$serverKey = strtoupper($storeInfo['BezSyncKey']);
		// validasi master toko
		if (!$storeInfo['StoreCode'])
		{
			echo 'FAILED#Store not Available';
			return false;
			exit;
		}
		// validasi key
		
		if ($serverKey != $key)
		{
			echo 'FAILED#Wrong Key';
			return false;
			exit;
		}	
		// create log access
		$schemaName = 'terminal';
		$tableLogName = 'trUpdate'.date('Ym');
		
		$this->store_log_access->set_table($tableLogName);
		
		$dataLog = array();
		
		$dataLog['StoreCode'] = $storeCode;
		$dataLog['ModulName'] = $modulName;
		$dataLog['LastUpdate'] = date('Y-m-d H:i:s');
		
		// di komen dulu insert log nya
		/*
		$new = $this->db->insert($schemaName.'.'.$tableLogName, $dataLog);	
		if (!$new)
		{
			echo 'FAILED#Failed create log';
			return false;
		}*/
		// done
		return true;
	}

	function gen_qrcode($code ='')
	{
		$this->load->library('ciqrcode');
		header("Content-Type: image/png");
		$params['data'] = $code;
		$this->ciqrcode->generate($params);
	}
	
	function get_auth()
	{
		$result = array();
		
		$result['statusCode'] 	= 0;
		// $result['status'] 	= 'FAILED';
		$result['message'] 	= 'NOT AUTHORIZED';
		$result['msgid'] 	= '';
		// print_r($_SERVER);die;
		$res = array();
		$res['ok'] = false;
		$res['result'] = $result;
		$user = '';
		$pass = '';
		$enable_auth_log = get_myconf('api_log_enabled');
		if(isset($_SERVER['PHP_AUTH_USER']))
		{
			$user = $_SERVER['PHP_AUTH_USER'];
		}
		if(isset($_SERVER['PHP_AUTH_PW']))
		{
			$pass = $_SERVER['PHP_AUTH_PW'];
		}
		$this->CI =& get_instance();
		$get_exp		= date('Y-m-d H:i:s');
		$auth_from_db	= get_myconf('auth_from_db');
		if($auth_from_db)
		{
			$this->CI->load->database();
			$this->CI->db->from('ws.auth');
			$this->CI->db->where('login', $user);		
			$this->CI->db->where('pass',$pass);
			$this->CI->db->where('enable',1);
			$user_auth = $this->CI->db->get();
			
			$auth_no_validate 	= ($user_auth->num_rows()==0);
			if(!$auth_no_validate)
			{
				$user_auth			= $user_auth->row_array();
				$get_exp			= $user_auth['validUntil'];
			}
		}else{
			$auth_no_validate	= ( get_myconf('api_user') != $user ) || ( get_myconf('api_pass') != $pass );
			$get_exp			= get_myconf('api_exp_date');
		}
		if( $auth_no_validate )
		{
			header('WWW-Authenticate: Basic realm="WS"');
			header('Content-type: application/json');
			header('HTTP/1.0 401 Unauthorized');
			echo json_encode($result);
			exit;
		}
		if($enable_auth_log)
		{
			// $user_auth= $user_auth->row_array();
			
			$date_expiry = new DateTime( $get_exp );
			$date_now = new DateTime(date('Y-m-d H:i:s'));
			
			if($date_expiry < $date_now)
			{
				$result['message'] 	= 'Expired Authorization';
				$this->error($result['message']);
			}
			$request = $_REQUEST;
			$uri_segments = $this->uri->uri_string();			
			$class 	= $this->router->class;
			$method = $this->router->method;
			$data_log['method'] =	$this->input->method();
			$data_log['log_type'] = 'ws '.$uri_segments;
			$data_log['action_time'] = date('Y-m-d H:i:s');
			$data_log['ip_comp'] = $this->CI->input->ip_address();
			$data_log['user_id'] = $user;
			$data_log['table_name'] = '';
			$data_log['data'] = array_to_string($request);
			$log = $this->CI->db->insert('ws.authLog', $data_log);
		}

		return $user;
	}
	
	
	function remove_empty_array($array)
	{
		
		foreach ($array as $key =>$value)
		{
			if($value=='')
			{
				unset($array[$key]);
			}
		}
		
		return $array;
	}
	
	function set_title($title)
	{
		$this->title = $title;
	}
	
	function get_title()
	{
		return $this->title;
	}
	
	function validate_role($id_menu)
	{
		$id_operator = $this->session->userdata('idMsOperator');
		
		$this->load->model('tools/user_priv_model');
		
		$get_priv = $this->user_priv_model->get(array('fidMsOperator'=>$id_operator,'fidAppMenu'=>$id_menu));
		
		if($get_priv['idPrivilege'])
		{
			return true;
		}else{
			redirect('/user/no_access');
			die;
		}
	}

	function load_pdf($content, $data, $config=array())
	{
		// Load pdf library
		$this->load->library('htmltopdf');
		/**
		 * output type 1 = stream, 0 = json encoded
		 *
		 * @var int output_type
		 */
		$output_type = isset($config['output_type'])?$config['output_type']:0;
		/**
		 * stream output 1 = download, 0 = preview
		 *
		 * @var int stream_output
		 */
		$stream_output = isset($config['stream_output'])?$config['stream_output']:0;
		/**
		 * custom paper size, default A4 if custom using array ex:array(0,0,204,650)
		 *
		 * @var varchar paper_size
		 */
		$paper_size = isset($config['paper_size'])?$config['paper_size']:'A4';
		/**
		 * custom paper orientation portrait|landscape (only enabled if not custom size)
		 *
		 * @var varchar paper_orientation
		 */
		$paper_orientation = isset($config['paper_orientation'])?$config['paper_orientation']:'portrait';
		/**
		 * custom font type courier|helvetica|serif
		 *
		 * @var varchar font
		 */
		$font = isset($config['font'])?$config['font']:'serif';
		/**
		 * custom document name
		 *
		 * @var varchar name
		 */
		$name = isset($config['name'])?$config['name']:'dokumen';
		/**
		 * custom DPI
		 *
		 * @var varchar name
		 */
		$dpi = isset($config['dpi'])?$config['dpi']:null;

		// add external css library
		$html = '';
		$html .= '<link href="' . base_url() . 'assets/css/print-doc-pdf.css" rel="stylesheet">';
		$html .= $this->load->view($content, $data, TRUE);
		// set options
		
		$options = $this->dompdf->getOptions();
		$options->setDefaultFont($font);

		// load data to pdf
		$this->dompdf->loadHtml($html);
		// setup size
		if(($paper_size) && (is_array($paper_size)))
		$this->dompdf->set_paper($paper_size); else
		$this->dompdf->setPaper($paper_size, $paper_orientation);
		// setup dpi
		if($dpi)
		$this->dompdf->set_option('dpi', $dpi);
		// Render the HTML as PDF
		$this->dompdf->render();
		// output as encoded or stream
		if($output_type==0)
		{
			// encoded
			$output = $this->dompdf->output();
			$return = base64_encode($output);
			echo json_encode($return);
		}else{
			// stream
			// Output  PDF (1 = download and 0 = preview)
			return $this->dompdf->stream($name, array("Attachment" => $stream_output));
		}
	}
} 
