<?php

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

// check array
function appArrayCheck($array){
	$result = false ;
	if ( count($array) > 0 && is_array($array) ){
		$result = true ;	
	}
	return $result ;
}

// escape string
function appEscapeString($value){
	$value = ( appCheckValue($value) ? trim(stripslashes(htmlentities($value, ENT_QUOTES, 'UTF-8'))) : '' ) ;
	return $value ;
}

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

// get my current ip
function appGetClientIP() {
    $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;
}

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

function appUserAgent($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';
    }    
}

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

function resetContent( $content ){
	
	$temp = array() ;
	
	if ( appArrayCheck($content) ){
		foreach ( $content as $key => $value ){
			
			$temp_key = str_replace( array('post_', 'customer_') , '', $key ) ;
			
			$reset = stripslashes($value) ;
			
			if ( $key == 'post_title' || $key == 'post_content' || $key == 'post_content2' ){
				$reset = explode('<!--language--!>', $reset) ;
				$reset = $reset[0] ;
				$reset = str_replace('(_%%%%%_)', '', $reset) ;
			}
			
			if ( $key = 'post_content' ){
				$reset = html_entity_decode( $reset ) ;
			}
			
			$temp[$temp_key] = $reset ;
			
		}
	}
	
	return $temp ;
}

function resetDecode( $content ){
	
	$content = unserialize(base64_decode($content)) ;
	$new_value = array() ;
	if ( appArrayCheck($content) ){
		foreach($content as $value){
			$new_value[] = $value ;
		}
	}
	
	return $new_value ;
}

function appResetDimension( $l, $w, $h ){
	
	if ( ( $l == '0' || $l == '-' ) || ( $w == '0' || $w == '-' ) || ( $h == '0' || $h == '-' ) ){
		$dimension = '' ;
	}else{
		$dimension = 'L'.$l . ' X ' . 'W'.$w . ' X ' . 'H'.$h ;
	}	
	
	return $dimension ;
}

function resetFileApp( $value ){
	
	$array = array() ;
	
	$image_link = PATH.'Images/NoProduct.jpg' ;
	$image_link_b = PATH.'Images/NoProduct.jpg' ;
	
	$image_link = PATH.'Images/NoProduct.jpg' ;
	$image_link_b = PATH.'Images/NoProduct.jpg' ;
	if ( $value != '' ){
		$array_seow = appJsonEncodeDecode( 'decode', $value ) ;
		$image_link = PATH.'Uploads/'.$array_seow['folder'].'/' ;	
		$image_link_b = $image_link.'b/'.$array_seow['image'] ;
		$image_link = $image_link.$array_seow['image'] ;
	}
	
	$array['file'] = ($image_link) ;	
	$array['file_b'] = ($image_link_b) ;	
	
	return $array ;
}

