<?php
/*
 * Category management
 */

// TODO: Admin authentication

require('init.php');
require(
'db.php');

if (!
$_SESSION['user_id']) {
    die(
"You must be <a href='login.php'>logged in</a> first.");
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Category Management</title>
</head>
<body>
<?php

// row ordering should not be required any more.
// would be equiv to: SELECT * FROM category ORDER BY cat_parent NULLS FIRST
$sql "SELECT * FROM `category` ORDER BY `cat_parent` IS NOT NULL, `cat_parent` ASC";
$result mysql_query($sql,$db);
echo 
"Categories in database: " mysql_num_rows($result) . "<br />";

$ids = array();
$children = array();
while (
$row mysql_fetch_array($result)) {
    echo 
$row['cat_id'] . ": ".$row['cat_name'] . "(".$row['cat_parent'].")<br />";

    
// populate ids array
    
$ids[$row['cat_id']] = array('id' => $row['cat_id'], 'name' => $row['cat_name'],'parent' => $row['cat_parent']);

    
// populate children array
    
if ($row['cat_parent'] == null) {
        
$children[0][] = $row['cat_id'];
    } else {
        
$children[$row['cat_parent']][] = $row['cat_id'];
    }
}
echo 
"<pre>";
var_dump($children);
var_dump($ids);
echo 
"</pre>";

displayChildren($children00);

// recursive child display
function displayChildren($children$id$level) {
    global 
$ids;
    if (
is_array($children[$id])) {
        foreach (
$children[$id] as $item) {
            echo 
"<div style='margin-left: 2em;'>$item - ".$ids[$item]['name'];
            
displayChildren($children,$item,$level+1);
            echo 
"</div>";
        }
    }
}

?>
</body>
</html>