<?php
	class DbQuery extends Db
	{
		var $result;
		
		private function bindArrayValue($array, $query, $typeArray = false)
		{
			if(is_object($query) && ($query instanceof PDOStatement))
			{
				foreach($array as $keys => $value)
				{
					
					$key = str_replace('.','_',$keys);
					$key = str_replace('-','_',$key);
					//$key = str_replace('LOWER(','',$key);
					//$key = str_replace(')','',$key);
					if($typeArray)
						$query->bindValue(":$key",$value,$typeArray[$key]);
					else
					{
						if(is_int($value))
							 $param = PDO::PARAM_INT;
						elseif(is_bool($value))
							 $param = PDO::PARAM_BOOL;
						elseif(is_null($value))
							 $param = PDO::PARAM_NULL;
						elseif(is_string($value))
							 $param = PDO::PARAM_STR;
						else
							$param = PDO::PARAM_NULL;
						
						$query->bindValue(":$key",$value,$param);
						//if($param)
							//echo 'here';
							
					}
				}
				
			}
			
		}

		function insert($param,$lastInsert=null) 
		{
			$db = new Db('w');
			$db->db_connect();
			if(empty($param))
			{
				return false;
			}
			$columnName='';
			$columeValue='';
			$numItems = count($param['field']);
			$i = 0; $valueArray=array();
			foreach($param['field'] as $key => $value)
			{
				$columnName .= $key;
				$columeValue .= ":$key";
				if(++$i === $numItems) {
					$columnName .='';
					$columeValue .= '';	
				}
				else{
					$columnName .=',';
					$columeValue .= ',';
				}	
				$valueArray[]= $value;
			}		
			
			//echo "INSERT INTO tab_".$param['table']."(".$columnName.") VALUES (".$columeValue.")";
			$query = $db->db_query("INSERT INTO tab_".$param['table'].'s'." (".$columnName.") VALUES (".$columeValue.")");
			$this->bindArrayValue($param['field'],$query);
			if ($query->execute()){
				if($lastInsert!=null)
				{
					$table = 'tab_'.$param['table'].'s';
					if($lastInsert == 'ID'){
					$uniqueid = 'ID';	
					}
					else if($lastInsert == 'user_id')
					{
					$uniqueid = 'user_id';
					}
					else{
					$uniqueid = 'int_'.$param['table'].'_id';
					}
					return $db->get_lastInsertId($table,$uniqueid);
				}
				
				return true;
			}else{ 
				$failedTable = array(
					'tablename'=>$param['table'],
					'query'=>$query,
					'value'=>implode(' ',$valueArray),
				);
				$this->dbErrorLog($failedTable);
				return false;
			}
		}

		function update($param) 
		{
			$db = new Db('w');
			$db->db_connect();
			$tableOther = '';
			$columnName='';
			$count = count($param['field']);
			$countloop=1;
			foreach($param['field'] as $key => $value)
			{
				$columnName .= $key."=:$key";
				if ($countloop === $count){
					$columnName .='';
				}
				else{
					$columnName .=',';
				}		
				$countloop++;	
			}
			$columnwhere=''; $whereopecount=0; $valueArray = array();
			foreach($param['where'] as $key => $value)
			{
				$operator='';
				if(isset($param['whereOperator'][$whereopecount]))
				{
					$operator = $param['whereOperator'][$whereopecount];
				}
				$columnwhere .= $key."=:$key ".$operator;
				$whereopecount++;
				$valueArray[]= $value;
			}
			if(isset($param['other']))
			{
				$tableOther=$param['other'];
			}		
			$query = $db->db_query("UPDATE tab_".$param['table']."s SET ".$columnName." where ".$columnwhere." ".$tableOther);
			$this->bindArrayValue($param['field'],$query);
			$this->bindArrayValue($param['where'],$query);
			if ($query->execute()){
				return true;
			}else{
				$failedTable = array(
					'tablename'=>$param['table'],
					'query'=>$query,
					'value'=>implode(' ',$valueArray),
				);
				$this->dbErrorLog($failedTable);
				return false;
			}
		}

		function delete($param) 
		{
			return $this->select($param,'delete');
		}

		function truncate($tableName) 
		{
			$db = new Db('s');
			$db->db_connect();

			$query = $db->db_query("TRUNCATE ".'tab_'.$tableName.'s');
			if ($query->execute()){
				return true;
			}else{
				return false;
			}
		}


		function select($param,$type) 
		{
			$db = new Db('r');
			$db->db_connect();
			$tableOther='';
			$tableFrom='';	
			$tablewhere='';
			$valueArray =array();
			
			if(isset($param['table']))
			{
				if(isset($param['joinTable']))
				{
					if(isset($param['alias']))
					{
						$tableFrom = 'tab_'.$param['table'].'s AS '.strtoupper($param['alias']);
					}else{
						$tableFrom = 'tab_'.$param['table'].'s AS '.strtoupper($param['table']);
					}
				}else{
					$tableFrom = 'tab_'.$param['table'].'s';
				}
			}
			if(isset($param['joinTable']))
			{
				$joinTable = $param['joinTable'];
				$count = count($joinTable);
				for($i=0;$i<$count;$i++)
				{
					if(isset($joinTable[$i]['alias'])){
						$tableFrom .= ' '.$joinTable[$i]['join'].' JOIN '. 'tab_'.$joinTable[$i]['table'].'s as '.strtoupper($joinTable[$i]['alias']).' ON '.$joinTable[$i]['firstTable'].' = '.$joinTable[$i]['secondTable'];
					}else{
						$tableFrom .= ' '.$joinTable[$i]['join'].' JOIN '. 'tab_'.$joinTable[$i]['table'].'s as '.strtoupper($joinTable[$i]['table']).' ON '.$joinTable[$i]['firstTable'].' = '.$joinTable[$i]['secondTable'];
					}
					
				}
			}
			if(isset($param['where']))
			{
				$tablewhere ='WHERE ';
				$where = $param['where'];
				
				$whereTable = array_keys($where);
				 $count = count($where);
				for($i=0;$i<$count;$i++)
				{
					$operator='';
					if(isset($param['whereOperator'][$i]))
					{
						$operator = $param['whereOperator'][$i];
					}
					if(isset($param['operator'][$i]) && !empty($param['operator'][$i])){
						$signoperate= $param['operator'][$i];
					}else{
						$signoperate =' = ';
					}
					$valparm = str_replace('.','_',$whereTable[$i]);
					$valparm = str_replace('-','_',$valparm);
					$valueArray[]=$valparm;
					//$valparm = str_replace('LOWER(','',$kvalparmey);
					//$valparm = str_replace(')','',$valparm);
					$tabelField = explode('-',$whereTable[$i]);
					$tablewhere .= $tabelField[0] .' '.$signoperate.' :'.$valparm.' '.$operator .' ';
				}
			}

			if(isset($param['other']))
			{
				$tableOther=$param['other'];
			}
			
			if($type=='delete')
			{
				//echo "DELETE FROM ".$tableFrom .' '. $tablewhere;
				$query = $db->db_query("DELETE FROM ".$tableFrom .' '. $tablewhere);
			
			}else{
			//echo '<br/>';print_r("select ".$param['get']." from ".$tableFrom .' '. $tablewhere);echo '<br/>';
			$query = $db->db_query("SELECT ".$param['get']." FROM ".$tableFrom .' '. $tablewhere.' '. $tableOther);
			}
			//print_r($query); exit;
			if(isset($param['where']))
			{
				$this->bindArrayValue($param['where'],$query);
			}
			//print_r($query);// exit;
			if($query->execute())
			{
				if($type=='delete')
				{
					return true;	
				}		
				//echo $db->get_num_rows($query);
				if($db->get_num_rows($query))
				{
					return $db->$type($query);
				}
				else
				{
					return false;
				}
			}
			else
			{
				$failedTable = array(
					'tablename'=>$tableFrom,
					'query'=>$query,
					'value'=>implode(' ',$valueArray)
				);
				$this->dbErrorLog($failedTable);
				return false;
			}
		}
	}
?>