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

$level_max_region=4;

$Action=$_SERVER['PHP_SELF'];
$id_region=intval($_REQUEST['id_region']);
$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 region WHERE id_region = '".$a."'");
	$nr=mysql_num_rows($r);
	if($nr)
		{
		$rr = mysql_fetch_array($r);
		$i++;
		if($i==1)
			{
			$b = $rr['region'].' '.$b;
			$m = $rr['region'];
			}
		if ($i>1)
		$b = '<a href="?parent_id='.$rr['id_region'].'">'.$rr['region'].' >></a> '.$b;
		if($rr['parent_id']==0)
			{
			$c = $rr['id_region'];
			$b = '<a href="'.$Action.'">Все регионы >></a> '.$b;
			}
		$vverh = $rr['id_region'].' '.$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='';
$nav = _glob($parent_id);
$mm=$nav[4];
}

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

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

if ($_GET['id_region'] && isset($_GET['parent_id']) && $_GET['per'])
	{
	if ($_GET['per']==1) $per=1; else $per=-1;
	sort_num('region', 'id_region', 'num', 'region', intval($_GET['id_region']), $per, " WHERE parent_id='".intval($_GET['parent_id'])."'");
	include_once('_svod_region.php');
	}


if ($_POST["del"] && $_POST["del_element"]) 
	{ 
	function _array_del_element($del_element) 
		{
		global $del_cat;
		$r = mysql_query("SELECT * FROM region WHERE parent_id IN (".$del_element.")");
		while ($rr = mysql_fetch_array($r)) 
			{
			$del_cat[]=$rr['id_region'];
			_array_del_element($rr['id_region']);
			}
		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;
		if(file_exists($base_path."cashe_region/_svod_region_".$tmp_de.".php"))
		unlink ($base_path."cashe_region/_svod_region_".$tmp_de.".php");
		}
		
	$in=implode(",",$arrf);

	mysql_query ("DELETE FROM region WHERE id_region IN (".$in.") ") or die(mysql_error());
	
	include_once('_svod_region.php');
	echo "<HTML><HEAD><meta http-equiv='Refresh' charset='utf-8' content='0; URL=reg.php?parent_id=".$parent_id."'></HEAD></HTML>";
	exit();
	}

if ($_POST["edit"] && $id_region) 
	{ 
	$region = _pre($_POST['region']);
	$url = cpu(trim($region), $rru['url_type']);
	if(!$region) $err .='Укажите регион';
	if($_POST['rayon']) $rayon=1; else $rayon=0;
	
	if(!$err)
		{
		if($rru['url_fixed'])
		$q="UPDATE region SET region='".$region."', rayon='".$rayon."' WHERE id_region='".$id_region."'";
		else
		$q="UPDATE region SET region='".$region."', rayon='".$rayon."', url='".$url."' WHERE id_region='".$id_region."'";
		mysql_query($q);
		
		if(isset($_REQUEST['edit'])) unset($_REQUEST['edit']);
		if(isset($rayon)) unset($rayon);
		include_once('_svod_region.php');
		echo "<HTML><HEAD><meta http-equiv='Refresh' charset='utf-8' content='0; URL=reg.php?parent_id=".$parent_id."'></HEAD></HTML>";
		exit();
		}
	}

if ($_POST["add"]) 
	{ 
	$region = trim($_POST['region']);
	if(!$region) $err .='Укажите регион<br>';
	$arr_regions=explode("\n", $region);
	if($_POST['rayon']) $rayon=1; else $rayon=0;
	
	if(!$err)
		{
		foreach($arr_regions as $arr_ln)
			{
			if(trim($arr_ln))
				{
				mysql_query("INSERT INTO region (
				parent_id, 
				parent_glob, 
				region, 
				path, 
				rayon,
				url
				) VALUES (
				'".$parent_id."', 
				'".$parent_glob."', 
				'"._pre(trim($arr_ln))."', 
				'".$path."', 
				'".$rayon."',
				'".cpu(trim($arr_ln), $rru['url_type'])."'
				)");
				}
			}
		include_once('_svod_region.php');
		echo "<HTML><HEAD><meta http-equiv='Refresh' charset='utf-8' content='0; URL=reg.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 ($_REQUEST['edit'] && $id_region)
	{
	$rm1 = mysql_query ("SELECT id_region FROM region WHERE parent_id='".$id_region."'");
	$rrm1=mysql_num_rows($rm1);
	
	$rm = mysql_query ("SELECT * FROM region WHERE id_region='".$id_region."'");
	$rrm=mysql_fetch_array($rm);
	
	?>
	<form action="<? echo $Action; ?>" method="post" name="form_edit" >
		<table width="100%" cellspacing="0" cellpadding="0" >
			<tr>
				<td width="29%" >
  				<input name="id_region" type="hidden" value="<? echo $id_region; ?>">
  				<input name="parent_id" type="hidden" value="<? echo $parent_id; ?>">
  				<input name="region" type="text" value="<? echo $rrm['region']; ?>" size="40">
				<?
				if(!$rrm1)
				{
				?>
				<br>
				<input type="checkbox" name="rayon" value="1" <? if($rrm['rayon']) echo 'checked'; ?> > Район города
				<?
				}
				?>
				<br>
  				<input class="submit"  type="submit" name="edit" value="Изменить">
		</table>
	</form>
	<?
	}


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 (!$_REQUEST['edit'] && !$_POST['ch']) 
	{
	?>
	<form name="form_add" method="POST" action="<? echo $Action; ?>">
	<table width="100%" cellspacing="0" cellpadding="0" >
		<tr>
			<td width="29%" >
			<textarea name="region" cols="40" rows="8"></textarea>
  			<input name="parent_id" type="hidden" value="<? echo $parent_id; ?>">
			<br>
			<input type="checkbox" name="rayon" value="1" <? if($rayon) echo 'checked'; ?> > Район города
			<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 region WHERE parent_id='".$parent_id."' ORDER BY num, region ASC") or die(mysql_error());
$nr = mysql_num_rows ($r);

if($nav)
{
echo $nav[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>';
	echo '<td  width="30">';
	echo '<input type="checkbox" name=ch[] value="'.$rr['id_region'].'" ';
	if($_POST['ch'] && in_array($rr['id_region'],$_POST['ch'])) echo 'checked';
	echo ' >';
	
	echo '<td  width="30">';
	echo '<a title="Редактировать регион" href = "'.$Action.'?parent_id='.$rr['parent_id'].'&id_region='.$rr['id_region'].'&edit=1"><img hspace="2" src="../icon/edit.png" border="0" ></a>';
	
	echo '<td  width="30">';
	if($i>1)
	echo ' <a title="Переместить на одну позицию вверх" href = "?id_region='.$rr['id_region'].'&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_region='.$rr['id_region'].'&parent_id='.$rr['parent_id'].'&per=2"><img border=0 src="../icon/down.gif"></a>';
	
	
	echo '<td>';
	if($rr['rayon']) $ry=' <font color=red>(P)</font>'; else $ry='';
	
	if($level<$level_max_region && !$rr['rayon'] )
	echo '<a href = "'.$Action.'?parent_id='.$rr['id_region'].'">'.$rr['region'].'</a>'; 
	else
	echo $rr['region']; 
	
	echo $ry;
	}  
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'); 
?>