<?
include_once "db/dbElemento.class.php";

class dbCategoria extends dbElemento{
	
	function getNumeroFilhos($table, $idPai){
		$sql="select count(id) as TEMP from $table where idPai=$idPai";

	   	$arrTemp=$this->get($sql);
		$contagem=$arrTemp[0]['TEMP'];

	   	return $contagem;
	}

	function setOrder($table, $idPai, $id){
		
		
		$sql="select max(id) as TEMP from $table where idPai=$idPai"; //corrigir
	   	$arrTemp=$this->get($sql);
	   	$tempOrdem=$arrTemp[0]['TEMP'];
		$tempOrdem++;
		
	   	//$tempOrdem=$this->getNumeroFilhos($table, $idPai);	
		$sql="update $table set ordem=$tempOrdem where id=$id";
		
        $this->set($sql);
        return $tempOrder;
	}
	
	function setAbaixo($table, $idPai,  $id){
		
		$sql="select ordem from $table where id=$id ";
	   	$arrTemp=$this->get($sql);
	   	$outroOrdem=$arrTemp[0]['ordem'];
	   	
	   	$sql="select min(ordem) as TEMP from $table 
		   where idPai=$idPai and ordem> $outroOrdem";
		
		$arrTemp=$this->get($sql);
	   	$ordem=$arrTemp[0]['TEMP'];
	   	
	   	$sql="select id from $table 
		   where idPai=$idPai and ordem= $ordem";
	   	$arrTemp=$this->get($sql);
	    $outroId=$arrTemp[0]['id'];

		$sql="update $table set ordem=$outroOrdem where id=$outroId";
        $this->set($sql);
        
        $sql="update $table set ordem=$ordem where id=$id";
        $this->set($sql);
        
        return $tempOrder;
	}
	
	function setAcima($table, $idPai,  $id){

		$sql="select ordem from $table where id=$id ";
	   	$arrTemp=$this->get($sql);
	   	$outroOrdem=$arrTemp[0]['ordem'];
	   	
	   	$sql="select max(ordem) as TEMP from $table 
		   where idPai=$idPai and ordem< $outroOrdem";
		   
		$arrTemp=$this->get($sql);
	   	$ordem=$arrTemp[0]['TEMP'];
	   	
	   	$sql="select id from $table 
		   where idPai=$idPai and ordem= $ordem";
	   	$arrTemp=$this->get($sql);
	    $outroId=$arrTemp[0]['id'];

		$sql="update $table set ordem=$outroOrdem where id=$outroId";
        $this->set($sql);

        $sql="update $table set ordem=$ordem where id=$id";
        $this->set($sql);
        
        return $tempOrder;
	}
	
	
	function setInsert($table, $idCat, $data){
	  
		$strip=get_magic_quotes_gpc();
	  
		$camposBD=$this->getCampos($table) ;
		if (empty($data['id'])) array_shift($camposBD);

		$sep="";
        foreach ($camposBD as $c){
			if ($strip) stripslashes($data[$c]);
			$data[$c]=mysql_real_escape_string($data[$c]);			
			$cam.="$sep $c ";
			$val.="$sep '".$data[$c]."'";			
			if ($sep=="") $sep=",";
          }
            
        $sql="insert into $table (".$cam.") values (".$val.") ";

        $this->set($sql);
        $id= $this->getId();
        $this->setOrder($table, $data['idPai'], $id);
        
		return $id;
	}
		
}
?>
