<?
@session_start();
$base_path='../';
require_once('../connect/connect.php');
include_once('../lib/lib.php');
require('pdk.php');


if($_GET['cashe'])
include_once('_menu_cashe.php');


$level_max_catalog=4;

$Action=$_SERVER['PHP_SELF'];
$id_catalog=intval($_REQUEST['id_catalog']);
$parent_id=intval($_REQUEST['parent_id']);

function _glob ($a) 
{
global $vverh;
global $Action;
global $b;
global $c;
global $i;
global $m;

	$r = mysql_query("SELECT * FROM catalog WHERE id_catalog = '".$a."'");
	$nr=mysql_num_rows($r);
	if($nr)
		{
		$rr = mysql_fetch_array($r);
		$i++;
		if($i==1)
			{
			$b = $rr['catalog'].' '.$b;
			$m = $rr['catalog'];
			}
		if ($i>1)
		$b = '<a href="?parent_id='.$rr['id_catalog'].'">'.$rr['catalog'].' >></a> '.$b;
		if($rr['parent_id']==0)
			{
			$c = $rr['id_catalog'];
			$b = '<a href="'.$Action.'">Все каталоги >></a> '.$b;
			}
		$vverh = $rr['id_catalog'].' '.$vverh;
		_glob($rr['parent_id']);
		}
$d[0]=$c; // id региона
$d[1]=$b; // ссылка на ВСЕ КАТАЛОГИ
$d[2]=$i; // кол-во уровней
$d[3]=$vverh; // path
$d[4]=$m; // path

return $d;
} 

$mm = 'все каталоги';

if($parent_id)
{
$vverh='';
$i=0;
$b='';
$c=0;
$m='';
$navs = _glob($parent_id);
$mm=$navs[4];
}

$parent_glob=intval($navs[0]);
$level=intval($navs[2])+1;
$path='0 '.$navs[3];
$path=trim($path);

if($parent_id)
	{
	$r = mysql_query ("SELECT * FROM catalog WHERE id_catalog = '".$parent_id."'") or die(mysql_error());
	$rr=mysql_fetch_array($r);
	$view_parent=$rr['parent_id'];
	}


if ($_GET['id_catalog'] && isset($_GET['parent_id']) && $_GET['per'])
	{
	if ($_GET['per']==1) $per=1; else $per=-1;
	sort_num('catalog', 'id_catalog', 'num', 'id_catalog', intval($_GET['id_catalog']), $per, " WHERE parent_id='".intval($_GET['parent_id'])."'");
	include_once('_svod_catalog.php');
	if($level<3)
	f_cashe_menu();
	}


if ($_POST["del"] && $_POST["del_element"]) 
	{ 
	function _array_del_element($del_element) 
		{
		global $del_cat;
		$r = mysql_query("SELECT * FROM catalog WHERE parent_id IN (".$del_element.")");
		while ($rr = mysql_fetch_array($r)) 
			{
			$del_cat[]=$rr['id_catalog'];
			_array_del_element($rr['id_catalog']);
			}
		return $del_cat;
		} 
		
	$arrf = _array_del_element($_POST["del_element"]);
	
	$tmp_del = explode(",",$_POST["del_element"]);
	foreach($tmp_del as $tmp_de)
		{
		$arrf[]=$tmp_de;
		}
		
	foreach($arrf as $af)
		{
		if(file_exists($base_path."cashe_catalog/_svod_catalog_".$af.".php"))
		unlink($base_path."cashe_catalog/_svod_catalog_".$af.".php");
		}

	$in=implode(",",$arrf);
	
	mysql_query ("DELETE FROM catalog WHERE id_catalog IN (".$in.") ") or die(mysql_error());
	mysql_query ("DELETE FROM field WHERE id_catalog IN (".$in.") ") or die(mysql_error());
	
	include_once('_svod_catalog_short.php');
	f_cashe_menu();

	echo "<HTML><HEAD><meta http-equiv='Refresh' charset='utf-8' content='0; URL=cat.php?parent_id=".$parent_id."'></HEAD></HTML>";
	exit();
	}
	
if ($_POST["add"]) 
	{ 
	$catalog = trim($_POST['catalog']);
	if(!$catalog) $err .='Укажите каталог<br>';
	$arr_catalogs=explode("\n", $catalog);
	
	if(!$err)
		{
		foreach($arr_catalogs as $arr_ln)
			{
			if(trim($arr_ln))
				{
				mysql_query("INSERT INTO catalog (
				parent_id, 
				parent_glob, 
				catalog, 
				path,
				url
				) 
				VALUES (
				'".$parent_id."', 
				'".$parent_glob."', 
				'"._pre(trim($arr_ln))."', 
				'".$path."',
				'".cpu(trim($arr_ln), $rru['url_type'])."'
				)");
				$insert_id=mysql_insert_id();
				ob_start();
				echo "<?\n";
				$result = mysql_query("SELECT * FROM catalog WHERE id_catalog = '".$insert_id."'");
				while($r_result=mysql_fetch_array($result)) 
					{
					echo '$arr_catalog[\'id_catalog\']='.$r_result['id_catalog'].';';
					echo "\n";
					echo '$arr_catalog[\'parent_id\']='.$r_result['parent_id'].';';
					echo "\n";
					echo '$arr_catalog[\'catalog\']=\''.$r_result['catalog'].'\';';
					echo "\n";
					echo '$arr_catalog[\'path\']=\''.$r_result['path'].'\';';
					echo "\n";
					echo '$arr_catalog[\'url\']=\''.$r_result['url'].'\';';
					echo "\n";
					echo '$tree_cat=array('.str_replace(" ", ",", trim($r_result['path'])).",".$r_result['id_catalog'].');';
					echo "\n";
					} 
				echo "?>";
				$buf = ob_get_contents();
				ob_end_clean();

				$file1 = fopen ("../cashe_catalog/_svod_catalog_".$insert_id.".php", "w");
				flock($file1, LOCK_EX);
				fputs($file1, $buf);
				fclose($file1);
				}
			}
		include_once('_svod_catalog_short.php');
		f_cashe_menu();
		echo "<HTML><HEAD><meta http-equiv='Refresh' charset='utf-8' content='0; URL=cat.php?parent_id=".$parent_id."'></HEAD></HTML>";
		exit();
		}
	}


