<?php
    function cuci($string){
		return htmlentities(mysql_fix_string(trim($string)));
	}

	function mysql_fix_string($string){

            	  	
		$string = strip_tags($string);
		
		$string = filter_danger_char($string);
		
		if (get_magic_quotes_gpc()) $string = stripslashes($string);
			return $string;
	}	
	
	function filter_danger_char($string)
	{
		$string = str_replace("=","sama dengan",$string) ;
		$string = str_replace(";","_semi_col_",$string) ;
		$string = str_replace("--"," dua ",$string) ;
		$string = str_replace("/*"," komen ",$string) ;
		$string = str_replace("\\","",$string) ;
		$string = str_replace("()","00",$string) ;	
		
		$string = str_replace("<","KURANG",$string) ;
		$string = str_replace("'","",$string) ;
		$string = str_replace('"','',$string) ;
		$string = str_replace("V501","",$string) ;
		$string = str_replace("@@","",$string) ;
				
		$string = str_ireplace("now()","sekarang()",$string );
		$string = str_ireplace("sleep","tidur",$string);
		$string = str_ireplace("select","pilih",$string);
		//$string = str_ireplace(" and "," dan ",$string);
	
	return $string;
 	}
	 	 
	function check_numeric($string)
	{
	 
		if(is_numeric ($string) ) 
		 return  $string;
		else
		return "";
	 
	}

	function jEncrypt($num, $timestamp)
	{
		return $num * 484838 + $timestamp - 45623;
	}

	function jDecrypt($num, $timestamp)
	{
		return ($num - $timestamp + 45623) / 484838;
	}

# --------------------------------------------
# To get variable from form post or URL
# --------------------------------------------
function fetch_postget_val($key, $post=array(), $get=array()) {
	if(isset($post[$key])) return cuci($post[$key]);
	else if(isset($get[$key])) return cuci($get[$key]);
	else return false;
}

function fetch_postget_val_nocuci($key, $post=array(), $get=array()) {
	if(isset($post[$key])) return ($post[$key]);
	else if(isset($get[$key])) return ($get[$key]);
	else return false;
}

# --------------------------------------------
# To build SELECT query for datatable
# --------------------------------------------
function buildSelectQuery($columnArray)
{
	$QUERY_STR = '';
	foreach ($columnArray as $item)
	{
		if (isset($item['table']))
		{
			if(isset($item['akaFrom']))
			{
				$QUERY_STR .= "${item['table']}.${item['akaFrom']} AS ${item['db']}, ";
			}
			else
			{
				$QUERY_STR .= "${item['table']}.${item['db']}, ";
			}
		}
		else if (isset($item['user_defined']))
		{			
			if(preg_match_all('/\%([^%]+)\%/', $item['user_defined'], $out, PREG_SET_ORDER) > 0)
			{
				foreach($out as $matchItem)
				{
					$QUERY_STR .= $matchItem[1].", ";
				}
			}
		}
	}
	return rtrim($QUERY_STR, ", "); //remove tailing comma
}

function buildSelectQuery2($columnArray)
{
	$QUERY_STR = '';
	foreach ($columnArray as $item)
	{
		if (isset($item['table']))
		{
			if(isset($item['aka']))
			{
				$QUERY_STR .= "${item['table']}.${item['db']} AS ${item['aka']}, ";
			}
			else
			{
				$QUERY_STR .= "${item['table']}.${item['db']}, ";
			}
		}
		else if (isset($item['user_defined']))
		{			
			if(preg_match_all('/\%([^%]+)\%/', $item['user_defined'], $out, PREG_SET_ORDER) > 0)
			{
				foreach($out as $matchItem)
				{
					$QUERY_STR .= $matchItem[1].", ";
				}
			}
		}
	}
	return rtrim($QUERY_STR, ", "); //remove tailing comma
}
# --------------------------------------------
# To build FROM query for datatable
# --------------------------------------------
function buildFromQuery($columnArray)
{
	$FROM_STR = $columnArray['main'];
	foreach ($columnArray['sub'] as $item)
	{
		$AKA = (isset($item['aka'])?$item['aka']:'');
		$FROM_STR .= " LEFT JOIN ".$item['name']." $AKA ON ".(isset($item['main_name'])?$item['main_name']:$columnArray['main']).".".$item['main_id']." = ".(isset($item['aka'])?$item['aka']:$item['name']).".".$item['sub_id'];
	}
	return $FROM_STR." ";
}

# --------------------------------------------
# To build WHERE query for datatable
# --------------------------------------------
function buildWhereQuery($columnArray)
{
	if(count($columnArray) == 0)
	{
		return null;
	}
	else
	{
		$WHERE_STR = '';
		foreach ($columnArray as $item)
		{
			if(is_array($item[0])) //special OR by set array
			{
				$OR_STR = "(";
				foreach ($item as $or_item)
				{
					$OR_STR .= "{$or_item[0]}.{$or_item[1]} ".(isset($or_item[3])?$or_item[3]:'=')." ".((empty($or_item[2]) && $or_item[2] !== 0)?"''":$or_item[2])." OR ";
				}
				$WHERE_STR .= rtrim($OR_STR, "OR ").") AND ";
			}
			else
			{
				$WHERE_STR .= ($item[0]==''?'':$item[0].'.').$item[1].' '.(isset($item[3])?$item[3]:'=')." ".((empty($item[2]) && $item[2] !== 0)?"''":$item[2])." AND ";
			}
		}
		return rtrim($WHERE_STR, "AND "); //remove tailing AND
	}
}

# --------------------------------------------
# To get date time now
# --------------------------------------------
function dateTimeNow()
{
	return date("Y-m-d H:i:s");
}

function number_format_no_thousand($num, $decimal)
{
	return number_format($num, $decimal, '.' ,'');
}

# --------------------------------------------
# To convert Datetime format
# --------------------------------------------
function formatDate($date, $format = 'd/m/Y')
{
	if($date == '0000-00-00' || $date == '0000-00-00 00:00:00' || $date == null)
	{
		return "";
	}
	else
	{
		return date($format, strtotime($date));
	}
}

function monthToMalay($month)
{
	if($month == 1){return 'Januari';}
	else if($month == 2){return 'Februari';}
	else if($month == 3){return 'Mac';}
	else if($month == 4){return 'April';}
	else if($month == 5){return 'Mei';}
	else if($month == 6){return 'Jun';}
	else if($month == 7){return 'Julai';}
	else if($month == 8){return 'Ogos';}
	else if($month == 9){return 'September';}
	else if($month == 10){return 'Oktober';}
	else if($month == 11){return 'November';}
	else if($month == 12){return 'Disember';}
}

function monthToMalayShort($month)
{
	if($month == 1){return 'Jan';}
	else if($month == 2){return 'Feb';}
	else if($month == 3){return 'Mac';}
	else if($month == 4){return 'Apr';}
	else if($month == 5){return 'Mei';}
	else if($month == 6){return 'Jun';}
	else if($month == 7){return 'Jul';}
	else if($month == 8){return 'Ogos';}
	else if($month == 9){return 'Sep';}
	else if($month == 10){return 'Okt';}
	else if($month == 11){return 'Nov';}
	else if($month == 12){return 'Dis';}
}

function dayToMalay($day)
{
	if($day == 1){return 'Isnin';}
	else if($day == 2){return 'Selasa';}
	else if($day == 3){return 'Rabu';}
	else if($day == 4){return 'Khamis';}
	else if($day == 5){return 'Jumaat';}
	else if($day == 6){return 'Sabtu';}
	else if($day == 0){return 'Ahad';}
}

function kadarToMalay($kadar)
{
	$kadar_split = explode('.', $kadar);
	return numberToMalay($kadar_split[0]).' Ringgit'.($kadar_split[1] == '00'?'':' Dan '.numberToMalay($kadar_split[1]).' Sen');
}

