<?php

function checkExists( $value ){
	if ( !empty($value) && isset($value) ){
		return $value ;
	}
	return '' ;
}

function escapeString( $value ){
	return stripslashes( htmlentities( trim($value), ENT_QUOTES, 'UTF-8') ) ;
}

function dataFilter( $value ){
	$value = str_replace( 'font-family', 'unknonwn', $value ) ;
	return stripslashes( html_entity_decode( trim($value), ENT_QUOTES, 'UTF-8') ) ;
}

function dataFilterDash( $value ){
	$value = dataFilter( $value ) ;
	$value = ($value != '' ? $value : '-') ;
	return $value ;
}

function dataFilterImage($link, $path, $value){
	$value = dataFilter( $value ) ;
	$value = $link.($value != '' ? $path.$value : 'images/NoProduct.jpg') ;
	return $value ;
}

function stringCheck( $string ){
	$boolean = false ;
	if( isset( $string ) > 0 && !empty( $string ) && $string != '' ){
		$boolean = true ;	
	}
	return $boolean ;
}

function dateFilter( $type, $field, $date_from, $date_to, $year, $month, $day_from, $day_to ){
	global $mysqli ;

	$search = '' ;
	$array_td = array() ;

	if( stringCheck( $type ) ){
		switch( $type ){
			case 'normally' :
				if( stringCheck( $date_from ) && stringCheck( $date_to ) ){
					$search .= " AND ".$field." BETWEEN '".$date_from."' AND '".date( 'Y-m-d', strtotime( $date_to ) +86400 )."'" ;
				}else{
					$search .= " AND ".$field." BETWEEN '".date( 'Y-m-01' )."' AND '".date( 'Y-m-d', strtotime( TODAYDATE ) +86400 )."'" ;
				}
			break ;
			case 'yearly' : 
				$start_loop = STARTYEAR ;
				$end_loop = THISYEAR ;
			break ;
			case 'monthly' : 
				if( stringCheck( $year ) ){
					$start_loop = 1 ;
					$end_loop = 12 ;

					$search = " AND ".$field." LIKE '".$year."%'" ; 
				}
			break ;
			case 'daily' :
				if( stringCheck( $year ) && stringCheck( $month ) ){
					if( stringCheck( $day_from ) || stringCheck( $day_to ) ){
						$start_loop = $day_from ;
						$end_loop = $day_to ;

						$search .= " AND ".$field." BETWEEN '".$year."-".$month."-".$day_from."' AND '".date( 'Y-m-d', strtotime( $year."-".$month."-".$day_to ) +86400 )."'" ;
					}else{
						$start_loop = 1 ;
						$end_loop = 31 ;

						$search .= " AND ".$field." LIKE '%".$year."-".$month."%'" ;
					}
				}
			break ;
		}

		if( stringCheck( $start_loop ) && stringCheck( $end_loop ) ){
			for( $a = $start_loop ; $a <= $end_loop ; $a++ ){
				$reset_a = strPad( 2, $a ) ;
				switch( $type ){
					case 'yearly' : 
						$array_td[] = $reset_a ;
					break ;
					case 'monthly' : 
						$array_td[] = $reset_a ;
					break ;
					case 'daily' :
						if( $reset_a >= date( '01', strtotime( $year.'-'.$month ) ) && $reset_a <= date( 't', strtotime( $year.'-'.$month ) ) ){
							$array_td[] = $year.'-'.$month.'-'.$reset_a ;
						}
					break ;
				}
			}
		}
	}

	$array['array_date'] = $array_td ;
	$array['search'] = $search ;
	
	return $array ;					
}


function resetRequest( $array ){
	if ( arrayCheck( $array ) ){
		foreach ( $array as $key => $value ){
			if ( arrayCheck( $value ) ){
				$array[$key] = resetRequest( $value ) ;
			}else{
				$array[$key] = escapeString( $value ) ;
			}
		}
	}
	return $array ;
}

function getLimit( $current ){
	return  ( ( $current - 1 ) * LIMIT ) . ',' . LIMIT ;
}

// upload image
function uploadImage($path, $file_name, $source){
	$result   = false ;

	$split    = explode(',', substr($source, 5), 2) ;
	$mime     = trim( $split[0] ) ;
	$img_data = trim( $split[1] ) ;
	$mime_split_without_base64 = explode(';', $mime, 2) ;
	$mime_split = explode('/', $mime_split_without_base64[0], 2) ;

	if ( count($mime_split) == 2 ) {
		$extension     = $mime_split[1] ;
		$extension     = ( $extension == 'jpeg' ? 'jpg' : $extension ) ;
		$new_extension = '' ;

		switch ( $extension ){
			case "jpeg" :
			case "jpg" :
				$new_extension = 'jpg' ;
			break ;
			case "png" :
				$new_extension = 'png' ;
			break ;
			case "gif" :
				$new_extension = 'gif' ;
			break ;
			case "msword" :
				$new_extension = 'docx' ;
			break ;
			case "pdf" :
				$new_extension = 'pdf' ;
			break ;
			case "vnd.ms-excel" :
				$new_extension = 'xlsx' ;
			break ;
		}

		if ( $new_extension != '' ){
			$decoded   = base64_decode($img_data) ;
			$file_name = $file_name . '-' . time() . '-' . rand(000000, 999999) . '.' . $new_extension ;
			$file_type = $new_extension ;

			$s         = $_SERVER["DOCUMENT_ROOT"].'/uploads/'.$path.'/'.$file_name ;
			$b         = $_SERVER["DOCUMENT_ROOT"].'/uploads/'.$path.'/b/'.$file_name ;

			$is_upload = false ;
			switch ( $new_extension ){
				case "jpeg" :
				case "jpg"  :
				case "png"  :
				case "gif"  :
					if( file_put_contents( $s, $decoded ) && file_put_contents( $b, $decoded ) ) {
						$is_upload = true ;
					}
				break ;
				default :
					if( file_put_contents( $s, $decoded ) ) {
						$is_upload = true ;
					}
			}

			if( $is_upload ) {
				return [
					'status'  => '200',
					'message' => 'Success',
					'data'    => [
						'file_name' => $file_name,
						'file_type' => $file_type
					]
				] ;
			}
		}
	}
	return [
		'status'  => '306',
		'message' => 'Failed',
		'data'    => []
	] ;
}




function convertMinutes($time){
    $time = explode(':', $time);
    return ($time[0]*60) + ($time[1]) + ($time[2]/60) ;
}

function convertToTimes($minutes){
    $hours = strPad( 2, floor( $minutes / 60 ) ) ;
	$min   = strPad( 2, floor( $minutes - ( $hours * 60 ) ) ) ;

	return $hours.":".$min.":00" ;
}


// prevent new line, convert \n or enter to br
function escapeNewLine($value){
	$value = trim( preg_replace( '/(\r\n)|\n|\r/', '<br />', $value ) ); 
	return trim( preg_replace('/\s+/', ' ', $value) ) ;
}

// convert br to \n or enter
function brToNewLine($value){
	$breaks = array("<br />", "<br>", "<br/>") ;
	return str_ireplace($breaks, "\r\n", $value) ;  
}

// check spam email
function spamcheck($field){
	$field=filter_var($field, FILTER_SANITIZE_EMAIL);
	if(filter_var($field, FILTER_VALIDATE_EMAIL)){
		return TRUE;
	}
	else{
		return FALSE;
	}
}

// remove last comma
function removeLastComma($value, $type = ','){
	$value = rtrim(trimData($value), $type) ;
	return $value ;
}

// remove last 3 string
function subStrChar($value, $start, $end){
	return substr(trimData($value), $start, $end) ;	
}

// entity decode
function entityDecode($value){
	$value = html_entity_decode($value) ;
	return $value ;
}

// trim data
function trimData($value){
	$value = trim($value) ;
	return $value ;
}

function explodeToArray( $string ){
	$array          = [] ;
	if ( $string   != '' ){
		$new_string = explode(',', $string) ;
		foreach ( $new_string as $k => $v ){
			if ( $v != '' ){
				$array[] = dataFilter( $v ) ;
			}
		}
	}

	return $array ;
}

// self custom array
function customFilterArray($value){
	
	$result = false ;
	
	if (dataFilter($value) != ''){
		$value = str_replace('<filter-', '', $value) ;
		$value = removeLastComma($value, '>') ;
		$value = explode('>', $value) ;
		
		if (arrayCheck($value)){
			$result = true ;
		}
	}
	
	$array['result'] = $result ;
	$array['content'] = $value ;
	return $array ;
}

// insert database filter string
function resetString($value){
	$value = htmlspecialchars($value, ENT_QUOTES) ;	
	return $value ;
}

// check array is it true
function arrayCheck( $array ){
	if ( $array != null ){
		if ( is_array($array) ){
			if ( count($array) > 0 ){
				return true ;
			}
		}
	}
	return false ;
}

// check check value exsits
function checkValueExists($value){
	$result = false ;
	
	if (isset($value) && !empty($value)){
		$result = true ;	
	}
	
	return $result ;
}

// check if value exists
function checkArrayValueExists($array, $key, $val) {
	if (arrayCheck($array)){
	    foreach ($array as $item){
    	    if (isset($item[$key]) && $item[$key] == $val){
        	    return true;
			}
		}
	}
    return false;
}

// select box for loop
function selectForLoopNumber($name, $selected, $start, $end, $type, $required, $run_out){

	$select = '
	<select name="'.$name.'" class="form-control" '.$required.'>
		<option value="">Please select</option>' ;
		
		for ($a = $start; ($type == 'positive' ? $a <= $end : $a >= $end); ($type == 'positive' ? ($a += $run_out) : ($a -= $run_out) )){
			$select .= '
			<option value="'.$a.'" '.($a == $selected && $selected ? 'selected' : '').'>'.$a.'</option>' ;
		}
		
	$select .= '
	</select>' ;
	
	return $select ;
	
}

// trash page
function trashPage($page, $mysqli, $query, $trash){
	
	$multiple_trash = array() ;
	$multiple_trash = $trash ;
	$boolean = true ;
	
	if (arrayCheck($multiple_trash)){
		foreach($multiple_trash as $key => $value){

			// trash query
			if ($value == '1' && $mysqli->query($query . $key)){
				$boolean = true ;
			}else{
				$boolean = false ;
			}
			
		}
	}else{
		$boolean = false ;	
	}
	
	return $boolean ;
}