function getLastRecordPrice( $customer_id, $product ){
	global $mysqli, $prefixRecord ;
	
	$record = $mysqli->query( "SELECT record_rate_type, record_price FROM $prefixRecord
							   WHERE record_customer_id = '".$customer_id."' AND record_post_id = '".$product."' ORDER BY record_id DESC LIMIT 1" ) ;
	
	$result = 'No record.' ;
	if ( $record->num_rows > 0 ){
		$row_record = $record->fetch_assoc() ;
		$result = strtoupper($row_record['record_rate_type']).' '.$row_record['record_price'] ;
	}
	return $result ;
}

function evalmath( $equation ){
    $result = 0;
    // sanitize imput
    $equation = preg_replace("/[^a-z0-9+\-.*\/()%]/","",$equation);
    // convert alphabet to $variabel 
    $equation = preg_replace("/([a-z])+/i", "\$$0", $equation); 
    // convert percentages to decimal
    $equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
    $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
    $equation = preg_replace("/([0-9]{1})(%)/",".0\$1",$equation);
    $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
    if ( $equation != "" ){
        $result = @eval("return " . $equation . ";" );
    }
    if ($result == null) {
    	$result = 0 ;
    }
    return $result;
}

function resetPriceCode( $id, $date, $price ){
	global $mysqli, $prefixPost ;

	$code     = '' ; 
	$get_code = $mysqli->query("SELECT post_content FROM $prefixPost
			   			 	    WHERE post_type = 'page-price-code' AND post_categories = 'page-price-code' AND post_trash = '0' LIMIT 1") ;
	if ( $get_code->num_rows > 0){
		$row_code  = $get_code->fetch_assoc() ;
		$content   = appJsonEncodeDecode('decode', $row_code['post_content']) ;

		$f_to      = $content['formula_to'] ;
		$f_outcome = $content['formula_outcome'] ;

		if ( $f_to != '' ){
			$price = appNumberFormat( evalmath($price.$f_to) ) ;
		}

		$reset_price = '' ;
		for ( $i = 0 ; $i < strlen($price) ; $i++ ){
			switch ( $price[$i] ){
				case '0' : $reset_price .= $content['digit_0'] ; break ;
				case '1' : $reset_price .= $content['digit_1'] ; break ;
				case '2' : $reset_price .= $content['digit_2'] ; break ;
				case '3' : $reset_price .= $content['digit_3'] ; break ;
				case '4' : $reset_price .= $content['digit_4'] ; break ;
				case '5' : $reset_price .= $content['digit_5'] ; break ;
				case '6' : $reset_price .= $content['digit_6'] ; break ;
				case '7' : $reset_price .= $content['digit_7'] ; break ;
				case '8' : $reset_price .= $content['digit_8'] ; break ;
				case '9' : $reset_price .= $content['digit_9'] ; break ;
				case '.' : $reset_price .= $content['digit_point'] ; break ;
			}
		}

		$md5_id = strtoupper(md5(md5($id))) ;
		for ( $i = 0 ; $i < strlen($f_outcome) ; $i++ ){
			switch ( $f_outcome[$i] ){
				case '!' : $code .= substr($md5_id, 0, $content['formula_1']) ; break ;
				case '@' : $code .= date($content['formula_2'], strtotime($date)) ; break ;
				case '#' : $code .= $content['formula_3'] ; break ;
				case '$' : $code .= $reset_price ; break ;
				case '%' : $code .= appStrPad($content['formula_4'], $id) ; break ;
				default  : $code .= $f_outcome[$i] ;
			}
		}

	}
	
	return $code ;
}

// return pagination
function appNextPrevious( $mysqli, $current, $limit, $query ) {

	// get query
	$page = $mysqli->query($query) ;

	// total page
	$total = $page->num_rows ;
	$total_page = ceil( $total / $limit ) ;
	
	$array = $array_page = array() ;
	$pagination = 'no' ;
	
	// start pagination
	if ($total_page <= 1){
		
	}else{
		
		$pagination = 'yes' ;
		
		// calculating the starting and endign values for the loop
		if ( $current >= 7 ) {
			$start_loop = $current - 3 ;
			if ($total_page > $current + 3)
				$end_loop = $current + 3 ;
			else if ($current <= $total_page && $current > $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 ;
		}
		
		// previous linking
		if ($current > 1) {
			$prev = $current - 1 ;
			$array_page[] = array('word' => 'Prev', 'page' => $prev) ;
		}

		// pagination number
		for ($i = $start_loop; $i <= $end_loop; $i++) {
			$array_page[] = array('word' => $i, 'page' => $i) ;
		}
						
		// show last page
		if ($current <= ($total_page - 4)){
			$array_page[] = array('word' => 'Last', 'page' => $total_page) ;
		}
		
		// next linking
		if ($current < $total_page) {
			$next = $current + 1 ;
			$array_page[] = array('word' => 'Next', 'page' => $next) ;
		}
		
	}
	
	$array['pagination'] = $pagination ;
	$array['total'] = ($total != '' ? $total : 0) ;
	$array['navigation'] = $array_page ;
	return $array;
}

// rate price
function appRatePrice($rate_type = 'usd', $boolean_id = ''){
	global $mysqli, $prefixRate ;
	
	// query for rate
	$mysqli_rate = $mysqli->query("SELECT rate_id, rate_currency, rate_markup FROM $prefixRate
								   WHERE rate_type = '".$rate_type."'
								   ORDER BY rate_id DESC LIMIT 1") ;
	$rate = 1 ;
	
	// check if rate exsits
	if ($mysqli_rate->num_rows > 0){
		
		// set query as array
		$row_rate = $mysqli_rate->fetch_assoc() ;
		
		// set in variable
		$currency = $row_rate['rate_currency'] ;
		$markup = $row_rate['rate_markup'] ;
		
		// set rate price
		if ($boolean_id == 'id'){
			$rate = $row_rate['rate_id'] ;
		}else{
			$rate = ($rate / $currency / $markup) ;
		}
		
	}
	return $rate ;
}

// rate price rounding
function appPriceRateRounding( $amount = 0 ){
	
	// set amount to 2 decimal
	// 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 = appNumberFormat($amount) ;
	$gst_rounding = substr($amount, -2) ;
	
	// statement for rounding
	if ($gst_rounding < 1){
		$amount = substr_replace($amount, 00, -2) ;
	}elseif ($gst_rounding <= 50){
		$amount = substr_replace($amount, 50, -2) ;
	}elseif ($gst_rounding <= 99){
		$amount = substr_replace($amount, 00, -2) ;
		$amount += 1 ;
	}
	
	// set again amount to 2 decimal
	$amount = appNumberFormat($amount) ;
	
	// return result
	return $amount ;
}

// price rounding
function appPriceRounding($amount = 0){
	
	// set amount to 2 decimal
	// 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 = appNumberFormat($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 = appNumberFormat($amount) ;
	// return result
	return $amount ;
}

function random_password( $length = 8 ) {
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?" ;
	$password = substr( str_shuffle( $chars ), 0, $length ) ;
    return $password ;
}

function sendEmail( $email_from, $email_to, $title, $body ){
	// put your email address here
	$header = 'From: "'.$email_from.'" <'.$email_from .'>'.PHP_EOL.
			  'Bcc: "'.$email_from.'" <'.$email_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( $email_to, $title, $body, $header ) ;
}

function resetToken( $id, $username, $type, $permission, $login_cookies ){
	return md5( $id . $username . $type . $permission . $login_cookies ) ;
}

function checkLogin( $id, $username, $customer, $token ){	
	global $mysqli, $prefixUser, $prefixCompany, $prefixCustomer ;
	
	$result = 'failed-login' ;
	$content = array() ;
	
	$user = $mysqli->query( "SELECT user_id, user_name, user_type, user_permission, user_login_cookies FROM $prefixUser
							 WHERE user_id = '".$id."' AND user_name = '".$username."' AND user_trash = '0' LIMIT 1" ) ;
	if ( $user->num_rows > 0 ){
		
		$row = $user->fetch_assoc() ;
		$new_token = resetToken( $row['user_id'], $row['user_name'], $row['user_type'], $row['user_permission'], $row['user_login_cookies'] ) ;

		if ( $token != '' && $token == $new_token ){
			
			$content = $row ;
			$result = 'success-login' ;
			
			if ( $row['user_type'] == 'customer' ){
			
				// get customer and company information
				$customer = $mysqli->query( "SELECT a.customer_id, b.company_id, b.company_name FROM $prefixCustomer a
											 LEFT JOIN $prefixCompany b ON ( a.customer_company_id = b.company_id)
											 WHERE a.customer_id = '".$customer."' AND a.customer_trash = '0' LIMIT 1" ) ;
				if ( $customer->num_rows > 0 ){
					$row_customer = $customer->fetch_assoc() ;	
					$content = ( $content + $row_customer ) ;
				}
				
			}
			
		}
		
	}
	
	$array['content'] = $content ;
	$array['result'] = $result ;
	return $array ;
}

function pushAppNotification( $user_token, $user_id, $title, $message, $logo ){
	global $mysqli ;

	$search_query = '' ;
	if ( $user_token != '' ){
		$search_query .= " AND google_token = '".$user_token."'" ;
	}
	if ( $user_id != '' ){
		$search_query .= " AND google_user_id = '".$user_id."'" ;
	}
	
	// loop all register token
	$all_token = $mysqli->query( "SELECT google_id, google_token, google_count FROM system_google
								  WHERE google_id != ''" . $search_query ) ;
	
	if ( $all_token->num_rows > 0 ){
		
		$push = array() ;
		$array_id = array() ;
		$update = '' ;
		
		while ( $row = $all_token->fetch_assoc() ){
			$push[] = $row ;
		}
		
		foreach ( $push as $token ){
			$token_id = $token['google_id'] ;
			$badge = ($token['google_count'] + 1) ;
			$data = array( "to" => $token['google_token'],
						   "notification" 		=> array( 
								"title"   		=> $title, 
								"body"    		=> $message,
								"icon"    		=> PATH.$logo, 
								"sound"			=> '1',
								"vibrate"		=> '1',
								"badge"			=> $badge,
								"click_action" 	=> ''
							)
						) ;
			pushToAppNotification( $data ) ;
			$array_id[] = $token_id ;
			$update .= sprintf( " WHEN %d THEN '%s' ", $token_id, $badge ) ;
		}

		$mysqli->query( "UPDATE system_google SET
						 google_count = Case google_id " . $update . " END
						 WHERE google_id IN ('".implode("','", $array_id)."')" ) ;
	}
}


function pushToAppNotification( $data ){
	
	$headers = array(
		'Authorization: key='.FIREBASEKEY, 
		'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);
	curl_close ($ch) ;
	
}

// get combine quotation id
function apiCombineQuotation($mysqli, $prefixCombineSub, $prefixQuotation, $prefixRate, $prefixCompany, $prefixUser, $head_id, $all_order_item){

	// query for sub
	$mysqli_sub = $mysqli->query("SELECT quotation_id, quotation_so, quotation_so2, quotation_date, quotation_so2_manual, quotation_rate_id, quotation_total_quotation, quotation_total_company, quotation_total, quotation_po_id, quotation_goods_ready_date, rate_currency, company_account_code, company_code, company_number, user_name FROM ".$prefixCombineSub." a
									LEFT JOIN ".$prefixQuotation." b ON (a.combine_sub_quotation_id = b.quotation_id)
									LEFT JOIN ".$prefixCompany." c ON (b.quotation_company_id = c.company_id)
									LEFT JOIN ".$prefixRate." d ON (b.quotation_rate_id = d.rate_id)
									LEFT JOIN ".$prefixUser." e ON (b.quotation_user_id = e.user_id )
									WHERE a.combine_sub_head_id = '".$head_id."' AND a.combine_sub_trash = '0' AND b.quotation_trash = '0'") ;
	// defaut variable
	$order_list = $order_list_date = $order_list_po = $order_list_po_date = $order_rate = $quotation_goods_ready_date = $incarge_person = '' ;
	$count = $total_pi = $total_po = $count_selected = 0 ;
	// check if query exsits
	if ($mysqli_sub->num_rows > 0){
		
		// check invoice item
		$arrray_item = array() ;
		if (apiArrayCheck($all_order_item)){
			foreach($all_order_item as $key => $value){
				$arrray_item[$value['cart_quotation_id']][] = $value ;	
			}
			array_values($arrray_item) ;
		}
		
		// loop all query
		while ($row_sub = $mysqli_sub->fetch_array(MYSQLI_ASSOC)){
			// decode data and keep in variable
			$quotation_total_pi = unserialize(base64_decode($row_sub['quotation_total'])) ;
			$total_pi += $quotation_total_pi['cart_grand_total'] ;
			$count++ ;
			// query for po
			$mysqli_po = $mysqli->query("SELECT quotation_so2, quotation_date, quotation_total, quotation_so2_manual, quotation_product FROM ".$prefixQuotation."
										 WHERE quotation_po_id = '".$row_sub['quotation_id']."' AND ( quotation_type = 'qc-order-po' OR quotation_type = 'order-po' ) AND quotation_trash = '0' LIMIT 1") ;
			// count selected
			$count_selected++ ;
			// invoice number
			$invoice_manual = $row_sub['quotation_so2_manual'] ;
			$invoice = $row_sub['quotation_so'] ;
			$invoice2 = ($invoice_manual == 1 ? '' : 'P').$row_sub['quotation_so2'] ;
			// get company details
			$company_number = apiDataFilterDash($row_sub['company_number']) ;
			$company_account_code = apiDataFilterDash($row_sub['company_account_code']) ;
			$company_code = apiDataFilterDash($row_sub['company_code']) ;
			// keep order so
			$order_list .= $invoice2 . ($mysqli_sub->num_rows != $count_selected ? ', ' : '') ;
			$order_list_date .= apiResetDate($row_sub['quotation_date']) . ($mysqli_sub->num_rows != $count_selected ? ', ' : '') ;
			$quotation_goods_ready_date .= $row_sub['quotation_goods_ready_date'] . ($mysqli_sub->num_rows != $count_selected ? ', ' : '') ;
			$order_rate .= apiDataFilter($row_sub['rate_currency']) . ($mysqli_sub->num_rows != $count_selected ? ', ' : '') ;
			$incarge_person .= ucwords(strtolower($row_sub['user_name'])) . ($mysqli_sub->num_rows != $count_selected ? ', ' : '') ;
			// check if query exists
			if ($mysqli_po->num_rows > 0){
				// set query as array
				$row_po = $mysqli_po->fetch_array(MYSQLI_ASSOC) ;
				$array_po = $arrray_item[$row_sub['quotation_id']] ;

				// decode data and keep in variable
				// $quotation_total_po = unserialize(base64_decode($row_po['quotation_total'])) ;
				$quotation_product = unserialize(base64_decode($row_po['quotation_product'])) ;
				// check array po
				if (apiArrayCheck($array_po)){
					foreach( $array_po as $key_po => $value_po ){
						
						foreach( $quotation_product as $key_item => $value_item ){
						
							if ( $value_po['cart_id'] == $value_item['cart_id'] ){
								$price_my = ( $value_item['cart_price_my'] ) ;
							}
							
						}
						
						$total_po += ($price_my * $value_po['cart_quantity']) ;
					}
				}
				// $total_po += $quotation_total_po['cart_grand_total_my'] ;
				// keep order so
				$order_list_po .= ($row_po['quotation_so2_manual'] == 1 ? '' : 'PO').apiDataFilterDash($row_po['quotation_so2']) . ', ' ;
				$order_list_po_date .= apiResetDate($row_po['quotation_date']) . ', ' ;
			}
		}
		$order_list_po = ($order_list_po != '' ? substr($order_list_po, 0, -2) : '') ;
		$order_list_po_date = ($order_list_po_date != '' ? substr($order_list_po_date, 0, -2) : '') ;
	}
	// set result as array
	$array['total_order'] = $count ;
	$array['goods_ready_date'] = $quotation_goods_ready_date ;
	$array['pi'] = $order_list ;
	$array['pi_date'] = $order_list_date ;
	$array['pi_total'] = $total_pi ;
	$array['po'] = apiDataFilterDash($order_list_po) ;
	$array['po_date'] = apiDataFilterDash($order_list_po_date) ;
	$array['po_total'] = $total_po ;
	$array['incharge'] = $incarge_person ;
	$array['rate_currency'] = $order_rate ;
	$array['company_number'] = $company_number ;
	$array['company_account_code'] = $company_account_code ;
	$array['company_code'] = $company_code ;
	// return result
	return $array ;
}

// check array is it true
function apiArrayCheck($array){
	$boolean_array = false ;
	if (count($array) > 0 && is_array($array)){
		$boolean_array = true ;	
	}
	return $boolean_array ;
}

// stripslashes data
function apiDataFilter($value){
	$value = trim($value) ;
	$value = stripslashes($value) ;
	//$value = html_entity_decode($value) ;
	return $value ;
}

function apiDataFilterDash($value, $dash = '-'){
	$value = apiDataFilter($value) ;
	$value = ($value != '' ? $value : $dash) ;
	return $value ;
}

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

// check image
function checkImage( $image, $path, $default_image = 'no' ){
	if ( $image != '' ){
		$image = PATH.'Uploads/'.$path.'/'.$image ;
	}else{
		if ( $default_image == 'yes' ){
			$image = PATH.'Images/NoProduct.jpg' ;
		}
	}
	return $image ;
}

// check audio
function checkAudio( $audio ){
	if ( $audio != '' ){
		$audio = PATH.'SoundRecord/'.$audio ;
	}
	return $audio ;
}

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

	$s = '../Uploads/'.$path.'/'.$file_name ;
	$b = '../Uploads/'.$path.'/b/'.$file_name ;

	if( file_put_contents($s, base64_decode($source)) && file_put_contents($b, base64_decode($source)) ) {
		$result = true ;
	}
	return $result ;
}

function apiResetDate($date){
	return date('d/M/Y', strtotime($date)) ;
}

// machine store log
function setStoreLogTemp( $store_id, $user_id, $user_name, $quantity, $latitude, $longitude ){
	global $mysqli, $prefixMachineStore, $prefixMachineStoreLog, $today_date ;

	$result        = 'failed-store' ;
	$message       = 'Store not found.' ;

	$log_type      = 'in' ;

	// check store if exists
	$store = $mysqli->query( "SELECT store_id, store_part_number, store_quantity, store_quantity_warning FROM $prefixMachineStore
							  WHERE store_id = '".$store_id."' LIMIT 1" ) ;
	if ( $store->num_rows > 0 ){

		$result    = 'failed-log' ;
		$message   = 'Failed to generate log.' ;

		$log_type  = ( $quantity >= 0 ? 'in' : 'out' ) ;

		if ( $mysqli->query( "INSERT INTO system_machine_store_log_temp
							 (log_store, log_user_id, log_user_name, log_latitude, log_longitude, log_type, log_quantity, log_date) VALUES
							 ('".$store_id."', '".$user_id."', '".$user_name."', '".$latitude."', '".$longitude."', '".$log_type."', '".$quantity."', '".$today_date."')" ) ){
			$result    = 'success' ;
			$message   = 'Success.' ;
		}

	}

	return [
		'result'  => $result,
		'message' => $message
	] ;

}

// machine store log
function setStoreLog( $store_id, $user_id, $user_name, $quantity, $latitude, $longitude, $machine_code, $supplier, $invoice_no, $invoice_image, $price ){
	global $mysqli, $prefixMachineStore, $prefixMachineStoreLog, $today_date ;

	$result        = 'failed-store' ;
	$message       = 'Store not found.' ;

	// default parameter
	$boolen        = false ;
	$part_number   = '' ;
	$log_type      = 'in' ;
	$before        = 0 ;
	$after         = 0 ;
	$balance       = 0 ;
	$stock_warning = 0 ;

	// check store if exists
	$store = $mysqli->query( "SELECT store_id, store_part_number, store_quantity, store_quantity_warning FROM $prefixMachineStore
							  WHERE store_id = '".$store_id."' LIMIT 1" ) ;
	if ( $store->num_rows > 0 ){

		$result    = 'failed-log' ;
		$message   = 'Failed to generate log.' ;

		// check if log exists
		$row_store     = $store->fetch_assoc() ;
		$part_number   = $row_store['store_part_number'] ;
		$current_qty   = $row_store['store_quantity'] ;
		$stock_warning = $row_store['store_quantity_warning'] ;

		// check if log exits
		$log = $mysqli->query( "SELECT log_id, log_balance FROM $prefixMachineStoreLog
							    WHERE log_store = '".$store_id."' ORDER BY log_id DESC LIMIT 1" ) ;
		if ( $log->num_rows > 0 ){

			$result    = 'failed-balance' ;
			$message   = 'Incorrect balance.' ;

			$row_log      = $log->fetch_assoc() ;
			$last_balance = $row_log['log_balance'] ;

			// check if current quantity not same as last balance
			if ( $current_qty == $last_balance ){

				$boolen   = true ;
				$log_type = ( $quantity >= 0 ? 'in' : 'out' ) ;
				$before   = $current_qty ;
				$after    = $quantity ;
				$balance  = ( $current_qty + $quantity ) ;

			}

		}else{
			$boolen  = true ;
			$before  = 0 ;
			$after   = $quantity ;
			$balance = $quantity ;
		}

	}

	if ( $boolen ){
		if ( $mysqli->query( "INSERT INTO $prefixMachineStoreLog
							 (log_store, log_user_id, log_user_name, log_latitude, log_longitude, log_machine_code, log_supplier, log_invoice_no, log_price, log_type, log_before, log_after, log_balance, log_date) VALUES
							 ('".$store_id."', '".$user_id."', '".$user_name."', '".$latitude."', '".$longitude."', '".$machine_code."', '".$supplier."', '".$invoice_no."', '".$price."', '".$log_type."', '".$before."', '".$after."', '".$balance."', '".$today_date."')" ) ){
			$result    = 'success' ;
			$message   = 'Success.' ;

			$last_id   = $mysqli->insert_id ;

			if ( $invoice_image != '' ){
				$image       = 'store'.'-'.$last_id.'-'.time().'.jpg' ;
				$decocedData = uploadImage('Maintenance', $image, $invoice_image) ;
				if ( $decocedData ){

					// update database
					$mysqli->query("UPDATE $prefixMachineStoreLog SET
									log_invoice_image = '".$image."'
									WHERE log_id      = '".$last_id."'") ;

				}
			}

		}
	}

	return [
		'result'        => $result,
		'message'       => $message,
		'part_number'   => $part_number,
		'stock_warning' => $stock_warning,
		'stock'         => $balance
	] ;

}

?>