function numberToMalay($num)
{
	//echo 'num = '.$num.'<br>';
	if($num[0] == '0') //remove heading 0
	{
		$num = substr($num, 1);
	}
	if($num == 1){return 'Satu';}
	else if($num == 2){return 'Dua';}
	else if($num == 3){return 'Tiga';}
	else if($num == 4){return 'Empat';}
	else if($num == 5){return 'Lima';}
	else if($num == 6){return 'Enam';}
	else if($num == 7){return 'Tujuh';}
	else if($num == 8){return 'Lapan';}
	else if($num == 9){return 'Sembilan';}
	else if($num == 10){return 'Sepuluh';}
	else if($num == 11){return 'Sebelas';}
	else if($num >= 12 && $num < 20){return numberToMalay($num[1]).' Belas';}
	else if($num >= 20 && $num < 100){return numberToMalay($num[0]).' Puluh '.numberToMalay($num[1]);}
	else if($num >= 100 && $num < 1000){return numberToMalay($num[0]).' Ratus '.numberToMalay(substr($num, -2));}
    else if($num >= 1000 && $num < 1000000){return numberToMalay(substr($num, 0, -3)).' Ribu '.numberToMalay(substr($num, -3));}
    else if($num >= 1000000 && $num < 1000000000){return numberToMalay(substr($num, 0, -6)).' Juta '.numberToMalay(substr($num, -6));}
}

//https://stackoverflow.com/questions/11500088/php-express-number-in-words
function convertNumberToWord($num = false)
{
    $num = str_replace(array(',', ' '), '' , trim($num));
    if(! $num) {
        return false;
    }
    $num = (int) $num;
    $words = array();
    $list1 = array('', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
        'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'
    );
    $list2 = array('', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety', 'hundred');
    $list3 = array('', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion',
        'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',
        'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion', 'vigintillion'
    );
    $num_length = strlen($num);
    $levels = (int) (($num_length + 2) / 3);
    $max_length = $levels * 3;
    $num = substr('00' . $num, -$max_length);
    $num_levels = str_split($num, 3);
    for ($i = 0; $i < count($num_levels); $i++) {
        $levels--;
        $hundreds = (int) ($num_levels[$i] / 100);
        $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' hundred' . ' ' : '');
        $tens = (int) ($num_levels[$i] % 100);
        $singles = '';
        if ( $tens < 20 ) {
            $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '' );
        } else {
            $tens = (int)($tens / 10);
            $tens = ' ' . $list2[$tens] . ' ';
            $singles = (int) ($num_levels[$i] % 10);
            $singles = ' ' . $list1[$singles] . ' ';
        }
        $words[] = $hundreds . $tens . $singles . ( ( $levels && ( int ) ( $num_levels[$i] ) ) ? ' ' . $list3[$levels] . ' ' : '' );
    } //end for loop
    $commas = count($words);
    if ($commas > 1) {
        $commas = $commas - 1;
    }
    return implode(' ', $words);
}

function dateToMalay($date)
{
	return formatDate($date, 'd').' '.monthToMalay(formatDate($date, 'm')).' '.formatDate($date, 'Y');
}

function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "", $string);
} 

function integerToRoman($integer)
{
 // Convert the integer into an integer (just to make sure)
 $integer = intval($integer);
 $result = '';
 
 // Create a lookup array that contains all of the Roman numerals.
 $lookup = array('M' => 1000,
 'CM' => 900,
 'D' => 500,
 'CD' => 400,
 'C' => 100,
 'XC' => 90,
 'L' => 50,
 'XL' => 40,
 'X' => 10,
 'IX' => 9,
 'V' => 5,
 'IV' => 4,
 'I' => 1);
 
 foreach($lookup as $roman => $value){
  // Determine the number of matches
  $matches = intval($integer/$value);
 
  // Add the same number of characters to the string
  $result .= str_repeat($roman,$matches);
 
  // Set the integer to be the remainder of the integer and the value
  $integer = $integer % $value;
 }
 
 // The Roman numeral should be built, return it
 return $result;
}
# --------------------------------------------
# To calculate date different
# --------------------------------------------
function daysDifferent($date)
{
	$dStart = new DateTime($date);
	$dEnd  = new DateTime(null);
	$dDiff = $dStart->diff($dEnd);
	return $dDiff->days;
}

function dateDifference($date_1 , $date_2, $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);
    
    $interval = date_diff($datetime1, $datetime2);
	$return_result = $interval->format($differenceFormat);
    if($datetime1 < $datetime2)
	{
		$return_result = $return_result * -1;
	}
    return $return_result;
}

# --------------------------------------------
# To process KP Baru
# --------------------------------------------
function processKP($kp_baru)
{
	$year = substr($kp_baru, 0, 2);
	$month = substr($kp_baru, 2, 2);
	$day = substr($kp_baru, 4, 2);
	$state = substr($kp_baru, 6, 2);
	$gender = substr($kp_baru, -1);
	$date = (((year <= datenow.format('YY'))?'20':'19') . year).'-'.$month.'-'.$day;
	//$date = formatDate('19'.$year.'-'.$month.'-'.$day); //assume all 19xx
	$state = ($state == '08' || $state == '37' || $state == '38' || $state == '39')?1:2; //08, 37, 38, 39 penang kod
	$gender = ($gender % 2 == 0)?2:1; //even is female, odd is male
	return array($date, $state, $gender);
}

function processJantina($kp_baru)
{
	$gender = substr($kp_baru, -1);
	$gender = ($gender % 2 == 0)?2:1; //even is female, odd is male
	return ($gender);
}