// duplicate or clone new order
function duplicateMySQLRecord ($action, $type, $table, $array_field, $id, $search_query) {
	global $mysqli, $prefixQuotation, $prefixQuotationJob ;

	$new_id = '' ;
	$prefix_table = '' ;
	$prefix_data = '' ;
	$prefix_level = 'sub' ;
	
	$id = dataFilter($id) ;
	$id_field = $array_field['id'] ;
	$related_type_field = $array_field['related_type'] ;
	$related_id_field = $array_field['related_id'] ;
	$related_action_field = $array_field['related_action'] ;
	$version_field = $array_field['version'] ;
	$status_field = $array_field['status'] ;
	$date_filed = $array_field['date'] ;
	$modified_filed = $array_field['modified'] ;
	$date_start_filed = $array_field['date_start'] ;
	
    // load the original record into an array
    $mysqli_query = $mysqli->query("SELECT * FROM ".$table."
									WHERE ".$id_field." = '".$id."' ".$search_query." LIMIT 1") ;
	if ($mysqli_query->num_rows > 0){
		
		$row_record = $mysqli_query->fetch_array(MYSQLI_ASSOC) ;
		$main_related_id = $row_record[$related_id_field] ;
		
		// total page exists
		if ( $action == 'clone' ){
			$mysqli_version = $mysqli->query("SELECT * FROM ".$table."
											  WHERE ".$related_id_field." = '".$main_related_id."' AND quotation_type = '".$type."'") ;
			$total_version = $mysqli_version->num_rows ;
		}else{
			$total_version = 0 ;
		}
		$total_version++ ;
		
		// check the type
		switch($type){
			case 'order' :
			case 'job-list' :
			case 'tax-invoice' :
				
				// get so number
				$form_submit = $row_record['quotation_type'] ;
				
				// check if invoice type
				switch($type){
					case 'job-list' :
						$prefix_level = 'main' ;
						$form_submit = 'job-list' ;	
						$prefix_table .= ", quotation_type, quotation_status" ;
						$prefix_data .= ", 'job-list', 'pending'" ;
					break ;
					case 'tax-invoice' :
						$prefix_level = 'main' ;
						$form_submit = 'tax-invoice' ;	
						$prefix_table .= ", quotation_type, quotation_status" ;
						$prefix_data .= ", 'tax-invoice', 'unpaid'" ;
					break ;
				}
				
				$system_company_id = $row_record['quotation_company_id'] ;
				
				$so_number = soNumber($form_submit) ;
				
				$prefix_table .= ", quotation_so" ;
				$prefix_data .= ", '".$so_number."'" ;
	
			break ;
		}
		
		if ( $table == $prefixQuotation && $action == 'clone' ){
			// list all related id field
			$mysqli->query("UPDATE $prefixQuotation SET
							quotation_related_action = 'hide'
							WHERE quotation_related_id = '".$main_related_id."' AND quotation_type = '".$type."' AND quotation_trash = '0'") ;
		}
		
		// insert the new record and get the new auto_increment id
		if ($mysqli->query("INSERT INTO ".$table."
							(".$related_type_field.", ".$related_id_field.", ".$related_action_field.", ".$version_field.", ".$id_field.", ".$date_filed.", ".$modified_filed.", ".$date_start_filed." ".$prefix_table.") VALUES
							('".$prefix_level."', '".$main_related_id."', 'show', '".$total_version."', 'NULL', '".TODAYDATE."', '".TODAYDATE."', '".TODAYDATE."' ".$prefix_data.")")){
			$new_id = $mysqli->insert_id ;
			// generate the query to update the new record with the previous values
			$new_query = "UPDATE ".$table." SET " ;
			foreach ($row_record as $key => $value) {
				if (in_array($key, $array_field)) { }else{
					$new_query .= ('`'.$key.'` = "'.str_replace('"','\"',$value).'", ') ;
				}	
			} 
			// lop off the extra trailing comma
			$new_query = substr($new_query,0,strlen($new_query)-2) ;
			$new_query .= " WHERE ".$id_field." = '".$new_id."'" ;
			$mysqli->query($new_query) ;
		}
		
	}

    // return the new id
    return $new_id ;
}

function checkCookieLogin(){
   // check if user has been remembered
   if ($_COOKIE['system_id'] != '' && $_COOKIE['system_name'] != '' && $_COOKIE['system_branch'] != '' && $_COOKIE['system_permission'] != ''){
		// keep in session
		$_SESSION['system_id'] = $_COOKIE['system_id'] ;
		$_SESSION['system_name'] = $_COOKIE['system_name'] ;
		$_SESSION['system_branch'] = $_COOKIE['system_branch'] ;
		$_SESSION['system_permission'] = $_COOKIE['system_permission'] ;
		// refresh page to check session
		header('Refresh: 0') ;
		exit ;
   }
}

function getAllTier( $lang = 'en' ){
	global $mysqli ;

	$array_tier  = [] ;
	$mysqli_tier = $mysqli->query( "SELECT a.tier_id, a.level, b.title FROM profile_tier a
						   			LEFT JOIN profile_tier_translation b ON ( a.tier_id = b.tier_id )
						   			WHERE a.deleted_at IS NULL AND b.lang = '".$lang."'" ) ;
	if ( $mysqli_tier->num_rows > 0 ){
		while ( $row_tier = $mysqli_tier->fetch_assoc() ){
			$array_tier[$row_tier['tier_id']] = $row_tier ;
		}
	}

	return $array_tier ;
}

function getRelatedTierID( $is_include, $level ){
	global $mysqli ;

	$array_tier        = [] ;
	$search_query      = '' ;
	if ( $is_include  == 'yes' ){
		$search_query .= " AND level >= '".$level."'" ;
	}else{
		$search_query .= " AND level >  '".$level."'" ;
	}

	$mysqli_tier  = $mysqli->query( "SELECT tier_id FROM profile_tier WHERE deleted_at IS NULL " . $search_query . " ORDER BY level ASC" ) ;
	if ( $mysqli_tier->num_rows > 0 ){
		while ( $row_tier = $mysqli_tier->fetch_assoc() ){
			$array_tier[] = $row_tier['tier_id'] ;
		}
	}

	return $array_tier ;
}

function getTier( $staff_tier, $lang = 'en' ){
	global $mysqli ;

	$level 		             = -1 ;
	$title                   = '' ;
	$is_task                 = 'no' ;
	$is_task_assigned        = 'no' ;
	$is_task_incentive       = 'no' ;
	$is_task_incentive2      = 'no' ;
	$is_task_extra           = 'no' ;
	$is_adjustment           = 'no' ;

	$mysqli_tier             = $mysqli->query("SELECT a.level, a.is_task, a.is_task_assigned, a.is_task_incentive, a.is_task_incentive2, a.is_task_extra, a.is_adjustment, b.title FROM profile_tier a
						   					   LEFT JOIN profile_tier_translation b ON ( a.tier_id = b.tier_id )
						   		               WHERE a.deleted_at IS NULL AND b.lang = '".$lang."' AND a.tier_id = '".$staff_tier."' LIMIT 1") ;
	if ( $mysqli_tier->num_rows > 0 ){
		$row_tier            = $mysqli_tier->fetch_assoc() ;
		$level               = $row_tier['level'] ;
		$title               = $row_tier['title'] ;
		$is_task             = $row_tier['is_task'] ;
		$is_task_assigned    = $row_tier['is_task_assigned'] ;
		$is_task_incentive   = $row_tier['is_task_incentive'] ;
		$is_task_incentive2  = $row_tier['is_task_incentive2'] ;
		$is_task_extra       = $row_tier['is_task_extra'] ;
		$is_adjustment       = $row_tier['is_adjustment'] ;
	}

	return [ 
		'level'              => $level,
		'title'              => $title,
		'is_task'            => $is_task,
		'is_task_assigned'   => $is_task_assigned,
		'is_task_incentive'  => $is_task_incentive,
		'is_task_incentive2' => $is_task_incentive2,
		'is_task_extra'      => $is_task_extra,
		'is_adjustment'      => $is_adjustment
	] ;
}

// sort by subarray
function cmpBySortable($a, $b) {
  return $a["cart_sortable"] - $b["cart_sortable"];
}

// change number to wording
function numtowords($num, $currency){ 
	$decones = array( 
					'01' => "One", 
					'02' => "Two", 
					'03' => "Three", 
					'04' => "Four", 
					'05' => "Five", 
					'06' => "Six", 
					'07' => "Seven", 
					'08' => "Eight", 
					'09' => "Nine", 
					10 => "Ten", 
					11 => "Eleven", 
					12 => "Twelve", 
					13 => "Thirteen", 
					14 => "Fourteen", 
					15 => "Fifteen", 
					16 => "Sixteen", 
					17 => "Seventeen", 
					18 => "Eighteen", 
					19 => "Nineteen" 
				) ;
	$ones = array( 
				0 => " ",
				1 => "One",     
				2 => "Two", 
				3 => "Three", 
				4 => "Four", 
				5 => "Five", 
				6 => "Six", 
				7 => "Seven", 
				8 => "Eight", 
				9 => "Nine", 
				10 => "Ten", 
				11 => "Eleven", 
				12 => "Twelve", 
				13 => "Thirteen", 
				14 => "Fourteen", 
				15 => "Fifteen", 
				16 => "Sixteen", 
				17 => "Seventeen", 
				18 => "Eighteen", 
				19 => "Nineteen" 
			) ; 
	$tens = array( 
				0 => "",
				1 => "Ten", 
				2 => "Twenty", 
				3 => "Thirty", 
				4 => "Forty", 
				5 => "Fifty", 
				6 => "Sixty", 
				7 => "Seventy", 
				8 => "Eighty", 
				9 => "Ninety" 
			) ; 
	$hundreds = array( 
				"Hundred", 
				"Thousand", 
				"Million", 
				"Billion", 
				"Trillion", 
				"Quadrillion" 
            ) ; 
			// limit t quadrillion 
	$num = number_format($num,2,".",",") ; 
	$num_arr = explode(".", $num) ; 
	$wholenum = $num_arr[0] ; 
	$decnum = $num_arr[1] ; 
	$whole_arr = array_reverse(explode(",", $wholenum)) ; 
	krsort($whole_arr) ; 
	$rettxt = "" ; 
	foreach($whole_arr as $key => $i){ 
		if($i < 20){ 
			$length_id = strlen($i) ;
			if ($length_id == 3){ 
				$i = substr($i, 1) ;	
			}
			$rettxt .= $ones[$i] ; 
		}
		elseif($i < 100){ 
			// remove 0 infront
			$reset_value = ltrim($i, '0') ;
			// continue wording
			$rettxt .= $tens[substr($reset_value,0,1)] ; 
			$rettxt .= " ".$ones[substr($reset_value,1,1)] ; 
		}
		else{
			$rettxt .= $ones[substr($i,0,1)]." ".$hundreds[0] ;
			
			if ($decnum > 0){
				$rettxt .= ' ' ;
			}else{
				$rettxt .= ' and ' ;
			}
			
			$splite_txt = (substr($i,1,1).substr($i,2,1)) ;
			if ($splite_txt >= 10 && $splite_txt < 20){
				$rettxt .= $ones[$splite_txt] ; 
			}else{
				$rettxt .= $tens[substr($i,1,1)] ; 
				$rettxt .= ' '.$ones[substr($i,2,1)] ; 
			}
			
		} 
		if($key > 0){ 
			$rettxt .= " ".$hundreds[$key]." " ; 
		} 
	
	} 
	$rettxt = $rettxt." ".$currency ;
	
	if($decnum > 0){ 
		$rettxt .= " and " ; 
		if($decnum < 20){ 
			$rettxt .= $decones[$decnum] ; 
		}
		elseif($decnum < 100){ 
			$rettxt .= $tens[substr($decnum,0,1)] ; 
			$rettxt .= " ".$ones[substr($decnum,1,1)] ; 
		}
		$rettxt = $rettxt . ($decnum == 1 ? " cent" : " cents") ; 
	} 
	return $rettxt . ' ONLY' ;
}

// Product pagination
function nextPrevious($current_page, $limit_page, $search, $query) {
	global $mysqli ;
	// today date
	$today_date = date('Y-m-d', time()) ;
	// get query
	$mysqli_product = $mysqli->query($query) ;
	// total page
	$total = $mysqli_product->num_rows ;
	$total_page = ceil($total / $limit_page) ;
	$end_number = ($total - (($current_page - 1) * $limit_page)) ;
	// start pagination
	if ($total_page <= 1){
		$search_result = '
		<div class="total_pagination_result">
			Total result: <strong>'.$total.'</strong>
		</div>';	
	}
	else{
		// explode url
		$explode_url = explode('&page=', $url, 2);
		// Calculating the starting and endign values for the loop
		if ($current_page >= 7) {
			$start_loop = $current_page - 3;
			if ($total_page > $current_page + 3)
				$end_loop = $current_page + 3;
			else if ($current_page <= $total_page && $current_page > $total_page - 6) {
				$start_loop = $total_page - 6;
				$end_loop = $total_page;
			} else {
				$end_loop = $total_page;
			}
		}
		else {
			$start_loop = 1;
			if ($total_page > 7)
				$end_loop = 7;
			else
				$end_loop = $total_page;
		}
		// End calculating the starting and endign values for the loop
		$search_result = '
		<div class="row">
			<div class="col-sm-3">
				Total result: <strong>'.$total.'</strong>
			</div>
			<div class="col-sm-9">
				<div class="dataTables_paginate paging_simple_numbers" id="basic-datatable_paginate">
					<ul class="pagination no-margn pull-right">';
						// previous linking
						if ($current_page > 1) {
							$prev = $current_page - 1;
							$search_result .= '
							<li class="paginate_button previous" aria-controls="basic-datatable" tabindex="0" id="basic-datatable_previous">
								<a href="?'.$search.'&page='.$prev.'">Previous</a>
							</li>' ;
						}

						// pagination number
						for ($i = $start_loop; $i <= $end_loop; $i++) {
							
							$search_result .= '
							<li class="paginate_button '.($current_page == $i ? 'active' : '').'" aria-controls="basic-datatable" tabindex="0">
								<a href="?'.$search.'&page='.$i.'">'.$i.'</a>
							</li>' ;
							
						}
						
						// show last page
						if ($current_page <= ($total_page - 4)){
							$search_result .= '
							<li class="paginate_button" aria-controls="basic-datatable" tabindex="0">
								<a href="?'.$search.'&page='.$total_page.'"> ... Last</a>
							</li>' ;
						}
						
						// next linking
						if ($current_page < $total_page) {
							$next = $current_page + 1;
							$search_result .= '
							<li class="paginate_button next" aria-controls="basic-datatable" tabindex="0" id="basic-datatable_next">
								<a href="?'.$search.'&page='.$next.'">Next</a>
							</li>' ;
						}
					$search_result .= '
					</ul>
				</div>
			</div>
		</div>' ;
	}
	$array['page_total'] = ($total != '' ? $total : 0) ;
	$array['page_pagination'] = $search_result ;
	$array['page_end'] = $end_number ;
	return $array;
}

/*************************************************************************************
						Resize Image
*************************************************************************************/
function reCreateImage($path, $page, $title, $position, $image, $type, $source, $status = ''){
	// Image uploads when exists
	$image = $image ;
	$imagetype = $type ;
	$source_file = $source ;
	$explode_type = pathinfo($image, PATHINFO_EXTENSION);
	$flag = false ;
	switch($imagetype){
		case 'image/jpg':
		case 'image/jpeg':
			$ext_type = 'jpg' ;
			$flag = true ;
		break ;
		case 'image/png':
			$ext_type = 'png' ;
			$flag = true ;
		break ;
	}
	// check if image not exists
	if ($image != ''){
		// check if image type not jpeg or png
		if ($flag){
			// image
			$image_name = $title.($status != '' ? '-'.$status : '').'-'.$page.'.'.$ext_type;
			$dir_img = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$path.'/m/'.$image_name ;
			$dir_img_ori = $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$path.'/b/'.$image_name ;
			// move file to selected directory
			if (move_uploaded_file($source_file, $dir_img_ori)){
				list($img_width,$img_height) = getimagesize($dir_img_ori);
				// resize image 2000 x height ?
				$modwidth_2000 = 1080 ;
				$diff_2000 = $img_width / $modwidth_2000 ;
				$modheight_2000 = $img_height / $diff_2000 ;
				// resize image 500 x height ?
				$modwidth = 500; 
				$diff = $img_width / $modwidth; 
				$modheight = $img_height / $diff;
				// keep resize image into array
								
				$dir_img_crop = 
					array(
						array(
							'width' => $modwidth_2000, 
							'height' => $modheight_2000, 
							'type' => 'auto',
							'watermark' => $_SERVER['DOCUMENT_ROOT'].'/images/watermark_800.png', 
							'source' => $dir_img_ori
						),
						array(
							'width' => $modwidth, 
							'height' => $modheight, 
							'type' => 'auto',
							'watermark' => $_SERVER['DOCUMENT_ROOT'].'/images/watermark_800.png', 
							'source' => $dir_img
						),
						array(
							'width' => '400', 
							'height' => '400', 
							'type' => 'crop', 
							'watermark' => $_SERVER['DOCUMENT_ROOT'].'/images/watermark_100.png', 
							'source' => $_SERVER['DOCUMENT_ROOT'].'/uploads/'.$path.'/'.$image_name
						)
					) ;
				// return result as array
				$array['result'] = true ;
				$array['image'] = $image_name ;
				$array['original'] = $dir_img_ori ;
				$array['extension'] = $ext_type ;
				$array['position'] = $position ;
				$array['merge_watermark'] = $status ;
				$array['crop'] = $dir_img_crop ;
			}
		}else{
			$array['result'] = false ;	
			$array['result_message'] = 'error-type' ;	
		}
	}
	return $array ;
}

// check title
function checkTitle($title, $page){
	global $mysqli ;
	$title = escapeString($title) ;
	$title = stripNonAlphaNumeric($title) ;
	$title = $title != '' ? $title : 'No Title' ;
	$title = strtolower(str_replace("  ", "-", $title)) ;
	$title = strtolower(str_replace(" ", "-", $title)) ;
	if (substr($title, -1) == '-'){ $title = substr_replace($title, '', -1) ; }
	$mysqli_check = $mysqli->query("SELECT * FROM system_post
									WHERE post_id != '".$page."' AND post_link = '".$title."' AND post_trash = '0' ORDER BY (post_status+0) DESC");
	if ($mysqli_check->num_rows > 0){
		$status = 1;
		$check_title = 0;
		while($check_title == 0){
			$new_title = $title.$status;
			$new_title = stripNonAlphaNumeric($new_title);
			$new_title = strtolower(str_replace("  ", "-", $new_title));
			$new_title = strtolower(str_replace(" ", "-", $new_title));
			if (substr($title, -1) == '-'){ $title = substr_replace($title, '', -1) ; }
			$mysqli_check = $mysqli->query("SELECT * FROM system_post
											WHERE post_id != '".$page."' AND post_link = '".$new_title."' AND post_trash = '0' ORDER BY (post_status+0) DESC");
			if ($mysqli_check->num_rows > 0){
				$check_title = 0;
			}
			else{
				$check_title = 1;
			}
			$status++;
		}
		$title = $new_title;
	}
	else{
		$status = 0;	
	}
	$array['title'] = $title ;
	$array['status'] = $status ;
	return $array ;
}

// check product title if exists
function titleExists($mysqli, $prefix_post, $id, $title){
	$boolean_result = false ;
	if ($title != ''){
		// check id 
		if ($id != ''){
			$search_query = " AND post_id != '".$id."'" ;
		}
		// query for product
		$mysqli_product = $mysqli->query("SELECT post_title FROM system_post
										  WHERE post_title = '".$title."' AND post_type = 'product' AND post_trash = '0' ".$search_query." LIMIT 1") ;
		// check if product exist
		if ($mysqli_product->num_rows == 0){
			$boolean_result = true ;
		}
	}
	return $boolean_result ;
}

// replace numeric string
function stripNonAlphaNumeric($string) {
    return  preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
}

// number format with 2 decimal
function numberFormat($price, $digit = 2, $type = ''){
	$price = number_format($price, $digit, '.', $type) ;
	return $price ;
}

// check if number
function numberCheck($value){
	$value = ($value > 0 ? $value : 0) ;	
	return $value ;
}

// product breadcrumbs
function productBreadcrumbs($page_id){
	global $mysqli, $selected_page ;
	// start loop breadcrumbs
	$mysqli_breadcrumbs = $mysqli->query("SELECT post_id, post_title, post_parent FROM system_post 
											WHERE post_id = '".$page_id."' AND post_trash = '0' LIMIT 1") ;
	$row_breadcrumbs = $mysqli_breadcrumbs->fetch_array(MYSQLI_ASSOC) ;
	// page title
	$title = dataFilter($row_breadcrumbs['post_title']) ;
	// keep title in breadcrumbs
	$breadcrumbs = $title ;
	// post parent
	$post_parent = $row_breadcrumbs['post_parent'] ;
	while ($post_parent != 0){
		$mysqli_breadcrumbs = $mysqli->query("SELECT post_id, post_title, post_parent FROM system_post 
												WHERE post_id = '".$post_parent."' AND post_trash = '0' LIMIT 1") ;
		$row_breadcrumbs = $mysqli_breadcrumbs->fetch_array(MYSQLI_ASSOC) ;
		// keep title in breadcrumbs
		// page title
		$title = dataFilter($row_breadcrumbs['post_title']) ;
		$breadcrumbs = '<a href="order-product.php?selected_page='.$selected_page.'&id='.$row_breadcrumbs['post_id'].'">'.$title.'</a> / '.$breadcrumbs ;
		// post parent
		$post_parent = $row_breadcrumbs['post_parent'] ;
	}
	$breadcrumbs = '<a href="order-product.php?selected_page='.$selected_page.'">Main Category</a>'.($breadcrumbs != '' ? ' / '.$breadcrumbs : '') ;
	return $breadcrumbs;
}

// get my current ip
function get_client_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'unknown';
    return $ipaddress;
}

function userAgent($ua){
    $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that)
    $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent
    $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that)
     
    function androidTablet($ua){ //Find out if it is a tablet
        if(strstr(strtolower($ua), 'android') ){//Search for android in user-agent
            if(!strstr(strtolower($ua), 'mobile')){ //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets)
                return true;
            }
        }
    }
    $androidTablet = androidTablet($ua); //Do androidTablet function
    $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent
   $kindle = strstr(strtolower($ua), 'kindle'); //Search for iPad in user-agent
     
    if($androidTablet || $ipad || $kindle){ //If it's a tablet (iPad / Android / Kindly)
        return 'tablet';
    }
    elseif($iphone || $android || $windowsPhone){ //If it's a phone and NOT a tablet
        return 'mobile';
    }
    else{ //If it's not a mobile device
        return 'desktop';
    }    
}

//****************************************************************
//**************************************************************** zip all jpeg file
//****************************************************************
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) && !$overwrite) { return false; }
	//vars
	$valid_files = array();
	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(file_exists($file)) {
				$valid_files[] = $file;
			}
		}
	}
	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
		//add the files
		foreach($valid_files as $file) {
			$zip->addFile($file,$file);
		}
		//debug
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
		
		//close the zip -- done!
		$zip->close();
		
		//check to make sure the file exists
		return file_exists($destination);
	}
	else
	{
		return false;
	}
}

// set 0 infront of number
function strPad($zero, $value){
	return str_pad($value, $zero, '0', STR_PAD_LEFT) ;	
}

function emailVerifcationCode($mysqli, $system_user, $company, $from, $arruser, $rand){
	$fullname = dataFilter($arruser['user_fullname']);
	$user_id = $arruser['user_id'];
	if ($rand != '' && strlen($rand) == 6){
		// query for user
		$mysqli_user = $mysqli->query("SELECT * FROM system_user
										WHERE (user_permission = 'admin' || user_id = '".$user_id."') AND user_trash = '0'") ;
		if ($mysqli_user->num_rows > 0){
			// loop all user
			while ($row_user = $mysqli_user->fetch_array(MYSQLI_ASSOC)){
				// email to owner | sbs admin
				$to = dataFilter($row_user['user_email']) ;
				$title = SYSTEM . ' verification code for ' . $fullname ;
				// show content
				$body = 'Verification code for ' . $fullname . ' is ' . $rand ;
				//put your email address here
				$header = 'From: '.$company.' <'.$from.'>'.PHP_EOL.
					'MIME-Version: 1.0'.PHP_EOL.
					'Content-type: text/html; charset=utf-8'.PHP_EOL.
					'Content-Transfer-Encoding: 8bit'.PHP_EOL.
					'X-Mailer: PHP/'.PHP_VERSION.PHP_EOL ; // send to owner
				mail($to, $title, $body, $header); // send to user	
			}
		}
	}
	return $boolean ;
}

// continue array with text with comma
function continueTextWithComma($array){
	$wording = '' ;
	if (count($array) > 0 && is_array($array)){
		foreach($array as $key => $value){
			$wording .= ($key == 0 ? '' : ', ') . $value ;
		}
	}
	return $wording ;
}

// check is numberic
function checkNumberic($value){
	$value = ($value > 0 ? $value : 0) ;
	return $value ;
}

// check if zero value
function checkZeroValue($value){
	return ($value > 0 ? $value : 0) ;
}

// json_encode array
function jsonEncodeDecode($type, $array){
	
	if ($type == 'encode'){
		return json_encode($array) ;
	}else{
		return json_decode($array, true) ;
	}
	
}

// add array with set max array
function arrayInsertMax($array, $insert, $max){

	array_unshift($array, $insert) ;
	array_splice($array, $max) ;
	
	return $array ;
}

// list all country in array
function allCountry($type, $selected){
	$content = '' ;
	
	$countries = array("AFGHANISTAN", "ALBANIA", "ALGERIA", "AMERICAN SAMOA", "ANDORRA", "ANGOLA", "ANGUILLA", "ANTARCTICA", "ANTIGUA AND BARBUDA", "ARGENTINA", "ARMENIA", "ARUBA", "AUSTRALIA", "AUSTRIA", "AZERBAIJAN", "BAHAMAS", "BAHRAIN", "BANGLADESH", "BARBADOS", "BELARUS", "BELGIUM", "BELIZE", "BENIN", "BERMUDA", "BHUTAN", "BOLIVIA", "BOSNIA AND HERZEGOWINA", "BOTSWANA", "BOUVET ISLAND", "BRAZIL", "BRITISH INDIAN OCEAN TERRITORY", "BRUNEI DARUSSALAM", "BULGARIA", "BURKINA FASO", "BURUNDI", "CAMBODIA", "CAMEROON", "CANADA", "CAPE VERDE", "CAYMAN ISLANDS", "CENTRAL AFRICAN REPUBLIC", "CHAD", "CHILE", "CHINA", "CHRISTMAS ISLAND", "COCOS (KEELING) ISLANDS", "COLOMBIA", "COMOROS", "CONGO", "CONGO, THE DEMOCRATIC REPUBLIC OF THE", "COOK ISLANDS", "COSTA RICA", "COTE D'IVOIRE", "CROATIA (HRVATSKA)", "CUBA", "CYPRUS", "CZECH REPUBLIC", "DENMARK", "DJIBOUTI", "DOMINICA", "DOMINICAN REPUBLIC", "EAST TIMOR", "ECUADOR", "EGYPT", "EL SALVADOR", "EQUATORIAL GUINEA", "ERITREA", "ESTONIA", "ETHIOPIA", "FALKLAND ISLANDS (MALVINAS)", "FAROE ISLANDS", "FIJI", "FINLAND", "FRANCE", "FRANCE METROPOLITAN", "FRENCH GUIANA", "FRENCH POLYNESIA", "FRENCH SOUTHERN TERRITORIES", "GABON", "GAMBIA", "GEORGIA", "GERMANY", "GHANA", "GIBRALTAR", "GREECE", "GREENLAND", "GRENADA", "GUADELOUPE", "GUAM", "GUATEMALA", "GUINEA", "GUINEA-BISSAU", "GUYANA", "HAITI", "HEARD AND MC DONALD ISLANDS", "HOLY SEE (VATICAN CITY STATE)", "HONDURAS", "HONG KONG", "HUNGARY", "ICELAND", "INDIA", "INDONESIA", "IRAN (ISLAMIC REPUBLIC OF)", "IRAQ", "IRELAND", "ISRAEL", "ITALY", "JAMAICA", "JAPAN", "JORDAN", "KAZAKHSTAN", "KENYA", "KIRIBATI", "KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF", "KOREA, REPUBLIC OF", "KUWAIT", "KYRGYZSTAN", "LAO, PEOPLE'S DEMOCRATIC REPUBLIC", "LATVIA", "LEBANON", "LESOTHO", "LIBERIA", "LIBYAN ARAB JAMAHIRIYA", "LIECHTENSTEIN", "LITHUANIA", "LUXEMBOURG", "MACAU", "MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF", "MADAGASCAR", "MALAWI", "MALAYSIA", "MALDIVES", "MALI", "MALTA", "MARSHALL ISLANDS", "MARTINIQUE", "MAURITANIA", "MAURITIUS", "MAYOTTE", "MEXICO", "MICRONESIA, FEDERATED STATES OF", "MOLDOVA, REPUBLIC OF", "MONACO", "MONGOLIA", "MONTSERRAT", "MOROCCO", "MOZAMBIQUE", "MYANMAR", "NAMIBIA", "NAURU", "NEPAL", "NETHERLANDS", "NETHERLANDS ANTILLES", "NEW CALEDONIA", "NEW ZEALAND", "NICARAGUA", "NIGER", "NIGERIA", "NIUE", "NORFOLK ISLAND", "NORTHERN MARIANA ISLANDS", "NORWAY", "OMAN", "PAKISTAN", "PALAU", "PANAMA", "PAPUA NEW GUINEA", "PARAGUAY", "PERU", "PHILIPPINES", "PITCAIRN", "POLAND", "PORTUGAL", "PUERTO RICO", "QATAR", "REUNION", "ROMANIA", "RUSSIAN FEDERATION", "RWANDA", "SAINT KITTS AND NEVIS", "SAINT LUCIA", "SAINT VINCENT AND THE GRENADINES", "SAMOA", "SAN MARINO", "SAO TOME AND PRINCIPE", "SAUDI ARABIA", "SENEGAL", "SEYCHELLES", "SIERRA LEONE", "SINGAPORE", "SLOVAKIA (SLOVAK REPUBLIC)", "SLOVENIA", "SOLOMON ISLANDS", "SOMALIA", "SOUTH AFRICA", "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS", "SPAIN", "SRI LANKA", "ST. HELENA", "ST. PIERRE AND MIQUELON", "SUDAN", "SURINAME", "SVALBARD AND JAN MAYEN ISLANDS", "SWAZILAND", "SWEDEN", "SWITZERLAND", "SYRIAN ARAB REPUBLIC", "TAIWAN, PROVINCE OF CHINA", "TAJIKISTAN", "TANZANIA, UNITED REPUBLIC OF", "THAILAND", "TOGO", "TOKELAU", "TONGA", "TRINIDAD AND TOBAGO", "TUNISIA", "TURKEY", "TURKMENISTAN", "TURKS AND CAICOS ISLANDS", "TUVALU", "UGANDA", "UKRAINE", "UNITED ARAB EMIRATES", "UNITED KINGDOM", "UNITED STATES", "UNITED STATES MINOR OUTLYING ISLANDS", "URUGUAY", "UZBEKISTAN", "VANUATU", "VENEZUELA", "VIETNAM", "VIRGIN ISLANDS (BRITISH)", "VIRGIN ISLANDS (U.S.)", "WALLIS AND FUTUNA ISLANDS", "WESTERN SAHARA", "YEMEN", "YUGOSLAVIA", "ZAMBIA", "ZIMBABWE");
	
	switch($type){
		case 'select' :
			$content = '
			<select name="country" id="call_country" class="form-control ui-search-input">
				<option value="">Country</option>' ;
				foreach($countries as $key => $value){
					$content .= '
					<option value="'.$value.'" '.($value == $selected ? 'selected' : '').'>'.$value.'</option>' ;
				}
			$content .= '
			</select>' ;
		break ;	
	}
	
	$array['content'] = $content ;
	return $array ;
}

// check company or customer exists else insert
function checkCompanyCustomer($array_company){
	global $mysqli, $prefixCompany, $prefixCustomer ;
	
	$array = array() ;
	$customer_type = 'customer' ;
	
	// reset value
	$company = $array_company['company_name'] ;
	$customer = $array_company['customer_name'] ;
	
	// check company if exists else insert
	$returnCompanyID = getCompanyByName($company) ;
	
	if ($returnCompanyID['result']){
		$company_id = $returnCompanyID['company_id'] ;
	}else{
		
		// insert into company table
		$mysqli->query("INSERT INTO $prefixCompany
						(company_name, company_website, company_gst, company_number, company_code, company_type, company_date, company_trash) VALUES
						('".$company."', '".$array_company['company_website']."', '".$array_company['company_gst']."', '".$array_company['company_number']."', '".$array_company['company_code']."', '".$array_company['company_type']."', '".TODAYDATE."', '0')") ;
		
		// get last id for company
		$company_id = $mysqli->insert_id ;	
		
	}
	
	$returnCustomerID = getCustomerByName($customer_type, $company_id, $customer) ;
	if ($returnCustomerID['result']){
		
		$customer_id = $returnCustomerID['customer_id'] ;
		$mysqli->query("UPDATE $prefixCustomer SET
						customer_account_code = '".$array_company['customer_account_code']."',
						customer_country = '".$array_company['customer_country']."',
						customer_state = '".$array_company['customer_state']."',
						customer_area = '".$array_company['customer_area']."',
						customer_address1 = '".$array_company['customer_address1']."',
						customer_address2 = '".$array_company['customer_address2']."',
						customer_address3 = '".$array_company['customer_address3']."',
						customer_call = '".$array_company['customer_call']."',
						customer_name = '".$customer."',
						customer_email1 = '".$array_company['customer_email1']."',
						customer_email2 = '".$array_company['customer_email2']."',
						customer_email3 = '".$array_company['customer_email3']."',
						customer_mobile = '".$array_company['customer_mobile']."',
						customer_office = '".$array_company['customer_office']."',
						customer_fax = '".$array_company['customer_fax']."',
						customer_modified = '".TODAYDATE."'
						WHERE customer_id = '".$customer_id."'") ;
						
	}else{
		
		// insert into company table
		$mysqli->query("INSERT INTO $prefixCustomer
						(customer_type, customer_company_id, customer_account_code, customer_call, customer_name,
						customer_country, customer_state, customer_area, customer_address1, customer_address2, customer_address3,
						customer_email1, customer_email2, customer_email3, customer_mobile, customer_office, customer_fax, 
						customer_live, customer_date, customer_modified, customer_trash) VALUES
						('".$customer_type."', '".$company_id."', '".$array_company['customer_account_code']."', '".$array_company['customer_call']."', '".$customer."',
						'".$array_company['customer_country']."', '".$array_company['customer_state']."', '".$array_company['customer_area']."', '".$array_company['customer_address1']."', '".$array_company['customer_address2']."', '".$array_company['customer_address3']."',
						'".$array_company['customer_email1']."', '".$array_company['customer_email2']."', '".$array_company['customer_email3']."', '".$array_company['customer_mobile']."', '".$array_company['customer_office']."', '".$array_company['customer_fax']."', 
						'active', '".TODAYDATE."', '".TODAYDATE."', '0')") ;
		
		// get last id for company
		$customer_id = $mysqli->insert_id ;	
		
	}
	
	$array['company_id'] = $company_id ;
	$array['customer_id'] = $customer_id ;
	return $array ;
}

// get all company list only
function getAllCompanyOnly($search_query){
	global $mysqli, $prefixCompany ;
	
	$result = false ;
	$array_company = array() ;
	
	// query for company
	$mysqli_company = $mysqli->query("SELECT company_id, company_name FROM $prefixCompany
									  WHERE company_name != '' AND company_trash = '0' ".$search_query." ORDER BY (company_name+0) ASC") ;
	if ($mysqli_company->num_rows > 0){
			
		// loop all company
		while ($row_company = $mysqli_company->fetch_array(MYSQLI_ASSOC)){
			$array_company[] = $row_company ;
		}
		
		$result = true ;
	}
	
	$array['result'] = $result ;
	$array['content'] = $array_company ;
	
	return $array ;
}

// get all company list
function getAllCompany($search_query, $selected_id, $page_title){
	global $mysqli, $prefixCompany, $prefixCustomer ;
	$select = '' ;
	$result = false ;
	
	// query for company
	$mysqli_company = $mysqli->query("SELECT company_id, company_name FROM $prefixCompany a
									  LEFT JOIN $prefixCustomer b ON (a.company_id = b.customer_company_id)
									  WHERE a.company_name != '' AND a.company_trash = '0' AND b.customer_live = 'active' AND b.customer_trash = '0' ".$search_query." GROUP BY a.company_name ORDER BY a.company_name ASC") ;
	if ($mysqli_company->num_rows > 0){
		$select .= '
		<select name="select_company" class="form-control tab_index ui-dropdown-select" id="call_company">
			<option value="">Select a '.$page_title.'</option>' ;
			
			// loop all company
			while ($row_company = $mysqli_company->fetch_array(MYSQLI_ASSOC)){
				$select .= '<option value="'.dataFilter($row_company['company_id']).'" '.($row_company['company_id'] == $selected_id ? 'selected' : '').'>'.dataFilter($row_company['company_name']).'</option>' ;
			}	
			
		$select .= '
		</select>' ;
		
		$result = true ;
	}
	
	$array['result'] = $result ;
	$array['select'] = $select ;
	return $array ;
}

// get selected company by name
function getCompanyByName($company_name){
	global $mysqli, $prefixCompany ;
	
	$result = false ;
	$array = array() ;
	
	$mysqli_company = $mysqli->query( "SELECT company_id FROM $prefixCompany
									  WHERE company_trash = '0' AND company_name = '".$company_name."' LIMIT 1" ) ;
	
	if ($mysqli_company->num_rows > 0){
		$row_company = $mysqli_company->fetch_array(MYSQLI_ASSOC) ;
		$array = $row_company ;
		$result = true ;	
	}
	
	$array['result'] = $result ;
	return $array ;
}

// get selected customer by name
function getCustomerByName($customer_type, $company_id, $customer_name){
	global $mysqli, $prefixCompany, $prefixCustomer ;
	
	$result = false ;
	$array = array() ;

	$mysqli_customer = $mysqli->query("SELECT customer_id FROM $prefixCustomer
									   WHERE customer_type = '".$customer_type."' AND customer_company_id = '".$company_id."' AND customer_name = '".$customer_name."' AND customer_trash = '0' LIMIT 1") ;
	
	if ($mysqli_customer->num_rows > 0){
		$row_customer = $mysqli_customer->fetch_array(MYSQLI_ASSOC) ;
		$array = $row_customer ;
		$result = true ;	
	}
	
	$array['result'] = $result ;
	return $array ;
}

// get all company list
function getAllCustomer($search_query, $selected_company_id, $selected_customer_id){
	global $mysqli, $prefixCompany, $prefixCustomer ;
	$select = '' ;
	$result = false ;
	
	// query for company
	$mysqli_company = $mysqli->query("SELECT company_id, company_name FROM $prefixCompany a
									  LEFT JOIN $prefixCustomer b ON (a.company_id = b.customer_company_id)
									  WHERE a.company_name != '' AND a.company_trash = '0' AND b.customer_live = 'active' AND b.customer_trash = '0' ".$search_query." GROUP BY a.company_name ORDER BY a.company_name ASC") ;
	if ($mysqli_company->num_rows > 0){
		$select .= '
		<select name="select_company" class="form-control ui-dropdown-select" id="call_company">
			<option value="">Select a '.$company_type.'</option>' ;
			
			// loop all company
			while ($row_company = $mysqli_company->fetch_array(MYSQLI_ASSOC)){
				$select .= '<option value="'.dataFilter($row_company['company_id']).'" '.($row_company['company_id'] == $selected_id ? 'selected' : '').'>'.dataFilter($row_company['company_name']).'</option>' ;
			}	
			
		$select .= '
		</select>' ;
		
		$result = true ;
	}
	
	$array['result'] = $result ;
	$array['select'] = $select ;
	return $array ;
}

// return customer value
function getCustomer($type, $select_customer_id, $select_company_id, $select_customer_type){
	global $mysqli, $prefixCustomer, $prefixCompany ;
	$result = false ;
	
	// check query if exsits
	if ($type == 'trash'){
	}else{
		$query = " AND a.customer_type = '".$type."'" ;
		if ($type != 'supplier'){
			$query = " AND a.customer_company_id = '".$select_company_id."'" ;
		}
	}
	
	$mysqli_query = "SELECT * FROM $prefixCustomer a 
					 LEFT JOIN $prefixCompany b ON (a.customer_company_id = b.company_id)
					 WHERE a.customer_id = '".$select_customer_id."' AND a.customer_live = 'active' AND a.customer_trash = '0' AND b.company_trash = '0'".$query ;
	$mysqli_customer = $mysqli->query($mysqli_query." LIMIT 1") ;
	if ($mysqli_customer->num_rows > 0){
		
		$row_customer = $mysqli_customer->fetch_array(MYSQLI_ASSOC) ;

		$array['content'] = $row_customer ;
		$result = true ;
	}
	
	$array['result'] = $result ;
	return $array ;
	
}

// return selected customer value with company id provide
function getSelectedCustomerOption($selected_page, $select_customer_id, $select_company_id, $boolean_marketing, $user_id){
	global $mysqli, $prefixCustomer, $prefixCompany ;
	
	// check selected page
	$search_query = $customer = '' ;
	
	if ($selected_page != ''){
		// check user page
		switch($selected_page){
			case 'marketing' :
				// check permission
				$search_query .= " AND customer_type = 'customer'" ;
			break ;
			case 'purchasing' :
				$search_query .= " AND customer_type = 'supplier'" ;
			break ;
		}	
	}
	
	// query for customer
	$mysqli_customer = $mysqli->query("SELECT * FROM $prefixCustomer
										WHERE customer_company_id = '".$select_company_id."' AND customer_live = 'active' AND customer_trash = '0' ".$search_query." ORDER BY customer_name ASC") ;
											
	$customer = '<option value="">Select</option>' ;
	if ($mysqli_customer->num_rows > 0){
		// loop all customer
		while($row_customer = $mysqli_customer->fetch_array(MYSQLI_ASSOC)){
			// check if customer not null
			$customer_name = dataFilter($row_customer['customer_name']) ;
			$customer_name = ($customer_name != '' ? $customer_name : 'NoName') ;
			$customer_account_code = dataFilter($row_customer['customer_account_code']) ;
			$customer_account_code = ($customer_account_code != '' ? $customer_account_code : 'No Account Code') ;
			
			if ($customer_name != '' || $customer_account_code != ''){
				$customer .= '
				<option value="'.$row_customer['customer_id'].'" '.($row_customer['customer_id'] == $select_customer_id ? 'selected' : '').'>'.$customer_name.'</option>' ;
			}
		}
	}
	
	return $customer ;
}

// return company letter head
function getOwnerCompanyLetterHead($comp_id = ''){
	global $mysqli ;	

	if ($comp_id != '') {
		$search_pquery="AND branch_id ='".$comp_id."'";
	}

	$array        = [
		'name'    => '',
		'header'  => ''
	] ;
	
	$mysqli_page  = $mysqli->query("SELECT branch_name, branch_content FROM branch
								    WHERE deleted_at IS NULL ".$search_pquery." LIMIT 1") ;
	
	if ($mysqli_page->num_rows > 0){
		$row_page        = $mysqli_page->fetch_assoc() ;
		$content         = entityDecode(dataFilter($row_page['branch_content'])) ;
		$array['name']   = $row_page['branch_name'] ;
		$array['header'] = $content ;
	}
	return $array ;
}

// export file
function exportFileExcel($records) {
	$heading = false ;
	if(!empty($records))
	  foreach($records as $row) {
		if(!$heading) {
		  // display field/column names as a first row
		  echo implode("\t", array_keys($row)) . "\n" ;
		  $heading = true;
		}
		echo implode("\t", array_values($row)) . "\n" ;
	  }
	exit;
}

// get user list
function getUser($type, $select_name, $selected_id, $required, $search_query){
	global $mysqli ;
	
	$result = false ;
	$boolean_exsits = false ;
	$select_box = '' ;
	$array_list = array() ;
	
	// loop all user
	if ( $type != 'all-marketing' ){
		$search_query = " AND user_trash = '0'" . $search_query ;
	}
	
	$mysqli_page = $mysqli->query("SELECT user_id, user_name, user_colour FROM system_user
								   WHERE user_id != '' ".$search_query) ;

	if ($mysqli_page->num_rows > 0){
		$result = true ;
		while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){
			
			$id = $row_page['user_id'] ;
			$username = ucwords(dataFilter($row_page['user_name'])) ; 
			$colour = dataFilter($row_page['user_colour']) ;
			
			$select_box .= '
			<option value="'.$id.'" '.($id == $selected_id ? 'selected' : '').'>'.$username.'</option>' ;
			$array_list[] = array('id' => $id,
								  'name' => $username,
								  'user_name' => $username,
								  'colour' => $colour) ;
			if ($selected_id == $id){
				$boolean_exsits = true ;	
				$array_selected_list = array('id' => $id,
											 'name' => $username,
											 'user_name' => $username,
											 'colour' => $colour) ;
			}
			
		}
	}
	
	$select_box = '
	<select name="'.$select_name.'" class="form-control custom_required" id="'.$select_name.'" '.$required.'>
		<option value="">Select</option>
		'.$select_box.'
	</select>' ;
	
	$array['select_box'] = $select_box ;
	$array['exists'] = $boolean_exsits ;
	$array['list'] = $array_list ;
	$array['selected_list'] = $array_selected_list ;
	$array['result'] = $result ;
	return $array ;
}

// branch
function getBranch($type, $select_name, $selected_id, $required, $search_query){
	global $mysqli ;
	
	$result = false ;
	$select_box = '' ;
	$array_list = array() ;
	$array_selected_list = array() ;
	$boolean_branch_exsits = false ;
	
	// show hq and branch
	$array_branch_list = array('branch-hq', 'branch') ;
	foreach($array_branch_list as $key => $value){
		
		// loop hq
		switch($value){
			case 'branch-hq' :
				$search_query_reset = " LIMIT 1" ;
			break ;
			case 'branch' :
				$search_query_reset = " AND post_title != ''" . $search_query ;
			break ;	
		}
		
		// check branch query
		$mysqli_page = $mysqli->query("SELECT * FROM system_post
									   WHERE post_type = '".$value."' AND post_categories = '".$value."' AND post_trash = '0'" . $search_query_reset) ;
		if ($mysqli_page->num_rows > 0){
			
			$result = true ;
			
			while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){

				$id = $row_page['post_id'] ;
				
				$select_box .= '
				<option value="'.$id.'" '.($id == $selected_id ? 'selected' : '').'>'.dataFilter($row_page['post_title']).' '.($value == 'branch-hq' ? '(Headquarter)' : '').'</option>' ;
				$array_list[] = array('id' => $id,
									  'type' => $value,
									  'title' => dataFilter($row_page['post_title'])) ;
				if ($selected_id == $id){
					$boolean_branch_exsits = true ;	
					$array_selected_list = array('id' => $id,
											     'type' => $value,
											     'title' => dataFilter($row_page['post_title'])) ;
				}
				
			}
		}
		
	}
	
	$select_box = '
	<select name="'.$select_name.'" class="form-control ui-search-input" '.$required.'>
		<option value="">Select</option>
		'.$select_box.'
	</select>' ;
	
	$array['select_box'] = $select_box ;
	$array['list'] = $array_list ;
	$array['selected_list'] = $array_selected_list ;
	$array['exists'] = $boolean_branch_exsits ;
	$array['result'] = $result ;
	return $array ;
}

// return selected product status
function selectedProductStatus($id){
	global $mysqli ;
	$result = false ;
	
	if ($id != ''){
		$mysqli_product = $mysqli->query("SELECT post_id, post_type, post_title, post_content, post_product, post_quantity_available, post_quantity_minimum, post_price, post_price_selling, post_supplier_id FROM system_post
									      WHERE post_id = '".$id."' AND post_trash = '0' LIMIT 1") ;
		if ($mysqli_product->num_rows > 0){
			$row_product = 	$mysqli_product->fetch_array(MYSQLI_ASSOC) ;
			$array = $row_product ;
			$result = true ;
		}
	}
	
	$array['result'] = $result ;
	return $array ;
}

// get user list
function getPostType($type, $select_name, $selected_id, $required, $search_query){
	global $mysqli ;
	
	$result = false ;
	$boolean_exsits = false ;
	$select_box = '' ;
	$array_list = $array_select_list = array() ;

	// check type first
	switch($type){
		case 'area-title' :
			$post_type = 'area' ;
		break ;
		default :
			$post_type = $type ; 
	}
	
	// loop all user
	$mysqli_page = $mysqli->query("SELECT * FROM system_post
								   WHERE post_type = '".$post_type."' AND post_trash = '0'".$search_query) ;

	if ($mysqli_page->num_rows > 0){
		$result = true ;
		while ($row_page = $mysqli_page->fetch_array(MYSQLI_ASSOC)){
			
			$title = dataFilter($row_page['post_title']) ;
			$id = $row_page['post_id'] ;
			
			switch($type){
				case 'area' :
					$select_box .= '<option value="'.$id.'" '.(strpos($selected_id, '<filter-'.$id.'>') !== false ? 'selected' : '').'>'.$title.'</option>' ;
				break ;
				default :
					$select_box .= '<option value="'.$id.'" '.($id == $selected_id ? 'selected' : '').'>'.$title.'</option>' ;
					$array_list[] = array('id' => $id,
										  'name' => $title) ;
					if ($selected_id == $id){
						$boolean_exsits = true ;
						$array_select_list = array('id' => $id,
										  		   'name' => $title) ;	
					}
				break ;
			}

		}
	}
	
	switch($type){
		case 'area' :
			$select_box = '<div class="side-by-side clearfix"><select name="'.$select_name.'[]" data-placeholder="Select" class="select2-basic-single form-control ui-search-input" multiple>'.$select_box.'</select></div>' ;
		break ;
		default :	
			$select_box = '<select name="'.$select_name.'" class="form-control custom_required" id="'.$select_name.'" '.$required.'><option value="">Select</option>'.$select_box.'</select>' ;
	}
	
	$array['select_box'] = $select_box ;
	$array['exists'] = $boolean_exsits ;
	$array['list'] = $array_list ;
	$array['select_list'] = $array_select_list ;
	$array['result'] = $result ;
	return $array ;
}

// reset company insert function
function resetCompanyDetails($array_company){
	
	// reset key
	$array_remove = array('company_id', 'company_date', 'company_trash', 'customer_id', 'customer_type', 'customer_company_id', 'customer_user_id', 'customer_remark', 'customer_date', 'customer_modified', 'customer_trash') ;

	foreach($array_remove as $value){
		unset($array_company[$value]) ;
	}
	
	$array_company = resetStringArray($array_company) ;

	array_values($array_company) ;
	return $array_company ;
}

// reset string array
function resetStringArray($array){
	foreach ( $array as $key => $value ){
		$array[$key] = resetString(dataFilter($value)) ;	
	}
	return $array ;
}

// reset date format
function resetDateFormat($date){
	if($date != NULL){
		return ( $date == '0000-00-00' || $date == '0000-00-00 00:00:00' ? '-' : date('d . m . Y', strtotime($date)) ) ;
	}else{
		return "-";
	}
}

// reset date format
function resetDateFormat2($date){
	return ( $date == '0000-00-00' || $date == '0000-00-00 00:00:00' ? '-' : date('d . m . Y', strtotime($date)) ) ;
}

// reset date format
function resetDateTimeFormat($date){
	return ( $date != '0000-00-00 00:00:00' ? date('d . m . Y ( ha : i\m : s\s )', strtotime($date)) : '-' ) ;
}

// reset date format
function resetTimeFormat($date){
	$value         = '' ;
	switch ( $date ){
		case '0000-00-00 00:00:00' :
		case '00:00:00'  		   :
			$value = '' ;
		break ;
		default :
			$value = date('H:iA', strtotime($date)) ;			
	}
	return $value ;
}

function resetTimeWithoutSec( $value ){
	$value = ( $value != '00:00:00' ? date('H:i', strtotime($value)) : '' ) ;
	$value = ( $value != '00:00' ? $value : '' ) ;
	return $value ;
}

// encode value
function encodeValue($value){
	$value = base64_encode('system_'.$value.'123') ;
	return md5($value) ;	
}

function getRounding($amount){
	$priceRounding = priceRounding($amount);
	$Rounding = $priceRounding - $amount;
	return $Rounding;
}
// price rounding
function priceRounding($amount = 0){
	// set amount to 2 decimal
	// $amount = numberFormat($amount) ;
	// check if decimal exists
	if (is_float($amount) && strpos($amount, '.') !== false){
		$amount = substr_replace($amount, '', strpos($amount, '.') + 3) ;
	}else{
		$amount = $amount.'.00' ;
	}
	// reset amount to 2 decimal
	$amount = numberFormat($amount) ;
	$gst_rounding = substr($amount, -2) ;
	// statement for rounding
	if ($gst_rounding < 1){
		$amount = substr_replace($amount, 00, -2) ;
	}elseif ($gst_rounding <= 10){
		$amount = substr_replace($amount, 10, -2) ;
	}elseif ($gst_rounding <= 20){
		$amount = substr_replace($amount, 20, -2) ;
	}elseif ($gst_rounding <= 30){
		$amount = substr_replace($amount, 30, -2) ;
	}elseif ($gst_rounding <= 40){
		$amount = substr_replace($amount, 40, -2) ;
	}elseif ($gst_rounding <= 50){
		$amount = substr_replace($amount, 50, -2) ;
	}elseif ($gst_rounding <= 60){
		$amount = substr_replace($amount, 60, -2) ;
	}elseif ($gst_rounding <= 70){
		$amount = substr_replace($amount, 70, -2) ;
	}elseif ($gst_rounding <= 80){
		$amount = substr_replace($amount, 80, -2) ;
	}elseif ($gst_rounding <= 90){
		$amount = substr_replace($amount, 90, -2) ;
	}elseif ($gst_rounding <= 99){
		$amount = substr_replace($amount, 00, -2) ;
		$amount += 1 ;
	}
	// set again amount to 2 decimal
	$amount = numberFormat($amount) ;
	// return result
	return $amount ;
}

// multiple array insert
function multipleArrayTo($array){
	$temp = array() ;
	if ( arrayCheck($array) ){
		foreach ( $array as $value ){
			$temp[] = '('.$value.')' ;
		}
	}
	return implode(',', $temp) ;
}

// check page permission
function permissionCheck($row_user, $page){
	$page = '('.$page.')' ;
	$result = false ;
	if ( $page == '(all-can-access)' ){
		$result = true ;
	}else{
		if ( $row_user['user_permission'] == 'admin' || strpos($row_user['user_permission2'], $page) !== false ) {
			$result = true ;
		}
	}
	return $result ;

}

// check page permission
function permissionWebsite($row_page_website, $page){
	$page = '('.$page.')' ;
		if ( strpos($row_page_website['post_content'], $page) !== false ) {
			$result = true ;
		}
	return $result ;
}

function passwordEncrypt($psw){
	return md5('1QWE#!'.$psw.'2QW#wew') ;
}

function getConfig($attr){
	global $mysqli, $prefixConfig ;
	$config_value = '' ;
	$get_config   = $mysqli->query("SELECT config_value FROM $prefixConfig
								    WHERE config_attribute = '".$attr."' LIMIT 1") ;
	if ( $get_config->num_rows > 0 ){
		$row_config   = $get_config->fetch_assoc() ;
		$config_value = $row_config['config_value'] ;
	}
	return $config_value ;
}

// function change columns name
function changeColumnsName($pass_value){
	
	$array_col = array( 'col-xs-14' => 'twelve',
						'col-xs-13' => 'twelve',
						'col-xs-12' => 'twelve',
						'col-xs-11' => 'eleven',
						'col-xs-10' => 'ten',
						'col-xs-9' => 'nine',
						'col-xs-8' => 'eight',
						'col-xs-7' => 'seven',
						'col-xs-6' => 'six',
						'col-xs-5' => 'five',
						'col-xs-4' => 'four',
						'col-xs-3' => 'three',
						'col-xs-2' => 'two',
						'col-xs-1' => 'one') ;
	
	foreach($array_col as $key => $value){
		$pass_value = str_replace($key, $value . ' columns', $pass_value) ;
	}
	
	///$pass_value = str_replace('contenteditable="true" tabindex="0"', '', $pass_value) ;
	$pass_value = preg_replace("/(spellcheck=\"(\w*)\"|role=\"(\w*\W*\d*\D*\s*\S*)\"|aria-label=\"(\w*\W*\d*\D*\s*\S*)\"|aria-describedby=\"(cke_(\d+))\"|contenteditable=\"(\w+\W*\d*\D\s*\S*)\"|tabindex=\"(\w+\W*\d*\D\s*\S*)\")/", "", $pass_value);
	//preg_replace("/title=\"(.*editor(\d+))\"/", "", $input_lines);
	//$pass_value = preg_replace("/Rich.*editor\d+/", "", $pass_value);
	$pass_value = preg_replace("/Rich Text Editor, editor(\d+)/", "", $pass_value);
	return $pass_value ;
}

function pushToBranchUser( $branchs, $staffs, $type, $type_id, $title, $message ){
	global $mysqli ;

	$search_query      = '' ;
	if ( arrayCheck($branchs) ){
		$search_query .= " AND branch_id IN ( ".implode(', ', $branchs)." )" ;
	}

	if ( arrayCheck($staffs) ){
		$search_query .= " AND staff_id IN ( ".implode(', ', $staffs)." )" ;
	}

	$select_staffs 	   = $mysqli->query( "SELECT staff_id FROM staff
  				  				          WHERE deleted_at IS NULL AND ( staff_date_resigned IS NULL || staff_date_resigned = '0000-00-00' || staff_date_resigned >= '".TODAYDATE."' ) " . $search_query ) ;
  	if ( $select_staffs->num_rows > 0 ){
  		$array_staffs  = [] ;
  		while ( $staff = $select_staffs->fetch_assoc() ){
  			$array_staffs[] = $staff['staff_id'] ;
  		}

  		foreach ( $array_staffs as $k => $v ){
  			pushToUserCron( $type, $type_id, $v, $title, $message ) ;
  		}
  	}
}

function pushToUserCron( $type, $type_id, $staff_id, $title, $message, $inbox_id = '' ){
	global $mysqli ;

	$mysqli->query( "INSERT INTO staff_notification_cron
					 ( type, type_id, staff_id, title, message, inbox_id, is_sent ) VALUES
					 ( '".$type."', '".$type_id."', '".$staff_id."', '".$title."', '".$message."', '".$inbox_id."', 'no' )" ) ;
}

function pushToUser( $type, $type_id, $staff_id, $title, $message, $cron_id = '', $inbox_id = '' ){
	/*
	global $mysqli ;

	$push     = array() ;

	$notifications_query = $mysqli->query( "SELECT notificationid, notification, badge FROM staff_notification
										    WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' ORDER BY notificationid DESC LIMIT 1") ;

	if ( $notifications_query->num_rows > 0 ){

		$notification  = $notifications_query->fetch_assoc() ;
		$token_id      = $notification['notificationid'] ;
		$badge         = ( $notification['badge'] + 1 ) ;

		$is_create     = true ;
		if ( $inbox_id != '' && $inbox_id > 0 ){
			$is_create = false ;
		}

		if ( $is_create ){
			$mysqli->query( "INSERT INTO inbox  ( staff_id, from_table, from_id, receiver_type, view_format, title, description, created_at ) VALUES ( '/".$staff_id."/', '".$type."', '".$type_id."', '3', 'message', '".$title."', '".$message."', '".TODAYDATE."' )" ) ;

			$inbox_id  = $mysqli->insert_id ;

			$mysqli->query( "INSERT INTO staff_inbox_view ( inbox_id, staff_id, is_read ) VALUES ( '".$inbox_id."', '".$staff_id."', '0' )" ) ;

			$mysqli->query( "UPDATE staff_notification_cron SET inbox_id = '".$inbox_id."' WHERE cron_id = '".$cron_id."'" ) ;
		}

		$data = array( "to" 		    => $notification['notification'],
					   "notification" 	=> array( 
					   		"id" 				 => $notification['notificationid'],
							"title"   			 => dataFilter( $title ), 
							"body"    			 => dataFilter( $message ),
							"icon"    			 => PATH.'images/logo.png', 
							"sound"				 => 'default',
							"vibrate"			 => '1',
							"badge"				 => $badge,
							"click_action" 		 => '',
							"show_in_foreground" => 'true'
						)
					) ;
		pushNotification( $data ) ;

		// update badge
		$mysqli->query("UPDATE staff_notification SET badge = '".$badge."' WHERE notificationid = '".$token_id."'") ;
	}
	*/
}

function pushNotification( $data ){
	/*

	$credentialsPath    = 'hr-system-b0af6-firebase-adminsdk-u5wel-5bcb3596d4.json' ; // Replace with your actual path
	$projectId          = '517510861795' ; // Your Firebase project ID or project number

	function getAccessToken($credentialsPath) {
	    $scopes         = ['https://www.googleapis.com/auth/firebase.messaging'];

	    // Get OAuth2 token using service account credentials
	    $credentials    = json_decode(file_get_contents($credentialsPath), true);
	    $client         = new Google_Client();
	    $client->setAuthConfig($credentials);
	    $client->setScopes($scopes);

	    // Get the token
	    $accessToken    = $client->fetchAccessTokenWithAssertion()['access_token'];

	    return $accessToken;
	}


	$headers = array(
		'Authorization: key='.PUSHTOKEN, 
		'Content-Type: application/json'
	) ; 

	$ch = curl_init() ;  
	curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' ) ;   
	curl_setopt( $ch,CURLOPT_POST, true ) ; 
	curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ) ;
	curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ) ;
	curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode($data)) ;
	$result = curl_exec($ch) ;
	$output = jsonEncodeDecode('decode', $result) ;

	print_r($result) ;

	saveLog( 'notification', 'Notification', $data, $output ) ;
	
	curl_close ($ch) ;
	*/
}

function setTotalHoursArray( $array, $value ){
	if ( $value != '' ){
		$value   = explode( ':', $value ) ;
		$array[] = $value ;
	}
	return $array ;
}

function setTotalHoursSum( $array ){
	$value = '00:00' ;
	if ( count($array) > 0 ){

		$hours   = 0 ;
		$minutes = 0 ;

		foreach ( $array as $kk => $vv ){
			$hours   += $vv['0'] ;
			$minutes += $vv['1'] ;
		}

		$check = true ;
		while ( $check ){
			if ( $minutes >= 60 ){
				$minutes -= 60 ;
				$hours++ ;
			}else{
				$check = false ;
			}
		}

		$value = strPad(2, $hours).':'.strPad(2, $minutes) ;

	}

	return $value ;
}

function cronjobHit($urlParameter){ 

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch,CURLOPT_URL,$urlParameter);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13");
    $output = curl_exec($ch);
    curl_close($ch);    

    return json_decode($output, true) ;
}

function callWithoutResponse( $host, $port, $method, $path, $params = [], $connectTimeout = 1 ){
	$status  = '2' ;
	$message = '' ;

	$host    = str_replace( [ 'https://', 'www.' ], '', $host ) ;
	$host    = str_replace( '/', '', $host ) ;
	$server  = $host ;
	$params  = http_build_query($params) ;

	if ( $port == '443' ){ $server = 'ssl://'.$server ; }

	$fp      = fsockopen( $server, $port, $errorCode, $errorInfo, $connectTimeout ) ;
	if ( !$fp ) {
	    $message = $errorInfo . ' ( '.$errorCode.' )' ;
	} else {

		if ( $method == 'POST' ){
			$http .= "$method $path HTTP/1.1\r\n" ;
			$http .= "Host: $host\r\n" ;
			$http .= "Content-type: application/x-www-form-urlencoded\r\n" ;
			$http .= "Content-length: ".strlen($params)."\r\n" ;
			$http .= "Connection: close\r\n\r\n" ;
			$http .= $params."\r\n\r\n" ;
		}else{
			$http .= "$method $path?".$params." HTTP/1.1\r\n" ;
			$http .= "Host: $host\r\n" ;
			$http .= "Connection: close\r\n\r\n" ;
		}

		if ( fputs( $fp, $http ) === false ){
			$message = 'Request failed.' ;
		}else{
			$status  = '1' ;
        	$message = 'Success' ;
		}

		fclose($fp) ;
	}

	return [
		'status'  => $status,
		'message' => $message
	] ;
}


function getOTSalary( $staffOtRate, $staff_salary, $list_ot_day, $return = '' ){
	$onehoursalary    = numberFormat( ( $staff_salary * $staffOtRate / 8 ), 2 ) ; // base rate
    // $oneminutesalary  = numberFormat( ( $onehoursalary / 60 ), 2 ) ; // base rate for minute
    // off day, public holiday, work day all ot rate is same
    $get_total        = numberFormat( $list_ot_day*$onehoursalary ) ; 

    // hour rate + minute rate
    if ( $return != '' ){
    	return [
    		'perhour' => $onehoursalary,
    		'total'   => $get_total
    	] ;
    }else{
    	return $get_total ; 
    }
}

function calculateSalary( $row ){
	$salary           = $row['salary'] ;
	$salary_jtk       = $row['salary_jtk'] ;

    $total_basic      = numberFormat( $salary * $row['total_normal_days'] ) ;
    $get_ot           = getOTSalary( $row['ot_rate'], $salary, $row['total_ot_hours'], 'yes' ) ;
    $total_ot         = $get_ot['total'] ;

    $total_rest       = numberFormat( numberFormat($salary_jtk * $row['day_rest_rate'], 2) * $row['total_rest_days'] ) ;
    $get_ot_rest      = getOTSalary( $row['ot_rest_rate'], $salary_jtk, $row['total_ot_rest_hours'], 'yes' ) ;
    $total_ot_rest    = $get_ot_rest['total'] ;

    $total_public     = numberFormat( numberFormat($salary_jtk * $row['day_public_rate'], 2) * $row['total_public_days'] ) ;
    $get_ot_public    = getOTSalary( $row['ot_public_rate'], $salary_jtk, $row['total_ot_public_hours'], 'yes' ) ;
    $total_ot_public  = $get_ot_public['total'] ;

    // $total_public_nor = numberFormat( $salary_jtk * $row['total_public_working_days'] ) ;
    $total_public_nor = numberFormat( $salary_jtk * $row['total_public_working_days'] ) ;

    $total_annual     = numberFormat( $salary_jtk * $row['total_annual_days'] ) ;

    $total_medical    = numberFormat( $salary_jtk * $row['total_mc_days'] ) ;
    $total_allo_food  = numberFormat( $row['allowance_food'] * $row['allowance_food_days'] ) ;

    $total_unpaid_leave = numberFormat( $salary_jtk * $row['total_unpaid_days'] ) ;

    // total allowance
    // claim or allowance description
    $allo    		 = 0 ;
    $allo    	    += $row['claim_medical'] ;
    $allo    	    += $row['allowance_monthly_increment'] ;
    $allo    	    += $row['allowance_monthly'] ;
    $allo    	    += $row['allowance_topup'] ;
    $allo    	    += $row['allowance_target'] ;
    $allo            = numberFormat( $allo ) ;

    // sum total salary first
    $total_earn      = ( $total_basic + $total_ot ) ;
    $total_earn     += ( $total_rest + $total_ot_rest ) ;
    $total_earn     += ( $total_public + $total_ot_public + $total_public_nor ) ;
    $total_earn     += ( $total_annual ) ;
    $total_earn     += ( $total_medical ) ;
    $total_earn     += ( $total_allo_food + $allo ) ;
    $total_earn      = numberFormat( $total_earn ) ;

    // total charge
    // charge
    $charge  		 = 0 ;
    $charge 		+= $row['charge_advance'] ;
    $charge 		+= $row['charge_skhppa'] ;
    $charge 		+= $row['charge_hostel'] ;
    $charge 		+= $row['charge_gas'] ;
    $charge 		+= $row['charge_absent'] ;
    $charge 		+= $row['charge_absent_punch'] ;
    $charge 		+= $row['charge_late'] ;
    $charge 		+= $row['charge_time_off'] ;
    $charge 		+= $row['charge_early_out'] ;
    $charge 		+= $row['charge_give_away'] ;
    $charge 		+= $row['charge_comment'] ;
    $charge 		+= $row['charge_target'] ;
    $charge 		+= $total_unpaid_leave ;
    $charge          = numberFormat( $charge ) ;

    $total_salary    = numberFormat( $total_earn - $charge ) ;

    return [
    	'total_basic'          => $total_basic,
    	'total_ot'         	   => $total_ot,
    	'total_ot_hour'    	   => $get_ot['perhour'],
    	'total_rest'       	   => $total_rest,
    	'total_ot_rest'    	   => $total_ot_rest,
    	'total_ot_rest_hour'   => $get_ot_rest['perhour'],
    	'total_public'         => $total_public,
    	'total_ot_public'      => $total_ot_public,
    	'total_ot_public_hour' => $get_ot_public['perhour'],
    	'total_public_nor'     => $total_public_nor,
    	'total_medical'        => $total_medical,
    	'total_annual'         => $total_annual,
    	'total_allo_food'      => $total_allo_food,
    	'total_allowance'      => $allo,
    	'total_earn' 		   => $total_earn,
    	'total_charge'		   => $charge,
    	'total_unpaid_leave'   => $total_unpaid_leave,
    	'total_salary'         => $total_salary
    ] ;
}

function zeroToEmpty( $value ){
	return ( $value > 0 ? $value : '' ) ;
}


function commonAddTime( $start, $end ){

    // explode
    $end      = strtotime($end) ;
    $hours    = date('H', $end) ;
    $minutes  = date('i', $end) ;
    $seconds  = date('s', $end) ;
    $interval = 'PT'.$hours.'H'.$minutes.'M'.$seconds.'S' ; // P开头代表日期, T=时间, Y=Year...，Sample : P2Y4DT6H8M

    $start    = new DateTime($start) ;
    $start    = $start->add( new DateInterval($interval) ) ;
    $start    = $start->format('H:i:s') ;
    return $start ;
}

function resetStatus( $value ){
	switch ( $value ){
		case 'inactive'            : return '<span style="color:#f00">Inactive</span>' ;     break ;
		case 'pending'             :
		case 'awaiting-arrival'    : 
		case 'awaiting-collection' : return '<span style="color:#f00">Pending</span>' ;      break ;
		case 'cancelled'           : return '<span style="color:#f00">Cancelled</span>' ;    break ;
		case 'active'              : return '<span style="color:#2f7219">Active</span>' ;    break ;
		case 'approved'            : return '<span style="color:#97ca86">Approved</span>' ; break ;
		case 'confirmed'           : return '<span style="color:#2f7219">Confirmed</span>' ; break ;
		case 'rated'               : return '<span style="color:#2f7219">Rated</span>' ;     break ;
		case 'rejected'            : return '<span style="color:#7c0000">Rejected</span>' ;  break ;
	}
}

function taskStatusButton( $status ){
	switch ($status) {
		case 'visited':
		case 'completed':
			$status = '<button type="button" class="btn btn-success" style="pointer-events:none;background-color:#19B6ED"><span style="text-transform:capitalize">'.$status.'</span></button>';
			break;
		case 'tested':
		case 'progress':
			$status = '<button type="button" class="btn btn-primary" style="pointer-events:none;background-color:#19B6ED"><span style="text-transform:capitalize">'.$status.'</span></button></button>';
			break;
		case 'tested-rejected' :
		case 'rejected':
			$status = '<button type="button" class="btn btn-danger" style="pointer-events:none;background-color:#f00"><span style="text-transform:capitalize">'.$status.'</span></button></button>';
			break;
		case 'tested-approved' :
		case 'approved':
			$status = '<button type="button" class="btn btn-primary" style="pointer-events:none;background-color:#3FB350"><span style="text-transform:capitalize">'.$status.'</span></button></button>';
			break;
		case 'pending':
			$status = '<button type="button" class="btn btn-warning" style="pointer-events:none;background-color:#FBB533"><span style="text-transform:capitalize">'.$status.'</span></button></button>';
			break;
		case 'assigned':
			$status = '<button type="button" class="btn btn-info" style="pointer-events:none;background-color:#687CC1"><span style="text-transform:capitalize">'.$status.'</span></button></button>';
			break;
		default:
			$status = '';
			break;
	}

	return $status;
}

function setDifficulty( $value ){
	switch ( $value ) {
		case 'normal':
			$color = 'darkgreen';
			break;
		case 'medium':
			$color = 'blueviolet';
			break;
		case 'high':
			$color = 'blue';
			break;
		case 'extremely':
			$color = 'orange';
			break;
		case 'urgent':
			$color = 'red';
			break;
		
		default:
			$color = 'black';
			break;
	}

	return $color;
}

function resetTaskType( $task_type ){
	switch($task_type){
		case '1time':
			$task_type = 'One Time Only';
			break;
		case 'daily':
			$task_type = 'Daily Update';
			break;
		case 'weekly':
			$task_type = 'Weekly Update';
			break;
		case 'monthly':
			$task_type = 'Monthly Update';
			break;
		case 'yearly':
			$task_type = 'Yearly Update';
			break;
		default:
			$task_type = '-';
			break;
	}

	return $task_type;
}

function getDepartmentName( $department_id ){
	global $mysqli;

	$mysqli_department = $mysqli->query("SELECT b.department_desc FROM setting_department a
						                 LEFT JOIN setting_department_translation b ON ( a.department_id = b.department_id ) 
						                 WHERE a.deleted_at IS NULL AND b.lang = 'en' AND a.department_id = '".$department_id."'");
	$row_department = $mysqli_department->fetch_assoc();
	$department_name = $row_department['department_desc'];

	return $department_name;
}

function getStaffName( $staff_id ){
	global $mysqli;

	$staff_name       = '' ;

	$mysqli_staff     = $mysqli->query("SELECT staff_name, staff_idno FROM staff WHERE staff_id = '".$staff_id."' LIMIT 1") ;
	if ( $mysqli_staff->num_rows > 0 ){
		$row_staff    = $mysqli_staff->fetch_assoc() ;
		$staff_name   = dataFilter( $row_staff['staff_name'] ) . ' ('.$row_staff['staff_idno'].')' ;
	}

	return $staff_name;
}

function getStaffPoint( $staff_id ){
	global $mysqli ;

	$select       = $mysqli->query( "SELECT balance FROM staff_point_movement
								     WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' ORDER BY movement_id DESC LIMIT 1" ) ;
	$balance      = 0 ;
	if ( $select->num_rows > 0 ){
		$row      = $select->fetch_assoc() ;
		$balance  = $row['balance'] ;
	}

	return $balance ;
}

function pointMovement( $from_table, $from_id, $type, $difficulty, $staff_id, $amount, $remark ){
	global $mysqli ;

	$result 		  = false ;

	$select           = $mysqli->query( "SELECT point_id, point_value FROM setting_point
							             WHERE deleted_at IS NULL AND point_from = '".$from_table."' AND point_type = '".$type."' AND difficulty = '".$difficulty."' LIMIT 1" ) ;

	if ( $select->num_rows > 0 ){

		$select_staff = $mysqli->query( "SELECT staff_point_achievement, staff_point FROM staff a
										 WHERE a.deleted_at IS NULL AND a.staff_id = '".$staff_id."' AND ( a.staff_date_resigned >= '".date("Y-m-d",time())."' OR a.staff_date_resigned = '0000-00-00' OR a.staff_date_resigned IS NULL ) LIMIT 1" ) ;


		if ( $select_staff->num_rows > 0 ){

			$staff 		  = $select_staff->fetch_assoc() ;

			$row_select   = $select->fetch_assoc() ;
			$reference_id = $row_select['point_id'] ;
			$amount       = ( $row_select['point_value'] + $amount ) ;

			if ( $amount < 0 || $amount > 0 ){

				// set staff point
				$select       = $mysqli->query( "SELECT balance FROM staff_point_movement
										         WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' ORDER BY movement_id DESC LIMIT 1" ) ;
				$before       = 0 ;
				if ( $select->num_rows > 0 ){
					$row      = $select->fetch_assoc() ;
					$before   = $row['balance'] ;
				}

				// if ( $before == $staff['staff_point'] ){

					$balance  = ( $before + $amount ) ;

					$mysqli->query( "INSERT INTO staff_point_movement
									 ( staff_id, reference_id, from_table, from_id, before_amount, amount, balance, remark ) VALUES
									 ( '".$staff_id."', '".$reference_id."', '".$from_table."', '".$from_id."', '".$before."', '".$amount."', '".$balance."', '".$remark."' )" ) ;





					// set staff star
					$update_query   		= '' ;
					$staff_star 		    = 0 ;
					$point_achievement      = $staff['staff_point_achievement'] ;
					$list_allow_achievement = [ 'hr', 'task', 'adjustment' ] ;

					if ( in_array( $from_table, $list_allow_achievement ) ){
						$point_achievement  = ( $point_achievement + $amount ) ;
						$point_achievement2 = $point_achievement ;

						// check current start get
						$boolean_achievement    		 = true ;
						if ( $point_achievement2 		>= 50 ){
							while ( $boolean_achievement ){
								$staff_star             += 0.5 ;
								$point_achievement2     -= 50 ;

								if ( $point_achievement2 < 50 ){
									$boolean_achievement = false ;
								}
							}
						}


						// set staff achievement
						$total_star 		    = 0 ;
						$select_monthly 	    = $mysqli->query( "SELECT SUM(staff_star) as total_star FROM staff_monthly_achievement
																   WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND reported_at LIKE '%".date('Y-')."%'" ) ;

						if ( $select_monthly->num_rows > 0 ){
							$row_monthly 		= $select_monthly->fetch_assoc() ;
							$total_star 		= ( $row_monthly['total_star'] != null ? $row_monthly['total_star'] : 0 ) ;
						}

						$total_star  		    = ( $total_star + $staff_star ) ;
						$staff_achievement      = 'beginner' ;

						// get profile achievement
						$select_achievement     = $mysqli->query( "SELECT code, star_from, star_to FROM profile_achievement WHERE deleted_at IS NULL" ) ;
						if ( $select_achievement->num_rows > 0 ){
							while ( $row_achievement = $select_achievement->fetch_assoc() ){
								if ( $total_star    >= $row_achievement['star_from'] && $total_star < $row_achievement['star_to'] ){
									$staff_achievement  = $row_achievement['code'] ;
								}
							}
						}

						$update_query 			= "
						staff_point_achievement = '".$point_achievement."',
						staff_star 		        = '".$staff_star."',
						staff_achievement       = '".$staff_achievement."'," ;
					}

					$mysqli->query( "UPDATE staff SET 
									 ".$update_query."
									 staff_point     = '".$balance."'
									 WHERE staff_id  = '".$staff_id."'" ) ;

					$result    = true ;

				// }
			}
		}
	}

	return $result ;
}

function walletMovement( $from_table, $from_id, $type, $difficulty, $staff_id, $amount, $remark ){
	global $mysqli ;

	$result 		  = false ;

	$select           = $mysqli->query( "SELECT wallet_id, wallet_value FROM setting_wallet
							             WHERE deleted_at IS NULL AND wallet_from = '".$from_table."' AND wallet_type = '".$type."' AND difficulty = '".$difficulty."' LIMIT 1" ) ;

	if ( $select->num_rows > 0 ){

		$select_staff = $mysqli->query( "SELECT staff_wallet FROM staff a
										 WHERE a.deleted_at IS NULL AND a.staff_id = '".$staff_id."' AND ( a.staff_date_resigned >= '".date("Y-m-d",time())."' OR a.staff_date_resigned = '0000-00-00' OR a.staff_date_resigned IS NULL ) LIMIT 1" ) ;


		if ( $select_staff->num_rows > 0 ){

			$staff 		  = $select_staff->fetch_assoc() ;

			$row_select   = $select->fetch_assoc() ;
			$reference_id = $row_select['wallet_id'] ;
			$amount       = ( $row_select['wallet_value'] + $amount ) ;

			if ( $amount < 0 || $amount > 0 ){

				// set staff wallet
				$select       = $mysqli->query( "SELECT balance FROM staff_wallet_movement
										         WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' ORDER BY movement_id DESC LIMIT 1" ) ;
				$before       = 0 ;
				if ( $select->num_rows > 0 ){
					$row      = $select->fetch_assoc() ;
					$before   = $row['balance'] ;
				}

				// if ( $before == $staff['staff_wallet'] ){

					$balance  = ( $before + $amount ) ;

					$mysqli->query( "INSERT INTO staff_wallet_movement
									 ( staff_id, reference_id, from_table, from_id, before_amount, amount, balance, remark ) VALUES
									 ( '".$staff_id."', '".$reference_id."', '".$from_table."', '".$from_id."', '".$before."', '".$amount."', '".$balance."', '".$remark."' )" ) ;

					$mysqli->query( "UPDATE staff SET 
									 staff_wallet    = '".$balance."'
									 WHERE staff_id  = '".$staff_id."'" ) ;

					$result    = true ;

				// }
			}
		}
	}

	return $result ;
}

function call( $type, $host, $method, $path, $params, $more_curl = [], $port = '443', $connectTimeout = 0 ){

	switch ( $type ){
		case 'curl' :
		case 'curl-gzip' :

			$curl    = curl_init() ;
			curl_setopt_array( $curl, array(
			  CURLOPT_URL 				=> $host,
			  CURLOPT_RETURNTRANSFER 	=> true,
			  CURLOPT_MAXREDIRS 		=> 10,
			  CURLOPT_TIMEOUT 			=> $connectTimeout,
			  CURLOPT_FOLLOWLOCATION 	=> true,
			  CURLOPT_HTTP_VERSION 		=> CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST 	=> $method,
			  CURLOPT_POSTFIELDS 		=> http_build_query($params),
			  CURLOPT_HTTPHEADER 		=> $path,
			  CURLOPT_ENCODING  		=> 'gzip'
			) + $more_curl ) ;

			$response = curl_exec($curl) ;
		    $result   = json_decode( $response, true ) ;
			curl_close($curl) ;

			return $result ;

		break ;
		case 'curl-json' :
			$path[]  = 'Content-Type:application/json' ;

			$curl    = curl_init() ;
			curl_setopt_array( $curl, array(
			  CURLOPT_URL 				=> $host,
			  CURLOPT_RETURNTRANSFER 	=> true,
			  CURLOPT_MAXREDIRS 		=> 10,
			  CURLOPT_TIMEOUT 			=> $connectTimeout,
			  CURLOPT_FOLLOWLOCATION 	=> true,
			  CURLOPT_HTTP_VERSION 		=> CURL_HTTP_VERSION_1_1,
			  CURLOPT_CUSTOMREQUEST 	=> $method,
			  CURLOPT_POSTFIELDS 		=> json_encode( $params ),
			  CURLOPT_HTTPHEADER 		=> $path,
			  CURLOPT_ENCODING  		=> 'gzip'
			) + $more_curl ) ;

			$response = curl_exec($curl) ;
			$result   = json_decode( $response, true ) ;
			curl_close($curl) ;

			return $result ;

		break ;
		case 'file-contents' : 

			$status    = '200' ;
			$message   = '' ;
			$data      = [] ;

			$params    = http_build_query($params) ;
			$opts      = [] ;

			if ( $method == 'POST' ){
				$opts    = array('http' =>
				    array(
				        'method'  => $method,
				        'header'  => 'Content-Type: application/x-www-form-urlencoded',
				        'content' => $params
				    )
				) ;
			}else{
				$host .= '?'.$params ;
			}

			$context   = stream_context_create($opts) ;
			$result    = file_get_contents( $host, false, $context ) ;
			$data      = json_decode( $result, true ) ;
			
			return [
				'status'  => $status,
				'message' => $message,
				'data'    => $data
			] ;

		break ;
		case 'no-response' : 

			$status  = '500' ;
			$message = '' ;
			$data    = [] ;

			$host    = str_replace( [ 'http://', 'https://', 'www.' ], '', $host ) ;
			$server  = str_replace( '/', '', $host ) ;
			$params  = http_build_query($params) ;

			if ( $port == '443' ){ $server = 'ssl://'.$server ; }

			$fp      = fsockopen( $server, $port, $errorCode, $errorInfo, $connectTimeout ) ;

			if ( !$fp ) {
			    $message = $errorInfo . ' ( '.$errorCode.' )' ;
			} else {

				$http .= "$method $path HTTP/1.1\r\n" ;
				$http .= "Host: $host\r\n" ;
				$http .= "Content-type: application/x-www-form-urlencoded\r\n" ;
				$http .= "Content-length: ".strlen($params)."\r\n" ;
				$http .= "Connection: close\r\n\r\n" ;
				$http .= $params."\r\n\r\n" ;

				if ( fputs( $fp, $http ) === false ){
					$message = 'Request failed.' ;
				}else{
					$status  = '200' ;
		        	$message = 'Success' ;

		        	while (!feof($fp)) {
				        $data[] = fgets( $fp, 128 ) ;
				    }
				}

				fclose($fp) ;
			}

			return [
				'status'  => $status,
				'message' => $message,
				'data'    => $data
			] ;

		break ;
	}
}

function showMessage( $status, $message ){
	$script = '' ;
	if ( checkExists($status) ){

		if ( $status <= '200' ){
			$script .= 'toastr.success("'.$message[$status].'") ;' ;
		}else{
			$script .= 'toastr.error("'.$message[$status].'") ;' ;
		}

		$script = '$(function(){ '.$script.' }) ;' ;

		unset($_SESSION['error']) ;
	}
	return $script ;
}

function setSecret( $value ){
	return md5( COMPANY . $value . SECRETKEY ) ;
}

function json_return( $status, $data = [] ){
	return [
		'status'  => $status,
		'data'    => $data
	] ;
}



function saveLog( $file, $name, $request, $response ){

	$path         = __DIR__ . '/../logs/' ;

	$year_folder  = $path . date('Y', time()) . '/' ;
	$month_folder = $year_folder . date('m', time()) . '/' ;
	$day_folder   = $month_folder . date('d', time()) . '/' ;

	if ( !file_exists($year_folder) ){ mkdir($year_folder, 0751) ; }
	if ( !file_exists($month_folder) ){ mkdir($month_folder, 0751) ; }
	if ( !file_exists($day_folder) ){ mkdir($day_folder, 0751) ; }

	$file_name    = $day_folder . date('H') . '-' . $file . '.txt' ;
	if ( file_exists($file_name) ) { 
		$fh = fopen($file_name, 'a') ; 
	} else { 
		$fh = fopen($file_name, 'w') ; 
	}

	$log          = '=====================================' . "\r\n" .
					'CALL       ::: ' . $name . "\r\n" .
					'URL        ::: ' . $_SERVER["REQUEST_URI"] . "\r\n" .
					'TIME START ::: ' . TODAYDATE."\r\n" .
					'TIME END   ::: ' . date('Y-m-d H:i:s', time()) . "\r\n" .
					'REQUEST    ::: ' . json_encode($request) . "\r\n" .
					'RESPONSE   ::: ' . json_encode($response) . "\r\n" .
					'=====================================' . "\r\n\r\n\r\n\r\n\r\n" ;
	fwrite( $fh, $log ) ;
	fclose( $fh ) ;

	// fwrite($fh, '====================================='."\r\n") ;
	// fwrite($fh, 'CALL       ::: '.$name."\r\n") ;
	// fwrite($fh, 'URL        ::: '.$_SERVER["REQUEST_URI"]."\r\n") ;
	// fwrite($fh, 'TIME START ::: '.TODAYDATE."\r\n") ;
	// fwrite($fh, 'TIME END   ::: '.date('Y-m-d H:i:s', time())."\r\n") ;
	// fwrite($fh, 'REQUEST    ::: '.json_encode($request)."\r\n") ;
	// fwrite($fh, 'RESPONSE   ::: '.json_encode($response)."\r\n") ;
	// fwrite($fh, '====================================='."\r\n\r\n\r\n\r\n\r\n") ;
	// fclose($fh) ;
	
}












function getTaskRelatedStaff( $task_id, $created_by, $assigned_by ){
	global $mysqli ;

	$push_staffid[$created_by]  = $created_by ;
	$push_staffid[$assigned_by] = $assigned_by ;

	$select = $mysqli->query( "SELECT * FROM task_joinstaff
							   WHERE task_id = '".$task_id."'" ) ;
	if ( $select->num_rows > 0 ){
		while ( $row = $select->fetch_assoc() ){
			$push_staffid[$row['staff_id']] = $row['staff_id'] ;
		}
	}

	return $push_staffid ;
}

function getMonthlyAchievement( $year, $staff_id ){
	global $mysqli ;

	$list             = [] ;
	for ( $a = 1 ; $a <= 12 ; $a++ ){
		$month        = strPad(2, $a) ;
		$reported_at  = date( 'Y-m-d', strtotime( $year.'-'.$month.'-01' ) ) ;
		$list[$month] = [
			'reported_at'   		  => $reported_at,
			'staff_point_achievement' => 0,
			'staff_star'  			  => 0,
			'staff_achievement'  	  => 0
		] ;
	}

	$select               = $mysqli->query( "SELECT reported_at, staff_point_achievement, staff_star, staff_achievement FROM staff_monthly_achievement
			              				    WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND reported_at LIKE '%".$year."-%'
					     		   		    ORDER BY created_at ASC" ) ;
	if ( $select->num_rows > 0 ){
		while ( $row      = $select->fetch_assoc() ){
			$month        = date( 'm', strtotime( $row['reported_at'] ) ) ;
			$list[$month] = $row ;
		}
	}

	return $list ;
}


function sendEmail( $to, $from, $title, $body ){
    $header = 'From: "'.$from.'" <'.$from .'>'.PHP_EOL.
              'MIME-Version: 1.0'.PHP_EOL.
              'Content-type: text/html; charset=utf-8'.PHP_EOL.
              'Content-Transfer-Encoding: 8bit'.PHP_EOL.
              'X-Mailer: PHP/'.PHP_VERSION.PHP_EOL ; // send to owner
    mail( $to, $title, $body, $header ) ;
}

function getWork( $type, $selected_day, $morning_in, $morning_out, $break_in, $afternoon_out, $shortbreak_in, $night_out, $working_ot_start ){

    $list_work = '00:00:00' ;
    $list_ot   = '00:00:00' ;

    if ( $type == 'normal' ){

        $total_break      = '00:00:00' ;
        $total_shortbreak = '00:00:00' ;
        $total_ot         = '00:00:00' ;

        // check last out 
        if ( $night_out == '00:00:00' ){
            $night_out = $afternoon_out ;
        }

        if ( $night_out == '00:00:00' ){
            $night_out = $morning_out ;
        }

        if ( $night_out == '00:00:00' ){
            $night_out = $morning_in ;
        }

        // get total working hours
        $start            = new DateTime($morning_in) ;
        $end              = new DateTime($night_out) ;
        $total_work       = $start->diff($end)->format('%H:%I:%S') ;

        // total break 
        if ( $morning_out != '00:00:00' && $break_in != '00:00:00' ){
            $start            = new DateTime($morning_out) ;
            $end              = new DateTime($break_in) ;
            $total_break      = $start->diff($end)->format('%H:%I:%S') ;
        }

        // total short break 
        if ( $afternoon_out != '00:00:00' && $shortbreak_in != '00:00:00' ){
            $start            = new DateTime($afternoon_out) ;
            $end              = new DateTime($shortbreak_in) ;
            $total_shortbreak = $start->diff($end)->format('%H:%I:%S') ;
        }

        // if staff no ot
        if ( $night_out > $working_ot_start ){

            // total ot
            // working_ot_start -> 19:00
            // afternoon_out    -> 18:00
            $start    = new DateTime($working_ot_start) ;
            $end      = new DateTime($night_out) ;
            $total_ot = $start->diff($end)->format('%H:%I:%S') ;

            $total_subot      = '00:00:00' ;
            if ( $morning_out > $working_ot_start && $break_in != '00:00:00' ){
                $start       = new DateTime($morning_out) ;
                $end         = new DateTime($break_in) ;
                $total_subot = $start->diff($end)->format('%H:%I:%S') ;
            }
            $total_ot = subtractTime( $total_ot, $total_subot ) ;

            $total_subot      = '00:00:00' ;
            if ( $afternoon_out > $working_ot_start && $shortbreak_in != '00:00:00' ){
                $start       = new DateTime($afternoon_out) ;
                $end         = new DateTime($shortbreak_in) ;
                $total_subot = $start->diff($end)->format('%H:%I:%S') ;
            }
            $total_ot = subtractTime( $total_ot, $total_subot ) ;
        }

        $total_ot = roundOt( $total_ot ) ;

        // count total work & ot
        $list_work = subtractTime( $total_work, $total_break ) ;
        $list_work = subtractTime( $list_work, $total_shortbreak ) ;
        $list_work = subtractTime( $list_work, $total_ot ) ;
        $list_ot   = $total_ot ;

    }

    if ( $type == 'weekend' || $type == 'holiday' ){

        $first     = '00:00:00' ;
        $second    = '00:00:00' ;
        $third     = '00:00:00' ;

        if ( $morning_in != '00:00:00' && $morning_out != '00:00:00' ){
            $start      = new DateTime($morning_in) ;
            $end        = new DateTime($morning_out) ;
            $first      = $start->diff($end)->format('%H:%I:%S') ;
        }

        if ( $break_in != '00:00:00' && $afternoon_out != '00:00:00' ){
            $start   = new DateTime($break_in) ;
            $end     = new DateTime($afternoon_out) ;
            $second  = $start->diff($end)->format('%H:%I:%S') ;
        }

        if ( $shortbreak_in != '00:00:00' && $night_out != '00:00:00' ){
            $start   = new DateTime($selected_day.' '.$shortbreak_in) ;
            $end     = new DateTime($selected_day.' '.$night_out) ;
            if ( $shortbreak_in > $night_out ){
                $end->modify('+1 day');
            }
            $third   = $start->diff($end)->format('%H:%I:%S') ;
        }

        $list_work = addTime( $first, $second ) ;
        $list_work = addTime( $list_work, $third ) ;

    }

    $total_work = addTime( $list_work, $list_ot ) ;

    return [
        'total' => $total_work,
        'work'  => $list_work,
        'ot'    => $list_ot
    ] ;
}

function roundOt( $ot ){

    $ot   = explode(':', $ot) ;
    $ot_h = $ot['0'] ;
    $ot_m = $ot['1'] ;

    if ( $ot_m < 15 ){
        $ot_m = '00' ;
    }elseif ( $ot_m < 30 ){
        $ot_m = '15' ;
    }elseif ( $ot_m < 45 ){
        $ot_m = '30' ;
    }elseif ( $ot_m < 60 ){
        $ot_m = '45' ;
    }

    return $ot_h.':'.$ot_m.':00' ;
}

function getTotalHour( $start, $end ){
    $start = new DateTime($start) ;
    $end   = new DateTime($end) ;
    return $start->diff($end)->format('%H:%I:%S') ; ;
}

function calculateAllHours( $hoursList ){

	// Initialize a DateInterval object with 0 hours
	$totalInterval = new DateInterval('PT0S');

	// Loop through the list of hours and add each one to the total
	foreach ($hoursList as $hour) {
	    list($h, $m, $s) = explode(':', $hour);
	    $totalInterval->h += (int)$h;
	    $totalInterval->i += (int)$m;
	    $totalInterval->s += (int)$s;
	}

	// Normalize the DateInterval
	$totalInterval->i += floor($totalInterval->s / 60);
	$totalInterval->s = $totalInterval->s % 60;
	$totalInterval->h += floor($totalInterval->i / 60);
	$totalInterval->i = $totalInterval->i % 60;

	// Format the total hours
	$totalHoursFormatted = $totalInterval->format('%H:%I:%S');

	// Format the total hours
	return $totalHoursFormatted ;
}

function getRest( $morning_out, $break_in, $afternoon_out, $shortbreak_in ){

    $list_rest = '00:00:00' ;

    if ( $morning_out != '00:00:00' && $break_in != '00:00:00' ){
        $start      = new DateTime($morning_out) ;
        $end        = new DateTime($break_in) ;
        $list_rest  = $start->diff($end)->format('%H:%I:%S') ;
    }

    if ( $afternoon_out != '00:00:00' && $shortbreak_in != '00:00:00' ){
        $start      = new DateTime($afternoon_out) ;
        $end        = new DateTime($shortbreak_in) ;
        $list_rest2 = $start->diff($end)->format('%H:%I:%S') ;
        $list_rest  = addTime( $list_rest, $list_rest2 ) ;
    }
    return $list_rest ;
}

function getLate( $list_late, $break, $working, $check_out, $check_in ){

    // get break hours
    if ( $break != '00:00:00' && $working != '00:00:00' ){
        
        // get working break hours
        $start             = new DateTime($break) ;
        $end               = new DateTime($working) ;
        $get_working_break = $start->diff($end)->format('%H:%I:%S') ;
        $get_check_break   = '00:00:00' ;

        if ( $check_out != '00:00:00' && $check_in != '00:00:00' ){
            // get check in & out break hours
            $start           = new DateTime($check_out) ;
            $end             = new DateTime($check_in) ;
            $get_check_break = $start->diff($end)->format('%H:%I:%S') ;
        }

        // check if late
        $get_working_break = date('H:i:s', strtotime($get_working_break.' +5 minutes')) ;
        if ( $get_check_break > $get_working_break ){
            $start             = new DateTime($get_check_break) ;
            $end               = new DateTime($get_working_break) ;
            $get_working_break = $start->diff($end)->format('%H:%I:%S') ;
            $list_late         = addTime( $list_late, $get_working_break ) ;
        }
    }

    $list_late = date('H:i', strtotime($list_late)) ;
    return $list_late ;
}

function addTime( $start, $end ){

    // explode
    $end      = strtotime($end) ;
    $hours    = date('H', $end) ;
    $minutes  = date('i', $end) ;
    $seconds  = date('s', $end) ;
    $interval = 'PT'.$hours.'H'.$minutes.'M'.$seconds.'S' ; // P开头代表日期, T=时间, Y=Year...，Sample : P2Y4DT6H8M

    $start    = new DateTime($start) ;
    $start    = $start->add( new DateInterval($interval) ) ;
    $start    = $start->format('H:i:s') ;
    return $start ;
}

function subtractTime( $start, $end ){

    // explode
    $end      = strtotime($end) ;
    $hours    = date('H', $end) ;
    $minutes  = date('i', $end) ;
    $seconds  = date('s', $end) ;
    $interval = 'PT'.$hours.'H'.$minutes.'M'.$seconds.'S' ; // P开头代表日期, T=时间, Y=Year...，Sample : P2Y4DT6H8M

    $start    = new DateTime($start) ;
    $start    = $start->sub( new DateInterval($interval) ) ;
    $start    = $start->format('H:i:s') ;
    return $start ;
}














function getTotalMonth( $date1, $date2 ){
	$ts1    = strtotime( $date1 ) ;
	$ts2    = strtotime( $date2 ) ;

	$year1  = date( 'Y', $ts1 ) ;
	$year2  = date( 'Y', $ts2 ) ;

	$month1 = date( 'm', $ts1 ) ;
	$month2 = date( 'm', $ts2 ) ;

	$diff   = ( ( $year2 - $year1 ) * 12 ) + ( $month2 - $month1 ) ;
	return $diff ;
}




function setStaffLeaveYear($staff_id){
	global $mysqli ;
		
	// check if staff exists or not
	$get_staff = $mysqli->query("SELECT staff_date_joined, staff_date_confirmed, leave_id, sick_id, job_status_id FROM staff
								 WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' LIMIT 1") ;
	if ( $get_staff->num_rows > 0 ){

		$staff 		   	      = $get_staff->fetch_assoc() ;

		$staff_date_joined    = $staff['staff_date_joined'] ;
		$staff_date_confirmed = $staff['staff_date_confirmed'] ;
		$job_status_id  	  = $staff['job_status_id'] ; 
		$date_joined_month    = 0 ;

		// default setting
		$current_year 		  = date( 'Y', strtotime(TODAYDATE) ) ;
    	$current_month  	  = date( 'm', strtotime(TODAYDATE) ) ;
		$given_date  		  = $current_year.'-'.$current_month.'-01' ;

		$divide_month  		  = '' ;
		switch ( LEAVESETTING ){
			case 'quaterly' :
				switch ( $current_month ){
					case 1  :
						$divide_month = 3 ;
					break   ;
					case 4  :
						$divide_month = 6 ;
					break   ;
					case 7  :
						$divide_month = 9 ;
					break   ;
					case 10 :
						$divide_month = 12 ;
					break   ;
				}
			break ;
			case 'month'    :
			default 		:
				$divide_month = $current_month ;
		}

		if ( $staff_date_joined != null && $staff_date_joined != '0000-00-00' ){


			// insert into list, check if exsits
			// for unpaid leave
	    	$unpaid_days      = 365 ;
	    	$get_leave_year   = $mysqli->query("SELECT leave_year_id FROM staff_leave_year
	    									    WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND leave_type = 'unpaid' AND leave_year = '".$current_year."' LIMIT 1") ;
	    	if ( $get_leave_year->num_rows == 0 ){
	    		$mysqli->query("INSERT INTO staff_leave_year
	    						(staff_id, leave_type, leave_year, leave_year_from, leave_year_to, leave_record_days, leave_given_days, leave_days, created_at, updated_at) VALUES
	    						('".$staff_id."', 'unpaid', '".$current_year."', '".$current_year."-01-01', '".$current_year."-12-31', '".$unpaid_days."', '".$unpaid_days."', '".$unpaid_days."', '".TODAYDATE."', '".TODAYDATE."')") ;
	    	}









	    	// insert into list, check if exsits
	    	// sick leave
	    	$date_joined_year 	= date('Y', strtotime($staff_date_joined)) ;
			$date_joined_first 	= $current_year.'-01-01' ;

			if ( $date_joined_first > $staff_date_joined ){
				$date_joined_end = $date_joined_first ;
			}else{
				$date_joined_end = $staff_date_joined ;
			}

			$date_joined_month  = getTotalMonth( $staff_date_joined, $date_joined_end ) ;

	    	// sick
	    	$sick_days   		= 0 ;
			if ( $staff['sick_id'] != '0' ){
				$get_sick = $mysqli->query("SELECT sick_rules FROM setting_sick
											WHERE sick_id = '".$staff['sick_id']."' LIMIT 1") ;
	    		if ( $get_sick->num_rows > 0 ){
	    			$row_sick  = $get_sick->fetch_assoc() ;
	    			$sick_rules = jsonEncodeDecode('decode', $row_sick['sick_rules']) ;
	    			if ( is_array($sick_rules) ){
	    				foreach ( $sick_rules as $value ){
	    					if ( $date_joined_month >= $value['more_from'] && $date_joined_month < $value['more_to'] ){
	    						$sick_days = $value['more_days'] ;
	    					}
	    				}
	    			}
	    		}
	    	}

	    	// update into db
	    	$get_sick_year = $mysqli->query("SELECT leave_year_id FROM staff_leave_year
	    									 WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND leave_type = 'sick' AND leave_year = '".$current_year."' LIMIT 1") ;
	    	if ( $get_sick_year->num_rows == 0 ){
	    		$mysqli->query("INSERT INTO staff_leave_year
	    						(staff_id, leave_type, leave_year, leave_year_from, leave_year_to, leave_record_days, leave_given_days, leave_days, created_at, updated_at) VALUES
	    						('".$staff_id."', 'sick', '".$current_year."', '".$current_year."-01-01', '".$current_year."-12-31', '".$sick_days."', '".$sick_days."', '".$sick_days."', '".TODAYDATE."', '".TODAYDATE."')") ;
	    	}


	    	// 1 = confirmed
			// 2 = under probation
			// 3 = training / internship
			if ( $job_status_id == '1' && ( $staff_date_confirmed != null && $staff_date_confirmed != '0000-00-00' ) ){

		    	// insert into list, check if exsits
		    	// annual leave
		    	$date_joined_from 	 = $current_year.'-01-01' ;
				$date_joined_to      = $current_year.'-12-31' ;

				if ( $date_joined_from > $staff_date_joined ){
					$date_joined_end = $date_joined_from ;
				}else{
					$date_joined_end = $staff_date_joined ;
				}

				$date_joined_month     = getTotalMonth( $staff_date_joined, $date_joined_end ) ;
				$date_joined_realmonth = getTotalMonth( $staff_date_joined, TODAYDATE ) ;

				if ( LEAVEMONTHTYPE   == '2' ){
					$date_joined_month = $date_joined_realmonth ;
				}

				$annual_days 		   = 0 ;
				$more_give_days        = 0 ;

				// annual
				if ( $staff['leave_id'] != '0' ){
					$get_annual        = $mysqli->query("SELECT leave_rules FROM setting_leave
												         WHERE leave_id = '".$staff['leave_id']."' LIMIT 1") ;
		    		if ( $get_annual->num_rows > 0 ){
		    			$row_annual    = $get_annual->fetch_assoc() ;
		    			$annual_rules  = jsonEncodeDecode('decode', $row_annual['leave_rules']) ;

		    			if ( is_array($annual_rules) ){
		    				foreach ( $annual_rules as $value ){
		    					if ( $date_joined_month >= $value['more_from'] && $date_joined_month < $value['more_to'] ){

		    						$current_minus_month   = ( $current_month - 1 ) ;
		    						$default_given_day     = 0 ;
		    						if ( $current_minus_month > 0 ){
		    							$default_given_day = numberFormat( ( $value['more_days'] / 12 * $current_minus_month ) , 2 ) ;

		    							$default_given_day = ( numberFormat( ( $value['more_days'] / 12 * $current_minus_month ) , 2 ) - $total_leave_month ) ;
		    						}

		    						$days 				   = 0 ;
						    		$boolean_day 		   = true ;
						    		while ( $boolean_day ){
						    			if ( $default_given_day   >= 1  ){
						    				$default_given_day    -= 1 ;
						    				$days++ ;
						    			}else{
						    				$boolean_day   = false ;
						    			}
						    		}

		    						$annual_days    = ( $value['more_days'] - $days ) ;
		    						$more_give_days = $value['more_days'] ;
		    					}
		    				}
		    			}
		    		}
		    	}

		    	// insert into list, check if exsits
		    	$get_leave_year = $mysqli->query("SELECT leave_year_id, leave_record_days FROM staff_leave_year
		    									  WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND leave_type = 'annual' AND leave_year = '".$current_year."' LIMIT 1") ;
		    	if ( $get_leave_year->num_rows == 0 ){
		    		$mysqli->query("INSERT INTO staff_leave_year
		    						(staff_id, leave_type, leave_year, leave_year_from, leave_year_to, leave_record_days, leave_given_days, leave_days, created_at, updated_at) VALUES
		    						('".$staff_id."', 'annual', '".$current_year."', '".$date_joined_from."', '".$date_joined_to."', '".$annual_days."', '0', '0', '".TODAYDATE."', '".TODAYDATE."')") ;
		    	}else{
		    		if ( ( $date_joined_realmonth - 12 ) > 0 && ( $date_joined_realmonth - 12 ) < 12 ){
		    			$row_leave_year = $get_leave_year->fetch_assoc() ;

		    			$mysqli->query("UPDATE staff_leave_year SET
		    						    leave_record_days   = '".$more_give_days."',
		    						    leave_yearup        = '1'
		    						    WHERE leave_year_id = '".$row_leave_year['leave_year_id']."' AND leave_yearup = '0'") ;
		    		}
		    	}



		    	// monthly given annual leave days
		    	$get_leave_year = $mysqli->query("SELECT leave_year_id, leave_record_days FROM staff_leave_year
		    									  WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND leave_type = 'annual' AND leave_year = '".$current_year."' LIMIT 1") ;
		    	if ( $get_leave_year->num_rows > 0 ){
		    		$row_leave_year        = $get_leave_year->fetch_assoc() ;

		    		if ( $divide_month    != '' ){
		    			$get_leave_month   = $mysqli->query( "SELECT * FROM staff_leave_month
			    						   				      WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND leave_year_id = '".$row_leave_year['leave_year_id']."' AND given_month = '".$current_month."' LIMIT 1" ) ;
			    		if ( $get_leave_month->num_rows == 0 ){

			    			$get_total_leave_month = $mysqli->query( "SELECT SUM(given_day) as total FROM staff_leave_month
				    						  	  				      WHERE deleted_at IS NULL AND staff_id = '".$staff_id."' AND leave_year_id = '".$row_leave_year['leave_year_id']."' AND given_month <= '".$current_month."'" ) ;

				    		$row_total_leave_month = $get_total_leave_month->fetch_assoc() ;
				    		$total_leave_month     = $row_total_leave_month['total'] ;
				    		$balance_leave_month   = ( $row_leave_year['leave_record_days'] - $total_leave_month ) ;

				    		// check month setting, by month or by quaterly
				    		$given_day     		   = ( numberFormat( ( $row_leave_year['leave_record_days'] / 12 * $divide_month ) , 2 ) - $total_leave_month ) ;

				    		$days 				   = 0 ;
				    		$boolean_day 		   = true ;
				    		while ( $boolean_day ){
				    			if ( $given_day   >= 1  ){
				    				$given_day    -= 1 ;
				    				$days++ ;
				    			}else{
				    				$boolean_day   = false ;
				    			}
				    		}

				    		$mysqli->query( "INSERT INTO staff_leave_month
				    						 ( leave_year_id, staff_id, given_month, given_day, given_date ) VALUES
				    						 ( '".$row_leave_year['leave_year_id']."', '".$staff_id."', '".$current_month."', '".$days."', '".$given_date."'  )" ) ;

				    		if ( $days > 0 ){
				    			$mysqli->query( "UPDATE staff_leave_year SET
				    						 	 leave_given_days    = leave_given_days + ".$days.",
				    							 leave_days 		 = leave_days + ".$days."
				    							 WHERE leave_year_id = '".$row_leave_year['leave_year_id']."'" ) ;
				    		}


			    		}
		    		}

		    	}
		    }
		}
	}
}











function getCurrentCountry(){
	$myip 		= '' ;
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $myip = $_SERVER['HTTP_CLIENT_IP'] ;
    }
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $myip = $_SERVER['HTTP_X_FORWARDED_FOR'] ;
    }
    else {
        $myip = $_SERVER['REMOTE_ADDR'] ;
    }
	  
	$curl    = curl_init() ;
	curl_setopt_array($curl, array(
	  CURLOPT_URL => 'http://www.geoplugin.net/json.gp?ip=' . $myip,
	  CURLOPT_RETURNTRANSFER => true,
	  CURLOPT_ENCODING => '',
	  CURLOPT_MAXREDIRS => 10,
	  CURLOPT_TIMEOUT => 0,
	  CURLOPT_FOLLOWLOCATION => true,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => 'GET',
	));
	$response = curl_exec($curl);
	curl_close($curl) ;
	
	return json_decode( $response, true ) ;
}










function showTabs( $table, $key, $id, $list ){
	global $mysqli, $LANGS, $lang ;

	$lang_content = [] ;

	if ( $id     != '' ){
		$select   = $mysqli->query( "SELECT * FROM " . $table . " WHERE ".$key." = '".$id."'" ) ;
		if ( $select->num_rows > 0 ){
			while ( $row = $select->fetch_assoc() ){
				foreach ( $list as $klist => $vlist ){
					$lang_content[$row['lang']][$klist] = $row[$klist] ;
				}
			}
		}
	}


	$html = '
	<div id="tabs" style="margin-top:30px; margin-bottom:30px;">

		<ul>' ;
			foreach ( $LANGS as $klang => $vlang ){ $html .= '<li><a href="#tabs-'.$klang.'">'.$vlang.'</a></li>' ; }
		$html .= '
		</ul>' ;

		foreach ( $LANGS as $klang => $vlang ){ 
			$html .= '
			<div id="tabs-'.$klang.'">' ;
					
				foreach ( $list as $klist => $vlist ){
					switch ( $vlist['type'] ){
						case 'input'   :

							$html .= '
							<div class="form-group">
	                            <div class="col-sm-2 control-label">'.$vlist['title'].'</div>
	                            <div class="col-sm-9">
	                                <input type="text" name="'.$klist.'_'.$klang.'" class="form-control ui-search-input" value="'.dataFilter( $lang_content[$klang][$klist] ).'" placeholder="'.$vlist['title'].'" />
	                            </div>
	                        </div>' ;

						break ;
						case 'textarea' :

							$html .= '
							<div class="form-group">
			                    <div class="col-sm-2 control-label">'.$vlist['title'].'</div>
			                    <div class="col-sm-9">
			                        <textarea name="'.$klist.'_'.$klang.'" class="content" id="editor_'.$klang.'" rows="10" cols="80">'.dataFilter( $lang_content[$klang][$klist] ).'</textarea>
			                        <script>CKEDITOR.replace(\'editor_'.$klang.'\') ;</script>
			                    </div>
			                </div>' ;

						break ;
						case 'file' :

							$html .= '
							<div class="form-group">
	                            <div class="col-sm-2 control-label">'.$vlist['title'].'</div>
	                            <div class="col-sm-9">
	                                <div class="file_upload">
	                                    <div class="file_form">
	                                        <input type="hidden" name="remove_photo_'.$klang.'" value="" />
	                                        <input type="file" name="'.$klist.'_'.$klang.'" class="file_button control-label" />
	                                    </div>
	                                </div>
	                                '.( $vlist['size'] != '' ? '<font color="red">'.$vlist['size'].'</font>' : '' ).'
	                            </div>
	                        </div>' ;
	                        
	                        if ( $lang_content[$klang][$klist] != '' ){
	                        	$html .= '
		                        <div class="form-group form-group-pdf">
		                            <div class="col-sm-2 control-label">'.$lang['preview'].'</div>
		                            <div class="col-sm-9">
		                            	<label class="remove_photo">
		                            		<input type="checkbox" name="remove_photo_'.$klang.'" class="ui-checkbox tick" value="1" />&nbsp;'.$lang['Remove File'].'
		                            	</label>
		                            	<a href="'.PATH.'uploads/'.$vlist['folder'].'/'.dataFilter( $lang_content[$klang][$klist] ).'" target="_blank">
		                            		<img src="'.PATH.'uploads/'.$vlist['folder'].'/'.dataFilter( $lang_content[$klang][$klist] ).'" style="width:100px;" />
		                            	</a>
			                        </div>
		                        </div>' ;
	                        }else{
	                       		$html .= '<input type="hidden" name="remove_photo_'.$klang.'" value="" />' ;
	                        }

						break ;
					}
				}

			$html .= '
			</div>' ; 
		}

		$html .= '
	</div>' ;

	return $html ;
}

function checkLangUpdate( $table, $key, $id, $lang, $list ){
	global $mysqli ;

	$select = $mysqli->query( "SELECT * FROM ".$table." WHERE ".$key." = '".$id."' AND lang = '".$lang."' LIMIT 1" ) ;

	// only query only
	if ( $select->num_rows      > 0 ){

		$query_update           = [] ;
		foreach ( $list as $k   => $v ){
			if ( $v['type']    != 'file' ){
				$query_update[] = $k . " = '" . $v['value'] . "'" ;
			}
		}

		$mysqli->query( "UPDATE ".$table." SET
						 ".implode(',', $query_update)."
						 WHERE ".$key." = '".$id."' AND lang = '".$lang."'" ) ;

	}else{

		$query_key              = '' ;
		$query_value            = '' ;
		foreach ( $list as $k => $v ){
			if ( $v['type']    != 'file' ){
				$query_key     .= ", " . $k ;
				$query_value   .= ", '" . $v['value'] . "'" ;
			}
		}

		$mysqli->query( "INSERT INTO ".$table."
						 ( ".$key.", lang ".$query_key." ) VALUES
						 ( '".$id."', '".$lang."' ".$query_value." )" ) ;

	}

	// upload file only
	foreach ( $list as $k         => $v ){
		if ( $v['type']           == 'file' ){

			$image 		  		   = $v['value']["name"] ;
			$remove_photo 		   = $v['remove_photo'] ;

			if ( $remove_photo    == 1 ){
				$mysqli->query( "UPDATE ".$table." SET
								 ".$k." = ''
								 WHERE ".$key." = '".$id."' AND lang = '".$lang."'" ) ;
			}else{

				if ( $image   	   != '' ){
					$get_image 	    = pathinfo($image) ;
					$create_image   = reCreateImage( $v['folder'], $lang, $id, '', $image, $v['value']['type'], $v['value']['tmp_name'] ) ;

					if ( $create_image['result'] && is_array($create_image['crop']) && count($create_image['result']) > 0 ){
						$resizeObj  = new resize($create_image['original']) ; // Initialise load image
						foreach( $create_image['crop'] as $value ){
							$resizeObj -> resizeImage($value['width'], $value['height'], $value['type']) ;
							$resizeObj -> saveImage($value['source'], 70) ; // Save image	
						}
						$get_image   = pathinfo($create_image['image']) ;

						$mysqli->query( "UPDATE ".$table." SET
										 ".$k." = '".$create_image['image']."'
										 WHERE ".$key." = '".$id."' AND lang = '".$lang."'" ) ;

					}
				}

			}

		}
	}
}

function uploadImageBased64($path, $file_name, $source, $file_type = ''){

	$result = false ;
	// $s = $_SERVER["DOCUMENT_ROOT"].'/Uploads/'.$path.'/'.$file_name ;

	$b = $_SERVER["DOCUMENT_ROOT"].'/uploads/'.$path.'/'.$file_name ;

	$data = explode( ',', $source );

	$file = fopen($b, "wb"); //(you can put jpg, png or any other extension)

	fwrite($file, base64_decode($data[1]));

	fclose($file);

	// check file size
	if(filesize($b) > 0){
		$result = true;
	}
	
	return $result ;
}

function fromExcelToLinux($excel_time) {
    return date( 'Y-m-d', ($excel_time-25569)*86400 ) ;
}

function mergeImageWithContent ( $file, $content ){
	$html 		= '
	<!DOCTYPE html>
	<html lang="en">
	<head>
		<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
	</head>
	<body>
		'.( $file != '' ? '<img src="'.$file.'" style="width:100%; margin-bottom:20px;" />' : '' ).'
		'.$content.'
	</body>
	</html>' ;

	return $html ;
}

function resetGetParams( $parameter, $filterout ){
	$param 		 = '' ;
	foreach ( $parameter as $k => $v ){
		if ( $v != '' ){
			if ( !in_array( $k, $filterout ) ){
				$param .= '&'.$k.'='.$v ;
			}
		}
	}

	return $param ;
}

function calculateTax($type, $salary, $category, $category2){
	global $mysqli;
	include '../read_csv.php';
	return $tax;
}

function calculateTaxEPF($type, $salary, $age, $citizen){
	global $mysqli;
	include '../read_csv.php';
	return $tax;
}

function calculateTaxSOCSO($type, $salary, $category){
	global $mysqli;
	include '../read_csv.php';
	return $tax;
}

function calculateTaxEIS($type, $salary){
	global $mysqli;
	include '../read_csv.php';
	return $tax;
}

function calculateTaxZAKAT($salary, $rate){
	$tax = $salary * $rate / 100;
	return $tax;
}


function roundNearestRinggit($number){
	if(fmod($number, 1) !== 0.0){
		$explode = explode(".", $number);
		$return = $explode[0] + 1;
	}else{
		$return = $number;
	}
	return $return;
}

function userTierQuery( $user ){
	$tiers = [] ;
	
	if ( $user['user_tier'] != '' ){
		$temp 			  = explode( ',', $user['user_tier'] ) ;
		foreach ( $temp as $k => $v ){
			$temp_v 	  = str_replace( [ '|' ], '', $v ) ;
			$temp_v 	  = trim( $temp_v ) ;
			if ( $temp_v != '' ){
				$tiers[]  = $temp_v ;
			}
		}
	}

	if ( count($tiers)   == 0 ){
		$tiers[] 		  = -1 ;
	}

	return [
		'check'   => ( $user['user_permission'] == 'admin' ? false : true ),
		'tiers'   => $tiers
	] ;
}

function rmsCall( $api, $array ){
	$data_post            = 'POST' ;
    $data_path            = RMSAPIURL.$api ;
    $data_content         = $array ;
    $data_content_json    = json_encode( $data_content ) ;
    $data_datetime        = gmdate("Y-m-d\TH:i:s\Z") ;
    $data_terminal        = RMSAPITERMINAL ;
    $data_terminal_base64 = base64_encode($data_terminal) ;
    $data_key             = RMSAPIKEY ;

    $post_data            = $data_post . $data_path . $data_content_json . $data_datetime . $data_terminal ;
    $signature            = hash_hmac( "sha1", $post_data, RMSAPIKEY ) ;
    $signaturetobase64    = base64_encode( $signature ) ;

    $call                 = call( 'curl-json', $data_path, $data_post, [
        'Authorization: mol-req-sign '.$data_terminal_base64.':'.$signaturetobase64,
        'x-mol-date-time: '.$data_datetime
    ], $data_content ) ;

    return $call ;
}



function generateQrcode( $require_path, $qrcode, $qrcodegenerate ){
	require_once( $require_path.'plugins/phpqrcode/qrlib.php' ) ;

	$outputqrcode = $require_path.'qrcodes/'.$qrcode.'.png' ;
	QRcode::png($qrcodegenerate, $outputqrcode, 'L', 10, 1) ;

	return [
		'qrcode' => $qrcode,
		'url'    => PATH.'qrcodes/'.$qrcode.'.png',
	] ;

	// return [
	// 	'qrcode' => $qrcode,
	// 	'url'    => 'https://chart.googleapis.com/chart?chs=500x500&cht=qr&chl='.$qrcode,
	// ] ;
}
?>