<?php
/************************************************************
Desciption: Backoffice ajax jqgrid lista de categorias
File: /bsk/categorias/registos/lista/index.php
Project: Basikus
Developers: João Vieira - 7lis.com
Start Date: 2009/11/24
************************************************************/

//configuração principal
require_once($_SERVER['DOCUMENT_ROOT'] . "/bsk/includes/configuracao.default.php");
//funções de tratamento de textos
include($_SERVER['DOCUMENT_ROOT'] . '/bsk/includes/funcoes.default.php'); 

$localTabela    = 'categorias';

// get the leaf nodes first 
$sqlStmt 	= "SELECT t1.id AS t1id FROM categorias AS t1 
				LEFT JOIN categorias as t2 ON t1.id = t2.pai 
				WHERE (t2.id IS NULL OR t2.id = '0')
"; 
$resultDb	= $connectDb->pedido($sqlStmt);
$leafnodes = array(); 
while( $rowResultDb = $resultDb->fetch(PDO::FETCH_ASSOC) ) { 
	$leafnodes[$rowResultDb['t1id']] = $rowResultDb['t1id']; 
}
#var_dump($leafnodes);
if (!isset($_REQUEST["nodeid"])) $_REQUEST["nodeid"] = "";
if (!isset($_REQUEST["n_level"])) $_REQUEST["n_level"] = ""; 

// get the needed parameters 
$node 	= (int)$_REQUEST["nodeid"]; 
$n_lvl 	= (int)$_REQUEST["n_level"]; 
$valp 	= 'NULL'; 

if ( stristr($_SERVER["HTTP_ACCEPT"],"application/xhtml+xml") ) { 
	header("Content-type: application/xhtml+xml;charset=utf-8"); 
} else { 
	header("Content-type: text/xml;charset=utf-8"); 
} 

$et = ">"; 

echo "<?xml version='1.0' encoding='utf-8'?" . $et . "\n"; 
echo "<rows>"; 
echo "<page>1</page>"; 
echo "<total>1</total>"; 
echo "<records>1</records>"; 

if($node >0) { 
	$wh		= 'pai=' . $node; 
	// we ouput the next level 
	$n_lvl 	= $n_lvl+1; 
} else { 
	$wh = "pai='0'"; 
	//$level = 0; 
} 

// This is the most easy way for this model - we use autoloading tree 
// no need for recursion 
$sqlStmt	= "SELECT id, nome, activo, pai FROM categorias WHERE " . $wh; 
#dbg($sqlStmt);
$resultDb   = $connectDb->pedido($sqlStmt);
while( $rowResultDb = $resultDb->fetch(PDO::FETCH_ASSOC) ) { 
	echo "<row>"; 
	echo "<cell>" . $rowResultDb['id'] . "</cell>"; 
	echo "<cell>" . trd($rowResultDb['nome'], $usrLng) . "</cell>"; 
	echo "<cell>" . $rowResultDb['activo'] . "</cell>"; 
	echo "<cell>editar</cell>"; 
	echo "<cell>remover</cell>"; 
	echo "<cell>" . $n_lvl . "</cell>"; 
	
	if( $rowResultDb['pai'] == 0 ) $valp = 'NULL'; 
	else $valp = $rowResultDb['pai']; 
		
	echo "<cell><![CDATA[" . $valp . "]]></cell>"; 
	
	$leaf='false';
	if ( isset($leafnodes[$rowResultDb['id']]) ) {
		if($rowResultDb['id'] == $leafnodes[$rowResultDb['id']]) $leaf='true'; 
		else $leaf = 'false'; 
	}
	
	echo "<cell>" . $leaf . "</cell>"; 
	echo "<cell>false</cell>"; 
	echo "</row>"; 
} 

echo "</rows>"; 


?>