# --------------------------------------------
# Check access control level by role
# --------------------------------------------
//done
function checkAccess($PDO, $role, $script_name){
	$PDO_stmt = $PDO->prepare("SELECT P.aktif 
								FROM t_pautan  P
								INNER JOIN t_tetingkap T
								ON P.id_tetingkap = T.id_tetingkap
								WHERE P.aktif = 1 AND T.nama_skrip = ? 
								AND P.id_peranan = ?");
	$PDO_stmt->bindValue(1, $script_name, PDO::PARAM_STR);
	$PDO_stmt->bindValue(2, $role, PDO::PARAM_INT);
	$rstUser = $PDO_stmt->execute();
	if (!$rstUser) {
		return false;
	}
	$isAllow = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
	return ($isAllow['aktif'] > 0);
}

//****************************************************
//NEW UPDATE FUNCTION 07/11/2020
//****************************************************
//done
function createTextBox($label, $name, $placeholder, $value, $labelsize=5, $readonly=0, $tbSize=7, $divSize=6, $style = '', $type='text', $helpText='', $additional='', $maxLength=0)
{
	if($type == 'numonly')
	{
		$type = 'text';
		$extra_class = 'numonly';
	}
	
	echo '<div class="col-md-'.$divSize.' form-group row" id="'.$name.'_div">';
		echo '<label id="'.$name.'_label" class="col-md-'.$labelsize.' col-form-label">'.$label.'</label>';
		echo '<div class="col-md-'.$tbSize.'">';
			echo '<input class="form-control m-input '.$extra_class.'" type="'.$type.'" placeholder="'.$placeholder.'" value="'.$value.'" id="'.$name.'" name="'.$name.'" '.($readonly?'readonly':'').' style="'.$style.'" '.$additional.' '.(($maxLength>0)?'maxlength='.$maxLength:'').'>';
			echo '<span class="form-text" id="'.$name.'_help" style="font-size:110%;color:red;">'.$helpText.'</span>';
		echo '</div>';
	echo '</div>';
}

//done
function createDropDown_Array_Special($label, $my_array, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $size = 7, $label_size = 5, $div_size = 6, $readonly=0)
{
	echo '<div class="col-md-'.$div_size.' form-group row" id="'.$dropDownName.'_div">';
		echo '<label class="col-md-'.$label_size.' col-form-label" id="'.$dropDownName.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$size.'">';
			echo '<select name="'.$dropDownName.'" id="'.$dropDownName.'" class="form-control select2" '.($readonly?'disabled="disabled"':'').'>';
				echo '<option value="0" ';
				if($selectedIndex == 0){ echo 'selected'; }
				echo '>'.$firstIndex.'</option>';
				for($num = 0; $num < count($my_array); $num++)
				{
					echo '<option value="'.$my_array[$num][0].'" ';
					if($selectedIndex == $my_array[$num][0]){ echo 'selected'; }
					if($my_array[$num][2]){ echo $my_array[$num][2]; }
					echo '>'.$my_array[$num][1].'</option>';
				}
			echo '</select>';
		echo '</div>';
	echo '</div>';
}

function createDropDown_AdaTiada($label, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $size = 7, $label_size = 5, $div_size = 6, $readonly=0, $help='')
{
	$arr = [];
	$arr[] = array(1, 'Ada');
	$arr[] = array(2, 'Tiada');
	createDropDown_Array($label, $arr, $dropDownName, $selectedIndex, $firstIndex, $size, $label_size, $div_size, $readonly, $help);
}
//done
function createDropDown_Array($label, $my_array, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $size = 7, $label_size = 5, $div_size = 6, $readonly=0, $help='')
{
	echo '<div class="col-md-'.$div_size.' form-group row" id="'.$dropDownName.'_div">';
		echo '<label class="col-md-'.$label_size.' col-form-label" id="'.$dropDownName.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$size.'">';
			echo '<select name="'.$dropDownName.'" id="'.$dropDownName.'" class="form-control select2" '.($readonly?'disabled="disabled"':'').'>';
				echo '<option value="0" ';
				if($selectedIndex == 0){ echo 'selected'; }
				echo '>'.$firstIndex.'</option>';
				for($num = 0; $num < count($my_array); $num++)
				{
					echo '<option value="'.$my_array[$num][0].'" ';
					if($selectedIndex == $my_array[$num][0]){ echo 'selected'; }
					for($num2 = 2; $num2 < count($my_array[$num]); $num2++)
					{
						if($my_array[$num][$num2] != '' ){ echo ' cTag'.($num2-1).'="'.$my_array[$num][$num2].'" '; }
					}
					echo '>'.$my_array[$num][1].'</option>';
				}
			echo '</select>';
			echo '<span class="form-text" style="font-size:110%;color:red;"><b>'.$help.'</b></span>';
		echo '</div>';
	echo '</div>';
}

//done
function createDropDown_sql($PDO, $label, $mySQL, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $size = 7, $label_size = 5, $div_size = 6, $readonly=0, $help='')
{
	$myQuery_cmd = $PDO->prepare($mySQL);
	$myQuery_cmd->execute();
	$selectArray = [];
	while($result = $myQuery_cmd->fetch(PDO::FETCH_ASSOC)) {
		$temp = array($result['id'], $result['name']);
		//case for customtag
		for($num2 = 1; $num2 <= 2; $num2++)
		{
			if($result['cTag'.$num2] != ''){$temp[] = $result['cTag'.$num2];}
		}
		
		$selectArray[] = $temp;
	}
	createDropDown_Array($label, $selectArray, $dropDownName, $selectedIndex, $firstIndex, $size, $label_size, $div_size, $readonly, $help);
}

//done
function createDropDown($PDO, $label, $tableName, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $size = 7, $label_size = 5, $div_size = 6, $readonly=0, $name = 'desk_', $help='')
{
	$identifier = substr($tableName, 2); // remove the i_
	
	$myQuery = "
		SELECT id_{$identifier} AS id, concat({$name}{$identifier}) as name
		FROM {$tableName}
		WHERE aktif = 1
	";
	
	createDropDown_sql($PDO, $label, $myQuery, $dropDownName, $selectedIndex, $firstIndex, $size, $label_size, $div_size, $readonly, $help);
}

function createDropDown_Array2($label, $my_array, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $div_size = 6, $readonly=0)
{
	echo '<div class="col-md-'.$div_size.'" id="'.$dropDownName.'_div">';
		echo '<label for="'.$dropDownName.'" id="'.$dropDownName.'_label">'.$label.'</label>';
			echo '<select name="'.$dropDownName.'" id="'.$dropDownName.'" class="form-control" '.($readonly?'disabled="disabled"':'').'>';
				echo '<option value="0" ';
				if($selectedIndex == 0){ echo 'selected'; }
				echo '>'.$firstIndex.'</option>';
				for($num = 0; $num < count($my_array); $num++)
				{
					echo '<option value="'.$my_array[$num][0].'" ';
					if($selectedIndex == $my_array[$num][0]){ echo 'selected'; }
					echo '>'.$my_array[$num][1].'</option>';
				}
			echo '</select>';
	echo '</div>';
}

function createDropDown_sql2($PDO, $label, $mySQL, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $div_size = 6, $readonly=0)
{
	$myQuery_cmd = $PDO->prepare($mySQL);
	$myQuery_cmd->execute();
	$selectArray = [];
	while($result = $myQuery_cmd->fetch(PDO::FETCH_ASSOC)) {
		$selectArray[] = array($result['id'], $result['name']);
	}
	createDropDown_Array2($label, $selectArray, $dropDownName, $selectedIndex, $firstIndex, $div_size, $readonly);
}


function createDropDown_Array_special_style($label, $my_array, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $div_size = 6, $readonly=0, $divstyle='', $selectExtra='')
{
	echo '<div class="col-md-'.$div_size.'" id="'.$dropDownName.'_div" style="margin-top:10px;'.$divstyle.'">';
		echo '<label for="'.$dropDownName.'" id="'.$dropDownName.'_label">'.$label.'</label>';
			echo '<select name="'.$dropDownName.'" id="'.$dropDownName.'" class="form-control" '.($readonly?'disabled="disabled"':'').' '.$selectExtra.' >';
				echo '<option value="0" ';
				if($selectedIndex == 0){ echo 'selected'; }
				echo '>'.$firstIndex.'</option>';
				for($num = 0; $num < count($my_array); $num++)
				{
					echo '<option value="'.$my_array[$num][0].'" ';
					if($selectedIndex == $my_array[$num][0]){ echo 'selected'; }
					if(isset($my_array[$num][2])){ echo $my_array[$num][2]; }
					echo '>'.$my_array[$num][1].'</option>';
				}
			echo '</select>';
	echo '</div>';
}

function createDropDown_sql_special_style($PDO, $label, $mySQL, $dropDownName, $selectedIndex = 0, $firstIndex = 'SEMUA', $div_size = 6, $readonly=0, $divstyle='', $selectExtra='')
{
	$myQuery_cmd = $PDO->prepare($mySQL);
	$myQuery_cmd->execute();
	$selectArray = [];
	while($result = $myQuery_cmd->fetch(PDO::FETCH_ASSOC)) {
		$selectArray[] = array($result['id'], $result['name']);
	}
	createDropDown_Array_special_style($label, $selectArray, $dropDownName, $selectedIndex, $firstIndex, $div_size, $readonly, $divstyle, $selectExtra);
}

function createTextBox_special_style($label, $name, $placeholder, $value, $labelsize=5, $readonly=0, $tbSize=7, $divSize=6, $style = '', $type='text', $helpText='', $additional='')
{
	if($type == 'numonly')
	{
		$type = 'text';
		$extra_class = 'numonly';
	}
	
	echo '<div class="col-md-'.$divSize.'" id="'.$name.'_div" style="margin-top:10px">';
		echo '<label id="'.$name.'_label" class="col-md-'.$labelsize.'">'.$label.'</label>';
		echo '<div class="col-md-'.$tbSize.'">';
			echo '<input class="form-control m-input '.$extra_class.'" type="'.$type.'" placeholder="'.$placeholder.'" value="'.$value.'" id="'.$name.'" name="'.$name.'" '.($readonly?'readonly':'').' style="'.$style.'" '.$additional.'>';
			echo '<span class="form-text" style="font-size:110%;color:red;">'.$helpText.'</span>';
		echo '</div>';
	echo '</div>';
}
//done
function createLabels($label, $name, $value, $color='', $labelsize=5, $tbSize=7, $bold=0, $div_size = 2)
{	
	echo '<div class="form-group row col-md-'.$div_size.'" id="'.$name.'_div">';
		echo '<label class="col-md-'.$labelsize.' col-form-label" id="'.$name.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$tbSize.'">';
			echo '<span class="form-control-plaintext font-weight-bolder" id="'.$name.'">'.$value.'</span>';
		echo '</div>';
	echo '</div>';
}

function createtableLabels($label, $width=0, $value)
{	
	echo '<tr>';
		echo '<td>'.$label.'</td>';
		echo '<td style="width:'.$width.'%">:</td>';
		echo '<td><b>'.$value.'</b></td>';
	echo '</tr>';
}

function createtableTitle($title)
{	
	echo '<tr>';
		echo '<td colspan=3 style="padding-top:10px;font-size:15px"><b>'.$title.'</b></td>';
	echo '</tr>';
}


//done
function createTextArea($label, $name, $placeholder, $value, $readonly=0, $labelsize=5, $tbSize=7, $divSize=2, $style = '', $row=10)
{		
	echo '<div class="col-md-'.$divSize.' form-group row" id="'.$name.'_div">';
		echo '<label id="'.$name.'_label" class="col-md-'.$labelsize.' col-form-label">'.$label.'</label>';
		echo '<div class="col-md-'.$tbSize.'">';
			echo '<textarea class="form-control" placeholder="'.$placeholder.'" id="'.$name.'" name="'.$name.'"  '.($readonly?'readonly':'').' style="'.$style.'" rows="'.$row.'">'.$value.'</textarea>';
		echo '</div>';
	echo '</div>';
}

function createDateTB($label, $name, $placeholder, $value, $labelsize=5, $readonly=0, $tbSize=7, $divSize=6)
{
	echo '<div class="form-group row col-md-'.$divSize.'" id="'.$name.'_div">';
		echo '<label class="col-md-'.$labelsize.' col-form-label" id="'.$name.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$tbSize.'">';
			echo '<div class="input-group date">';
				echo '<input type="text" style="margin-left:0px" class="myDatePicker form-control m-input" readonly  placeholder="'.$placeholder.'" id="'.$name.'" name="'.$name.'" value="'.$value.'"/>';
				echo '<div class="input-group-append">';
					echo '<span class="input-group-text">';
						echo '<i class="la la-calendar-check-o"></i>';
					echo '</span>';
				echo '</div>';
			echo '</div>';
		echo '</div>';
	echo '</div>';
}

function createTimeTB($label, $name, $placeholder, $value, $labelsize=5, $readonly=0, $tbSize=7, $divSize=6)
{
	echo '<div class="form-group row col-md-'.$divSize.'" id="'.$name.'_div">';
		echo '<label class="col-md-'.$labelsize.' col-form-label" id="'.$name.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$tbSize.'">';
			echo '<div class="input-group date">';
				echo '<input type="text" style="margin-left:0px" class="myTimePicker form-control m-input" readonly  placeholder="'.$placeholder.'" id="'.$name.'" name="'.$name.'" value="'.$value.'"/>';
				echo '<div class="input-group-append">';
					echo '<span class="input-group-text">';
						echo '<i class="la la-clock"></i>';
					echo '</span>';
				echo '</div>';
			echo '</div>';
		echo '</div>';
	echo '</div>';
}

//--------------------------------------------ALL DONE EDIT ABOVE HERE-------------

function createBlnThn($label, $name, $value, $labelsize=3, $divSize=12, $month_size=2, $year_size=2, $readonly=0, $yearMinus = 30, $yearPlus = 30)
{
	echo '<div class="col-md-'.$divSize.' form-group m-form__group row" id="'.$name.'_div">';
		echo '<label class="col-md-'.$labelsize.' col-form-label" id="'.$name.'_label">'.$label.'</label>';
		createBlnThn_simple($name, $value, false, $month_size, $year_size, $readonly, $yearMinus, $yearPlus);
	echo '</div>';
}

function createBlnThn_simple($name, $value, $is_return = false, $month_size=5, $year_size=5, $readonly=0, $yearMinus = 20, $yearPlus = 20)
{
	if($value != "")
	{
		$date = explode("/", $value);
	}
	else
	{
		$date = explode("/", date("m/Y"));
	}
	$out = '<div class="col-md-'.$month_size.'">';
	$out .= '<select name="'.$name.'_month" id="'.$name.'_month" class="select2me form-control" '.($readonly?'disabled="disabled"':'').'>';
	$out .= '<option value="0" selected>Month</option>';
	for($num = 1; $num <= 12; $num++)
	{
		$num_temp = (($num < 10)?'0'.$num:$num);
		$out .= '<option value="'.$num_temp.'" ';
		if((int)$date[0] == $num_temp){ $out .= 'selected'; }
		$out .= '>'.$num_temp.'</option>';
	}
	$out .= '</select>';
	$out .= '</div>';
	
	$out .= '<div class="col-md-'.$year_size.'">';
	$out .= '<select name="'.$name.'_year" id="'.$name.'_year" class="select2me form-control" '.($readonly?'disabled="disabled"':'').'>';
	$out .= '<option value="0" selected>Year</option>';
	$yearNow = date("Y");
	for($num = $yearNow - $yearMinus; $num <= $yearNow + $yearPlus; $num++)
	{
		$out .= '<option value="'.$num.'" ';
		if((int)$date[1] == $num){ $out .= 'selected'; }
		$out .= '>'.$num.'</option>';
	}
	$out .= '</select>';
	$out .= '</div>';
	
	if($is_return)return $out;
	echo $out;
}

function createThn($label, $name, $value, $labelsize=3, $divSize=12, $year_size=2, $readonly=0, $yearMinus = 20, $yearPlus = 20)
{
	echo '<div class="col-md-'.$divSize.' form-group m-form__group row" id="'.$name.'_div">';
		echo '<label class="col-md-'.$labelsize.' col-form-label" id="'.$name.'_label">'.$label.'</label>';
		createThn_simple($name, $value, false, $year_size, $readonly, $yearMinus, $yearPlus);
	echo '</div>';
}

function createThn_simple($name, $value, $is_return = false, $year_size=5, $readonly=0, $yearMinus = 20, $yearPlus = 20)
{
	$date = $value;
	
	$out .= '<div class="col-md-'.$year_size.'">';
	$out .= '<select name="'.$name.'_year" id="'.$name.'_year" class="select2me form-control" '.($readonly?'disabled="disabled"':'').'>';
	$out .= '<option value="0" selected>Tahun</option>';
	$yearNow = date("Y");
	for($num = $yearNow - $yearMinus; $num <= $yearNow + $yearPlus; $num++)
	{
		$out .= '<option value="'.$num.'" ';
		if($date == $num){ $out .= 'selected'; }
		$out .= '>'.$num.'</option>';
	}
	$out .= '</select>';
	$out .= '</div>';
	
	if($is_return)return $out;
	echo $out;
}

function createCheckBox_sql($PDO, $label, $mySQL, $cbName, $selectedIndex = '', $disabledIndex = '', $size = 7, $name = 'desk_', $label_size = 5, $div_size = 6, $readonly=0, $check_uncheck=false)
{
	$all_selected = array();
	foreach(explode(',', $selectedIndex) as $item)
	{
		$all_selected[$item] = 1;
	}
	
	$all_disabled = array();
	foreach(explode(',', $disabledIndex) as $item)
	{
		$all_disabled[$item] = 1;
	}
	
	//get all user pages id
	$PDO_stmt = $PDO->prepare($mySQL);
	$PDO_stmt->execute();
	echo '<div class="col-md-'.$div_size.' form-group m-form__group row" id="'.$cbName.'_div">';
		echo '<label class="col-md-'.$label_size.' col-form-label" id="'.$cbName.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$size.'" id="'.$cbName.'_cbdiv">';
			echo '<div class="checkbox-list">';
				if($check_uncheck)
				{
					echo '<label class="checkbox checkbox-outline checkbox-outline-2x checkbox-primary" align="left">';
					echo '<input type="checkbox" value="0" id="'.$cbName.'_check_uncheck" name="'.$cbName.'_check_uncheck" checked/>';
					echo '<span></span>';
					echo 'Select All';
					echo '</label>';
				}
				while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
				{
					echo '<label class="checkbox checkbox-outline checkbox-outline-2x checkbox-primary">';
					echo '<input class="'.$cbName.'_myCheckBox" type="checkbox" value="'.$result['id'].'" name="'.$cbName.'" '.($all_selected[$result['id']] > 0?'checked':' ').($all_disabled[$result['id']] > 0?'disabled':'').'/>';
					echo '<span></span>';
					echo $result['name'];
					echo '</label>';
				}
			echo '</div>';
		echo '</div>';
	echo '</div>';
}

function createCheckBox_array($db, $label, $mySQL, $cbName, $selectedIndex = '', $disabledIndex = '', $size = 7, $name = 'desk_', $label_size = 5, $div_size = 6, $readonly=0)
{
	echo '<div class="col-md-'.$div_size.' form-group row align-items-center" id="'.$cbName.'_div">';
		echo '<label class="col-md-'.$label_size.' col-form-label" id="'.$cbName.'_label">'.$label.'</label>';
		echo '<div class="col-md-'.$size.'" id="'.$cbName.'_cbdiv">';
			echo '<div class="checkbox-inline">';
				echo '<label class="checkbox">';
				echo '<input type="checkbox" value="1" name="checkbox1">';
				echo '<span></span>Ingin juga mengesahkan EFT?</label>';
			echo '</div>';
		echo '</div>';
	echo '</div>';
}

//done
function createTable($name, $columns, $title='', $small_title='', $print=1, $userBtn='', $modalName='ajax-modal', $size=12, $showSearch=1, $titleStyle='', $setHiddenInput=1)
{
	echo '<div class="col-md-'.$size.'">';
		echo '<div class="card card-custom gutter-b">';
			echo '<div class="card-header flex-wrap border-0 pt-6 pb-0">';
				echo '<div class="card-title" style="'.$titleStyle.'">';
					echo '<h3 class="card-label">';
						echo '<span id="'.$name.'_bigCardLabel">'.$title.'</span>';
						echo '<span class="d-block text-muted pt-2 font-size-sm" id="'.$name.'_smallCardLabel">'.$small_title.'</span>';
					echo '</h3>';
				echo '</div>';
				echo '<div class="card-toolbar">';
					if ($print > 0) //if need to print
					{
						echo '<div class="dropdown dropdown-inline mr-2">';
							echo '<button type="button" class="btn btn-light-primary font-weight-bolder dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">';
							echo '<span class="svg-icon svg-icon-md">';
								echo $exportBtnSvg;
							echo '</span>Export</button>';
							echo '<div class="dropdown-menu dropdown-menu-sm dropdown-menu-right">';
								echo '<ul class="navi flex-column navi-hover py-2">';
									echo '<li class="navi-header font-weight-bolder text-uppercase font-size-sm text-primary pb-2">Choose an option:</li>';
									if ($print == 1) //put more if got different type of print option
									{
										echo '
										<li class="navi-item">
											<a href="javascript:;" class="navi-link" id="printExcel" value="1,1">
												<span class="navi-icon">
													<i class="la la-file-excel-o"></i>
												</span>
												<span class="navi-text">Excel</span>
											</a>
										</li>
										<li class="navi-item">
											<a href="javascript:;" class="navi-link" id="printPdf" value="1,0">
												<span class="navi-icon">
													<i class="la la-file-pdf-o"></i>
												</span>
												<span class="navi-text">PDF</span>
											</a>
										</li>
										';
									}
									else if ($print == 2) //put more if got different type of print option
									{
										echo '
										<li class="navi-item">
											<a href="javascript:;" class="navi-link" id="printExcel" value="1,1">
												<span class="navi-icon">
													<i class="la la-file-excel-o"></i>
												</span>
												<span class="navi-text">Excel</span>
											</a>
										</li>
										';
									}
									else if ($print == 3) //put more if got different type of print option
									{
										echo '
										<li class="navi-item">
											<a href="javascript:;" class="navi-link" id="printPdf" value="1,0">
												<span class="navi-icon">
													<i class="la la-file-pdf-o"></i>
												</span>
												<span class="navi-text">PDF</span>
											</a>
										</li>
										';
									}
									else if ($print == 4) //put more if got different type of print option
									{
										echo '
										<li class="navi-item">
											<a href="javascript:;" class="navi-link" id="'.$name.'_printPdf" value="1,0">
												<span class="navi-icon">
													<i class="la la-file-pdf-o"></i>
												</span>
												<span class="navi-text">PDF</span>
											</a>
										</li>
										';
									}
								echo '</ul>';
							echo '</div>';
						echo '</div>';
					}
					echo $userBtn;
					if($modalName != '')
					{
						$all_modal = explode(';', $modalName);
						for($num = 0; $num < count($all_modal); $num++)
						{
							createModal($all_modal[$num]);
						}
					}
				echo '</div>';
			echo '</div>';
			
			echo '<div class="card-body">';
				echo '<table class="table table-separate table-head-custom table-checkable" id="'.$name.'" name="'.$name.'">';
					echo '<thead>';
						echo '<tr>';
							foreach ($columns as $item)
							{
								echo '<th>'.$item[0].'</th>';
							}
						echo '</tr>';
					echo '</thead>';
					echo '<tbody>';
					echo '</tbody>';
				echo '</table>';
			echo '</div>';
			
			//some hidden input here for print purpose
			if($setHiddenInput)
			{
				if ($print == 4)
				{
					echo '<input type="hidden" id="'.$name.'_table_name" value="'.$name.'"/>';
					echo '<input type="hidden" id="'.$name.'_table_title" value="'.$title.'"/>';
					echo '<input type="hidden" id="'.$name.'_table_header" value=\''.json_encode($columns).'\'/>';
				}
				else
				{
					echo '<input type="hidden" id="table_name" value="'.$name.'"/>';
					echo '<input type="hidden" id="table_title" value="'.$title.'"/>';
					echo '<input type="hidden" id="table_header" value=\''.json_encode($columns).'\'/>';
				}
			}
			
		echo '</div>';
	echo '</div>';
}
//done
function createModal($modalName='ajax-modal', $style = '')
{
	echo '<div class="modal fade" id="'.$modalName.'" role="dialog" aria-labelledby="'.$modalName.'" aria-hidden="true" >';
		echo '<div class="modal-dialog modal-dialog-centered modal-xl" role="document" style="'.$style.'">';
			echo '<div id="'.$modalName.'_content" class="modal-content">										 ';
			echo '<!-- Content loading  modal-Header  modal-Body  modal-footer from ajax-->';
			echo '</div>';
		echo '</div>';
	echo '</div>';
}

//*****************************************
//FUNCTION for PDO INSERT, UPDATE
//*****************************************
function createInsertQuery($tableName, $myData)
{
	$qMark = '';
	$out = 'INSERT INTO '.$tableName.' (';
	foreach ($myData as $item)
	{
		$out .= $item[0].', ';
		$qMark .= '?,';
	}
	$out = rtrim($out, ", "); //remove tailing comma
	$out .= ') VALUES ('.rtrim($qMark, ",").')';
	return $out;
}

function createUpdateQuery($tableName, $myData, $whereCondition)
{
	$qMark = '';
	$out = 'UPDATE '.$tableName.' SET ';
	foreach ($myData as $item)
	{
		$out .= $item[0].' = ?, ';
	}
	$out = rtrim($out, ", "); //remove tailing comma
	$out .= ' '.$whereCondition;
	return $out;
}

function PDO_INSERT($PDO, $tableName, $dataArray)
{
	$PDO_stmt = $PDO->prepare(createInsertQuery($tableName, $dataArray));
	foreach($dataArray as $key=>$val)
	{
		$PDO_stmt->bindValue($key+1, (($val[3]==1)?$val[1]:strtoupper($val[1])), $val[2]);
	}
	
	return $PDO_stmt->execute();
}

function PDO_UPDATE($PDO, $tableName, $dataArray, $WHERE_CONDITION)
{
	$PDO_stmt = $PDO->prepare(createUpdateQuery($tableName, $dataArray, $WHERE_CONDITION));
	foreach($dataArray as $key=>$val)
	{
		$PDO_stmt->bindValue($key+1, (($val[3]==1)?$val[1]:strtoupper($val[1])), $val[2]);
	}
	
	return $PDO_stmt->execute();
}

function PDO_INSERT_AUDIT($PDO, $tableName, $dataArray, $id_pemohon, $id_table, $id_keyin=0, $tkh_keyin='0000-00-00 00:00:00', $auditOnly=0)
{
	$INSERT_QUERY = "INSERT INTO s_boranglog (id_pemohon, aktiviti, nama_table, nama_field, makl_baru, id_keyin, tkh_keyin, ip_add, nama_komputer, id_table) VALUES ";
	foreach($dataArray as $key=>$val)
	{
		$INSERT_QUERY .= '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?),';
	}
	$INSERT_QUERY = rtrim($INSERT_QUERY, ","); //remove tailing comma
	$ip_add = $_SERVER['REMOTE_ADDR'];
	$nama_komputer = gethostname();
	$counter = 0;
	$PDO_stmt = $PDO->prepare($INSERT_QUERY);
	foreach($dataArray as $key=>$val)
	{
		$PDO_stmt->bindValue($counter + 1, $id_pemohon, PDO::PARAM_INT); //id_pemohon
		$PDO_stmt->bindValue($counter + 2, 'I', PDO::PARAM_STR); //aktiviti
		$PDO_stmt->bindValue($counter + 3, $tableName, PDO::PARAM_STR); //nama_table
		$PDO_stmt->bindValue($counter + 4, $val[0], PDO::PARAM_STR); //nama_field
		$PDO_stmt->bindValue($counter + 5, strtoupper($val[1]), PDO::PARAM_STR); //makl_baru
		$PDO_stmt->bindValue($counter + 6, $id_keyin, PDO::PARAM_INT); //id_keyin
		$PDO_stmt->bindValue($counter + 7, $tkh_keyin, PDO::PARAM_STR); //tkh_keyin
		$PDO_stmt->bindValue($counter + 8, $ip_add, PDO::PARAM_STR); //ip_add
		$PDO_stmt->bindValue($counter + 9, $nama_komputer, PDO::PARAM_STR); //nama_komputer
		$PDO_stmt->bindValue($counter + 10, $id_table, PDO::PARAM_INT); //id_table
		$counter += 10;
	}
	
	if($auditOnly == 1)
	{
		return $PDO_stmt->execute();
	}
	else
	{
		return $PDO_stmt->execute() && PDO_INSERT($PDO, $tableName, $dataArray);
	}
}

function PDO_UPDATE_AUDIT($PDO, $tableName, $dataArray, $WHERE_CONDITION, $id_pemohon, $id_table, $id_keyin=0, $tkh_keyin='0000-00-00 00:00:00', $auditOnly=0, $id_anakemas=0, $id_pelajaremas=0)
{
	$SELECT_QUERY = 'SELECT ';
	foreach($dataArray as $key=>$val)
	{
		$SELECT_QUERY .= $val[0].',';
	}
	$SELECT_QUERY = rtrim($SELECT_QUERY, ","); //remove tailing comma
	$SELECT_QUERY .= ' FROM '.$tableName.' '.$WHERE_CONDITION;
	$PDO_stmt2 = $PDO->prepare($SELECT_QUERY);
	
	//$PDO_stmt->bindValue(1, $tempid, PDO::PARAM_STR);
	//$PDO_stmt->bindValue(2, $temppass, PDO::PARAM_STR);
	$PDO_stmt2->execute();
	$result = $PDO_stmt2->fetch(PDO::FETCH_ASSOC);
	
	$numOfChanges = 0;
	$INSERT_QUERY = "INSERT INTO s_boranglog (id_pemohon, aktiviti, nama_table, nama_field, makl_asal, makl_baru, id_keyin, tkh_keyin, ip_add, nama_komputer, id_table, id_anakemas, id_pelajaremas) VALUES ";
	
	foreach($dataArray as $key=>$val)
	{
		if($val[0] != 'tkh_kemaskini') //ignore this field
		{
			if(strtoupper($result[$val[0]]) != strtoupper($val[1]))
			{
				$INSERT_QUERY .= '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?),';
				$numOfChanges++;
			}
		}
	}
	$INSERT_QUERY = rtrim($INSERT_QUERY, ","); //remove tailing comma
	
	if($numOfChanges > 0)
	{
		$ip_add = $_SERVER['REMOTE_ADDR'];
		$nama_komputer = gethostname();
		$counter = 0;
		$PDO_stmt = $PDO->prepare($INSERT_QUERY);
		foreach($dataArray as $key=>$val)
		{
			if($val[0] != 'tkh_kemaskini') //ignore this field
			{
				if(strtoupper($result[$val[0]]) != strtoupper($val[1]))
				{
					$PDO_stmt->bindValue($counter + 1, $id_pemohon, PDO::PARAM_INT); //id_adun
					$PDO_stmt->bindValue($counter + 2, 'U', PDO::PARAM_STR); //aktiviti
					$PDO_stmt->bindValue($counter + 3, $tableName, PDO::PARAM_STR); //nama_table
					$PDO_stmt->bindValue($counter + 4, $val[0], PDO::PARAM_STR); //nama_field
					$PDO_stmt->bindValue($counter + 5, $result[$val[0]], PDO::PARAM_STR); //makl_asal
					$PDO_stmt->bindValue($counter + 6, strtoupper($val[1]), PDO::PARAM_STR); //makl_baru
					$PDO_stmt->bindValue($counter + 7, $id_keyin, PDO::PARAM_INT); //id_keyin
					$PDO_stmt->bindValue($counter + 8, $tkh_keyin, PDO::PARAM_STR); //tkh_keyin
					$PDO_stmt->bindValue($counter + 9, $ip_add, PDO::PARAM_STR); //ip_add
					$PDO_stmt->bindValue($counter + 10, $nama_komputer, PDO::PARAM_STR); //nama_komputer
					$PDO_stmt->bindValue($counter + 11, $id_table, PDO::PARAM_INT); //id_table
					$PDO_stmt->bindValue($counter + 12, $id_anakemas, PDO::PARAM_INT); //id_anakemas
					$PDO_stmt->bindValue($counter + 13, $id_pelajaremas, PDO::PARAM_INT); //id_pelajaremas
					$counter += 13;
				}
			}
		}
		
		if($auditOnly == 1)
		{
			return $PDO_stmt->execute();
		}
		else
		{
			return $PDO_stmt->execute() && PDO_UPDATE($PDO, $tableName, $dataArray, $WHERE_CONDITION);
		}
	}
	else
	{
		return PDO_UPDATE($PDO, $tableName, $dataArray, $WHERE_CONDITION);
	}
}

function PDO_UPDATE_INDIKATOR_AUDIT($PDO, $tableName, $id_indikator, $dataArray, $WHERE_CONDITION, $id_update=0, $id_peranan=0, $tkh_update='0000-00-00 00:00:00')
{
	$SELECT_QUERY = 'SELECT ';
	foreach($dataArray as $key=>$val)
	{
		$SELECT_QUERY .= $val[0].',';
	}
	$SELECT_QUERY = rtrim($SELECT_QUERY, ","); //remove tailing comma
	$SELECT_QUERY .= ' FROM '.$tableName.' '.$WHERE_CONDITION;
	$PDO_stmt2 = $PDO->prepare($SELECT_QUERY);
	
	//$PDO_stmt->bindValue(1, $tempid, PDO::PARAM_STR);
	//$PDO_stmt->bindValue(2, $temppass, PDO::PARAM_STR);
	$PDO_stmt2->execute();
	$result = $PDO_stmt2->fetch(PDO::FETCH_ASSOC);
	
	$changesList_lama = [];
	$changesList_baru = [];
	$INSERT_QUERY = "INSERT INTO s_updatelog (table_name, id_indikator, item_lama, item_baru, id_update, id_peranan, tkh_update, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
	foreach($dataArray as $key=>$val)
	{
		if($val[0] != 'update_datetime') //ignore this field
		{
			if(strtoupper($result[$val[0]]) != strtoupper($val[1]))
			{
				$changesList_lama[] = array($val[0], strtoupper($result[$val[0]]));
				$changesList_baru[] = array($val[0], strtoupper($val[1]));
			}
		}
	}
	
	if(count($changesList_lama) > 0)
	{
		$ip_add = $_SERVER['REMOTE_ADDR'];
		$PDO_stmt = $PDO->prepare($INSERT_QUERY);
		$PDO_stmt->bindValue(1, $tableName, PDO::PARAM_STR); //nama_table
		$PDO_stmt->bindValue(2, $id_indikator, PDO::PARAM_STR); //id_indikator
		$PDO_stmt->bindValue(3, json_encode($changesList_lama), PDO::PARAM_STR); //item_lama
		$PDO_stmt->bindValue(4, json_encode($changesList_baru), PDO::PARAM_STR); //item_baru
		$PDO_stmt->bindValue(5, $id_update, PDO::PARAM_INT); //id_update
		$PDO_stmt->bindValue(6, $id_peranan, PDO::PARAM_STR); //id_peranan
		$PDO_stmt->bindValue(7, $tkh_update, PDO::PARAM_STR); //tkh_update
		$PDO_stmt->bindValue(8, $ip_add, PDO::PARAM_STR); //ip_add
	
		return $PDO_stmt->execute() && PDO_UPDATE($PDO, $tableName, $dataArray, $WHERE_CONDITION);
	}
	else
	{
		return PDO_UPDATE($PDO, $tableName, $dataArray, $WHERE_CONDITION);
	}
}

function PDO_DELETE($PDO, $tableName, $WHERE_CONDITION)
{
	$PDO_stmt = $PDO->prepare("DELETE FROM $tableName $WHERE_CONDITION");
	return $PDO_stmt->execute();
}

function PDO_INSERT_ACTION_AUDIT($PDO, $id_pemohon=0, $id_audit=0, $id_keyin=0, $id_peranan=0, $tkh_keyin='0000-00-00 00:00:00', $id_jabatan=0, $id_dun=0, $id_daerah=0, $ulasan='', $id_anakemas=0, $id_pelajaremas=0, $id_parlimen=0, $id_program=0)
{
	$updateLog_Array = array();
	$updateLog_Array[] = array('id_pemohon', $id_pemohon, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_program', $id_program, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_audit', $id_audit, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_keyin', $id_keyin, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_peranan', $id_peranan, PDO::PARAM_STR);
	$updateLog_Array[] = array('tkh_keyin', $tkh_keyin, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_jabatan', $id_jabatan, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_parlimen', $id_parlimen, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_dun', $id_dun, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_daerah', $id_daerah, PDO::PARAM_STR);
	$updateLog_Array[] = array('ulasan', $ulasan, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_anakemas', $id_anakemas, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_pelajaremas', $id_pelajaremas, PDO::PARAM_STR);
	$updateLog_Array[] = array('ip_address', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
	
	return PDO_INSERT($PDO, 's_auditlog', $updateLog_Array); //to execute and get status of the execute, if fail 0, true 1
}

function PDO_INSERT_ACTION_ASSIGN($PDO, $id_aduan=0, $id_assignasal=0, $id_assignbaru=0, $id_keyin=0, $tkh_keyin='0000-00-00 00:00:00')
{
	$updateLog_Array = array();
	$updateLog_Array[] = array('id_aduan', $id_aduan, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_assignasal', $id_assignasal, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_assignbaru', $id_assignbaru, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_keyin', $id_keyin, PDO::PARAM_STR);
	$updateLog_Array[] = array('tkh_keyin', $tkh_keyin, PDO::PARAM_STR);
	
	return PDO_INSERT($PDO, 's_aduanassignlog', $updateLog_Array); //to execute and get status of the execute, if fail 0, true 1
}

function PDO_INSERT_EFT_AUDIT($PDO, $id_pemohon=0, $id_audit=0, $id_keyin=0, $id_peranan=0, $tkh_keyin='0000-00-00 00:00:00', $id_jabatan=0, $id_dun=0, $id_daerah=0, $ulasan='', $id_anakemas=0, $id_pelajaremas=0, $id_parlimen=0, $id_program=0)
{
	$eftLog_Array = array();
	$eftLog_Array[] = array('id_pemohon', $id_pemohon, PDO::PARAM_INT);
	$eftLog_Array[] = array('id_program', $id_program, PDO::PARAM_INT);
	$eftLog_Array[] = array('id_audit', $id_audit, PDO::PARAM_INT);
	$eftLog_Array[] = array('id_keyin', $id_keyin, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_peranan', $id_peranan, PDO::PARAM_STR);
	$eftLog_Array[] = array('tkh_keyin', $tkh_keyin, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_jabatan', $id_jabatan, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_parlimen', $id_parlimen, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_dun', $id_dun, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_daerah', $id_daerah, PDO::PARAM_STR);
	$eftLog_Array[] = array('ulasan', $ulasan, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_anakemas', $id_anakemas, PDO::PARAM_STR);
	$eftLog_Array[] = array('id_pelajaremas', $id_pelajaremas, PDO::PARAM_STR);
	$eftLog_Array[] = array('ip_address', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
	
	return PDO_INSERT($PDO, 's_eftlog', $eftLog_Array); //to execute and get status of the execute, if fail 0, true 1
}
# --------------------------------------------
# convert normal date into db format
# --------------------------------------------
function convertToDBDate($date) {
	$day = substr ($date, 0, 2);
	$month = substr ($date, 3, 2);
	$year = substr ($date, 6, 4);
	$newdate = $year."-".$month."-".$day;
	if($date != ""){
		if(strlen($date) > 11) //date with time
			$newdate = $newdate." ".substr($date, 11, 8);
		return $newdate;
	}
}

function insertUpdateLog($PDO, $id_table, $id_indikator, $item_lama, $item_baru, $id_update=0, $id_peranan=0, $tkh_update='0000-00-00 00:00:00')
{
	$updateLog_Array = array();
	$updateLog_Array[] = array('id_table', $id_table, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_indikator', $id_indikator, PDO::PARAM_INT);
	$updateLog_Array[] = array('item_lama', $item_lama, PDO::PARAM_INT);
	$updateLog_Array[] = array('item_baru', $item_baru, PDO::PARAM_INT);
	$updateLog_Array[] = array('id_update', $id_update, PDO::PARAM_STR);
	$updateLog_Array[] = array('id_peranan', $id_peranan, PDO::PARAM_STR);
	$updateLog_Array[] = array('tkh_update', $tkh_update, PDO::PARAM_STR);
	$updateLog_Array[] = array('ip_address', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR);
	
	return PDO_INSERT($PDO, 's_updatelog', $updateLog_Array); //to execute and get status of the execute, if fail 0, true 1
}

function generatePassword($length = 10, $available_sets = 'luds')
{
	$sets = array();
	if(strpos($available_sets, 'l') !== false)
		$sets[] = 'abcdefghjkmnpqrstuvwxyz';
	if(strpos($available_sets, 'u') !== false)
		$sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
	if(strpos($available_sets, 'd') !== false)
		$sets[] = '23456789';
	if(strpos($available_sets, 's') !== false)
		$sets[] = '!@#$_';
	$all = '';
	$password = '';
	foreach($sets as $set)
	{
		$password .= $set[array_rand(str_split($set))];
		$all .= $set;
	}
	$all = str_split($all);
	for($i = 0; $i < $length - count($sets); $i++)
		$password .= $all[array_rand($all)];
	$password = str_shuffle($password);
	return $password;
}

function startsWith($haystack, $needle) {
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false;
}

function createDynamicInput($PDO, $item, $indicator_List, $base_name='', $div_key='')
{
	switch ($item['id_inputtype']) 
	{
		case '1': //textbox
			createTextBox($item['label'], $item['input_name'], $item['placeholder']!=''?$item['placeholder']:$item['label'], $indicator_List[$item['value']], $item['label_size'], $readonly, $item['input_size'], $item['div_size'], $item['extra_param'], 'text');
			break;
		case '2': //dropdown
			createDropDown($PDO, $item['label'], $item['extra_param'], $item['input_name'], $indicator_List[$item['value']], $item['placeholder'], $item['input_size'], $item['label_size'], $item['div_size'], $readonly);
			break;
		case '3': //dropdown_sql
			createDropDown_sql($PDO, $item['label'], $item['extra_param'], $item['input_name'], $indicator_List[$item['value']], $item['placeholder'], $item['input_size'], $item['label_size'], $item['div_size'], $readonly);
			break;
		case '5': //custom
			echo $item['extra_param'];
			break;
		case '6': //action pass
			$actionArray['passAction_'.$counter][] = $item['value'];
			//echo '<input type="hidden" id="passAction_'.$counter.'" value=\''.$item['value'].'\'>';
			break;
		case '7': //action insert
			//script_url<BRE>borang_div<BRE>table_name<BRE>id_table<BRE>id_insert<BRE>id_update
			$action_value = ($base_name.'-insert.php').'<BRE>'.$div_key.'<BRE>'.$item['value'];
			echo '<input type="hidden" id="saveAction_'.$counter.'" value=\''.$action_value.'\'>';
			break;
		case '8': //textbox uncopyable
			createTextBox($item['label'], $item['input_name'], $item['placeholder']!=''?$item['placeholder']:$item['label'], $indicator_List[$item['value']], $item['label_size'], $readonly, $item['input_size'], $item['div_size'], $item['extra_param'], 'text', '', ' oncopy="return false" onpaste="return false" ');
			break;
		case '9': //action check equal
			$actionArray['equalAction_'.$counter][] = $item['value'];
			//echo '<input type="hidden" id="equalAction_'.$counter.'" value=\''.$item['value'].'\'>';
			break;
		case '10': //action hide if match value
			//borang_carabayar<HIDE>1<HIDE>borang_no_akaun
			$jsItem = explode('<HIDE>', $item['value']);
			$actionJS[$jsItem[0]]['value'] = $jsItem[1];
			$actionJS[$jsItem[0]]['item'][] = $jsItem[2];
			break;
		case '11': //datatable
			//get column here
			$tbColumn = array();
			$tbColumn[] = array('Bil', 15);
			$indicator_Query = "SELECT *
							  FROM u_datatableitem 
							  WHERE id_borangitem = ?
							  ORDER BY datatable_index";
			$PDO_stmt = $PDO->prepare($indicator_Query);
			$PDO_stmt->bindValue(1, $item['id_borangitem'], PDO::PARAM_STR);
			$PDO_stmt->execute();
			while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
			{
				$tbColumn[] = array($result['column_label'], 10);
			}
			
			//some hardcode value replacement here, too bad
			$item['extra_param'] = str_replace('<tambahForm>', $base_name.'-tambah.php?id=0&borangitem'.$item['id_borangitem'], $item['extra_param']);
			$item['extra_param'] = str_replace('<tambahBtnSvg>', $tambahBtnSvg, $item['extra_param']);
			$item['extra_param'] = str_replace('<dtModal>', $item['input_name'].'-modal', $item['extra_param']);
			
			createTable($item['input_name'], $tbColumn, $item['label'], $item['placeholder'], 0, $item['extra_param'], $item['input_name'].'-modal', $item['div_size']);
			$datatableJS[] = $item;
		case '12': //hidden input
			echo '<input type="hidden" id="'.$item['input_name'].'" value=\''.$indicator_List[$item['value']].'\'>';
			break;
	  default:
		echo '';
	}
}

function checkToken($PDO, $usr_id, $server_token){
    $pengguna_Query = "SELECT id_pemohon FROM t_pemohon WHERE id_pemohon = ? AND app_token = ?";
    $PDO_stmt = $PDO->prepare($pengguna_Query);
    $PDO_stmt->bindValue(1, $usr_id, PDO::PARAM_INT);
    $PDO_stmt->bindValue(2, $server_token, PDO::PARAM_STR);
    $PDO_stmt->execute();
    $pengguna_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC); 
	if ($pengguna_List['id_pemohon'] > 0){
		return $pengguna_List['id_pemohon'];
	}
	else{
		return -1;
	}    
}

/* 
1.Warta from senarai pemohon
2.Laporan Penerima Bayaran - dokumen jumlah, dokumen peruntukan
3.Eft check & sahkan
4.Cetak voucher tunai, senarai buku bank & senarai nama
*/
function getNonBayarTunaiQuery($PDO, $select_column, $cutoff, $cutoff_saheft, $tahun_bayar, $cutoff_aktif) //belum bayar tunai
{
	//to get tunai
	$BELUM_BAYAR_TUNAI_FROM_QUERY = "
	{$select_column}
	FROM m_pemohon A
	LEFT JOIN i_dun ON A.id_dun = i_dun.id_dun 
	LEFT JOIN i_daerah ON i_dun.id_daerah = i_daerah.id_daerah 
	LEFT JOIN m_waris ON A.id_pemohon = m_waris.id_pemohon AND m_waris.status = 1
	WHERE 
	A.id_rumahorgtua = 0 
	AND A.id_dun != 0 
	AND A.id_statusmohon = 4 
	AND A.id_statushidup = 1 
	AND A.id_aktifmohon = 1 
	AND (A.tkh_aktifmohon = '0000-00-00 00:00:00' OR A.tkh_aktifmohon <= '{$cutoff_aktif} 23:59:59')
	AND A.tkh_sah <= '{$cutoff} 23:59:59' 
	AND (A.tkh_saheft = '0000-00-00 00:00:00' OR A.tkh_saheft > '{$cutoff_saheft} 23:59:59')
	";
	/*
	$PDO_stmt = $PDO->prepare("
		SELECT *
		FROM i_program
		WHERE aktif = 1
		AND id_program IN (1,2,4,7)
	");
	$PDO_stmt->execute();
	while($res = $PDO_stmt->fetch(PDO::FETCH_ASSOC)) //to check if exist tahun bayaran in other program we/ie/it/oku
	{
		$mbayar_table = "m_bayaran_".$res['kod_program'];
		$BELUM_BAYAR_TUNAI_FROM_QUERY .= ' AND A.id_pemohon NOT IN (SELECT id_pemohon FROM '.$mbayar_table.' WHERE tahun_bayar = '.$tahun_bayar.') ';
	}
	*/
	$BELUM_BAYAR_TUNAI_FROM_QUERY .= ' AND A.id_pemohon NOT IN (SELECT id_pemohon FROM l_penerima) ';
	
	return $BELUM_BAYAR_TUNAI_FROM_QUERY;
}

function getNonBayarEftQuery($PDO, $select_column, $cutoff, $cutoff_saheft, $tahun_bayar, $cutoff_aktif) //belum bayar eft
{
	$BELUM_BAYAR_EFT_FROM_QUERY = "
	{$select_column}
	FROM m_pemohon A
	LEFT JOIN i_dun ON A.id_dun = i_dun.id_dun 
	LEFT JOIN i_daerah ON i_dun.id_daerah = i_daerah.id_daerah 
	LEFT JOIN m_waris ON A.id_pemohon = m_waris.id_pemohon AND m_waris.status = 1
	WHERE 
	(A.id_carabayar = 2 OR A.id_byrkepada = 2) 
	AND A.id_rumahorgtua = 0 
	AND A.id_dun != 0 
	AND A.id_statusmohon = 4 
	AND A.id_statushidup = 1 
	AND A.id_aktifmohon = 1 
	AND (A.tkh_aktifmohon = '0000-00-00 00:00:00' OR A.tkh_aktifmohon <= '{$cutoff_aktif} 23:59:59')
	AND A.tkh_sah <= '{$cutoff} 23:59:59' 
	AND A.tkh_saheft != '0000-00-00 00:00:00' 
	AND A.tkh_saheft <= '{$cutoff_saheft} 23:59:59'
	";
 
	//to check inside all program
	/*
	$PDO_stmt = $PDO->prepare("
		SELECT *
		FROM i_program
		WHERE aktif = 1
		AND id_program IN (1,2,4,7)
	");
	$PDO_stmt->execute();
	while($res = $PDO_stmt->fetch(PDO::FETCH_ASSOC)) //to check if exist tahun bayaran in other program we/ie/it/oku
	{
		$mbayar_table = "m_bayaran_".$res['kod_program'];
		$BELUM_BAYAR_EFT_FROM_QUERY .= ' AND A.id_pemohon NOT IN (SELECT id_pemohon FROM '.$mbayar_table.' WHERE tahun_bayar = '.$tahun_bayar.') ';
	}
	*/
	$BELUM_BAYAR_EFT_FROM_QUERY .= ' AND A.id_pemohon NOT IN (SELECT id_pemohon FROM l_penerima) ';
	
	return $BELUM_BAYAR_EFT_FROM_QUERY;	
}

function getNonBayarTunaiQuery_meninggal($PDO, $select_column, $cutoff, $cutoff_saheft, $tahun_bayar, $cutoff_aktif) //belum bayar tunai
{
	//to get tunai
	$BELUM_BAYAR_TUNAI_FROM_QUERY = "
	{$select_column}
	FROM m_pemohon A
	LEFT JOIN i_dun ON A.id_dun = i_dun.id_dun 
	LEFT JOIN i_daerah ON i_dun.id_daerah = i_daerah.id_daerah 
	WHERE A.id_dun != 0 
	AND A.id_statushidup = 2 
	AND (A.tkh_aktifmohon = '0000-00-00 00:00:00' OR A.tkh_aktifmohon <= '{$cutoff_aktif} 23:59:59')
	AND A.tkh_sah <= '{$cutoff} 23:59:59' 
	AND (A.tkh_saheft = '0000-00-00 00:00:00' OR A.tkh_saheft > '{$cutoff_saheft} 23:59:59')
	";
	$BELUM_BAYAR_TUNAI_FROM_QUERY .= ' AND A.id_pemohon NOT IN (SELECT id_pemohon FROM l_penerima) ';
	
	return $BELUM_BAYAR_TUNAI_FROM_QUERY;
}

function getNonBayarEftQuery_meninggal($PDO, $select_column, $cutoff, $cutoff_saheft, $tahun_bayar, $cutoff_aktif) //belum bayar eft
{
	$BELUM_BAYAR_EFT_FROM_QUERY = "
	{$select_column}
	FROM m_pemohon A
	LEFT JOIN i_dun ON A.id_dun = i_dun.id_dun 
	LEFT JOIN i_daerah ON i_dun.id_daerah = i_daerah.id_daerah 
	WHERE (A.id_carabayar = 2 OR A.id_byrkepada = 2) 
	AND A.id_dun != 0 
	AND A.id_statushidup = 2 
	AND (A.tkh_aktifmohon = '0000-00-00 00:00:00' OR A.tkh_aktifmohon <= '{$cutoff_aktif} 23:59:59')
	AND A.tkh_sah <= '{$cutoff} 23:59:59' 
	AND A.tkh_saheft != '0000-00-00 00:00:00' 
	AND A.tkh_saheft <= '{$cutoff_saheft} 23:59:59'
	";
	$BELUM_BAYAR_EFT_FROM_QUERY .= ' AND A.id_pemohon NOT IN (SELECT id_pemohon FROM l_penerima) ';
	
	return $BELUM_BAYAR_EFT_FROM_QUERY;	
}