$titl="Каталог: ".$mm;
require ('top.php'); 

echo '<table width=100%><tr><td valign=top width=40%>';

if($err) echo '<p><font color=red>'.$err.'</font></p>';

if($_POST['paket_del'] && $_POST['ch'])
	{
	$del_element = implode(",",$_POST['ch']);
	echo '<table width=300 bordercolor=red border=3 cellSpacing=0 cellPadding=5><tr><td>
	<p>Вы действительно хотите удалить каталоги под номерами <b>'.$del_element.'</b> ?</p>';
	?>
	<form action="<? echo $Action; ?>" method="post" name="form_del" >
 	<input name="del_element" type="hidden" value="<? echo $del_element; ?>">
  	<input name="parent_id" type="hidden" value="<? echo $parent_id; ?>">
 	<input class="submit" type="submit" name="del" value="ДА">
 	<input class="submit" type="submit" name="not" value="НЕТ">
	</form>
	<?
	echo '</td></tr></table>';
	}


if (!$_POST['ch']) 
	{
	?>
	<form name="form_add" method="POST" action="<? echo $Action; ?>">
	<table width="100%" cellspacing="0" cellpadding="0" >
		<tr>
			<td width="29%" >
			<textarea name="catalog" cols="40" rows="8"></textarea>
  			<input name="parent_id" type="hidden" value="<? echo $parent_id; ?>">
			<br>
			<input class="submit" type="submit" name="add" value="Добавить">
			<p><font color=green>Примечание:<br>Вы можете добавлять целым списком. Единственное условие - каждый элемент списка должет начинаться с новой строки</font></p>
	</table>
	</form>
	<? 
	} 


echo '<td valign=top>';


$r = mysql_query ("SELECT * FROM catalog WHERE id_catalog > 0 AND parent_id='".$parent_id."' ORDER BY num, id_catalog") or die(mysql_error());
$nr = mysql_num_rows ($r);

if($navs)
{
echo $navs[1].'<br><br>';
}

		
if ($nr <1) echo "<p><b>Список пуст</b></p>";

if ($nr >0)
{
echo '<form action="" method=post >';
echo '<TABLE width="100%" cellpadding="1" cellspacing="1">';
$i=0;
	while ($rr = mysql_fetch_assoc($r)) 
	{ 
	$i++;
	echo '<tr align=left>';
	echo '<td  width="30">';
	echo '<input type="checkbox" name=ch[] value="'.$rr['id_catalog'].'" ';
	if($_POST['ch'] && in_array($rr['id_catalog'],$_POST['ch'])) echo 'checked';
	echo ' >';
	
	echo '<td  width="30">';
	echo '<a title="Редактировать каталог" href = "catalog.php?id_catalog='.$rr['id_catalog'].'"><img hspace="2" src="../icon/edit.png" border="0" ></a>';
	
	echo '<td  width="30">';
	if($i>1)
	echo ' <a title="Переместить на одну позицию вверх" href = "?id_catalog='.$rr['id_catalog'].'&parent_id='.$rr['parent_id'].'&per=1"><img border=0 src="../icon/up.gif"></a>';
		
	echo '<td  width="30">';
	if($i<$nr)
	echo ' <a title="Переместить на одну позицию вниз" href = "?id_catalog='.$rr['id_catalog'].'&parent_id='.$rr['parent_id'].'&per=2"><img border=0 src="../icon/down.gif"></a>';
	
	echo '<td >';
	if($level<$level_max_catalog && !$rr['count_field'])
	echo '<a href = "'.$Action.'?parent_id='.$rr['id_catalog'].'">'.$rr['catalog'].'</a>'; 
	else
		{
		if($rr['count_field'])
		echo '<font color=green>'.$rr['catalog'].'</font>';
		else
		echo $rr['catalog']; 
		}
	}  
echo '</TABLE>';
echo '<br><input name="parent_id" type="hidden" value="'.$parent_id.'">
<input type="submit" class="submit" name="paket_del" value="Отмеченные удалить">';
echo '</form>';
}

echo '</TABLE>';
require ('bottom.php'); 
?>