<?php
// +------------------------------------------------------------------------+
// | PHP Melody version 1.6.7 ( www.phpsugar.com )
// +------------------------------------------------------------------------+
// | PHP Melody IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than www.phpsugar.com or if you have received
// | this software from someone who is not a representative of
// | phpSugar, you are involved in an illegal activity.
// | ---
// | In such case, please contact: support@phpsugar.com.
// +------------------------------------------------------------------------+
// | Developed by: phpSugar (www.phpsugar.com) / support@phpsugar.com
// | Copyright: (c) 2004-2011 PhpSugar.com. All rights reserved.
// +------------------------------------------------------------------------+
$showm = '3';
include('header.php');

$pattern = '/(^[a-z0-9_-]+)$/i';

// UPDATE CATEGORY
if(!empty($_POST['update']) && $_POST['update'] == 'Update') {
	$cid = $_POST['cid'];
 	$tag = secure_sql(trim($_POST['tag']));
	$name = secure_sql(trim($_POST['name']));
	$parent_id = (int) $_POST['parent_id'];
	$old_tag = $_POST['old_tag'];

	if(empty($tag) || empty($name)) 
		$info_msg = '<div class="info_msg_err">Please don\'t leave any empty fields.</div>';	
	else {
		if( ! @preg_match($pattern, $tag)) {
		$info_err_msg = '<div class="info_msg_err">Please make sure that the tags are typed properly (use only letters, numbers, "_" and "-").</div>';
		} else {
			
			if (strcmp($old_tag, $tag) != 0)
			{
				$sql = "SELECT COUNT(*) as total_found 
						FROM pm_categories 
						WHERE tag = '". $tag ."'";
				$result = @mysql_query($sql);
				$row = mysql_fetch_assoc($result);
				
				if ($row['total_found'] != 0)
				{
					$info_err_msg = '<div class="info_msg_err">The \'TAG\' attribute must be unique. A category using this tag was found in your database.</div>'; 
				}
				else
				{
					mysql_query("UPDATE pm_categories SET tag = '".$tag."', name = '".$name."' WHERE id = '".$cid."'");
					$info_msg = '<div class="info_msg_ok">Category <b>'.$name.'</b> has been updated.</div>';
					$_POST = array();
				}
			}
			else
			{
				mysql_query("UPDATE pm_categories SET name = '".$name."' WHERE id = '".$cid."'");
				$info_msg = '<div class="info_msg_ok">Category <b>'.$name.'</b> has been updated.</div>';
				$_POST = array();
			}
		}
	}
}

// ADD NEW CATEGORY
if(!empty($_POST['submit']) && $_POST['submit'] == 'Add category') {

	$parent_cid = $_POST['category']; // (parent_id)
	$cid = $_POST['cid'];
	$tag = secure_sql(trim($_POST['tag']));
	$name = secure_sql(trim($_POST['name']));
	
	if ($parent_cid < 0)
	{
		$parent_cid = 0;
	}
	
	if(empty($tag) || empty($name)) 
		$info_msg = '<div class="info_msg_err">Please don\'t leave any empty fields.</div>';	
	else {	
		$query = mysql_query("SELECT tag FROM pm_categories where tag = '".$tag."'");
		$result = mysql_num_rows($query);
		
		if($result == 0) {
		
			if( ! @preg_match($pattern, $tag)) {
			$info_err_msg = '<div class="info_msg_err">Please make sure that the tags are typed properly (use only letters, numbers, "_" and "-").</div>';
			} else {
				// get position of the last category
				$sql = "SELECT MAX(position) as max  
 						  FROM pm_categories 
						 WHERE parent_id = '". $parent_cid ."'";

				$result = mysql_query($sql);
				$row = mysql_fetch_assoc($result);
				mysql_free_result($result);
				
				$position = ($row['max'] > 0) ? ($row['max'] + 1) : 1;
				
				$sql = "INSERT INTO pm_categories (parent_id, tag, name, total_videos, position) 
							 VALUES ('". $parent_cid ."', '". $tag ."', '". $name ."', 0, ". $position .")";
				 
				if ( ! ($result = mysql_query($sql)))
				{
					$info_msg  = '<div class="info_msg_err">There was a problem while creating the new category.<br />';
					$info_msg .= '<strong>MySQL Reported:</strong>: '.mysql_error().'</div>';
				}
				else 
				{
					$info_msg = '<div class="info_msg_ok">Category <b>'.$name.'</b> has been added to the database.</div>';
					$_POST = array();
				}
			}
		
		} else {
				$info_msg = '<div class="info_msg_err">The \'TAG\' must be unique. A category using this tag was found in your database.</div>';

		}
	}	
}
// DELETE (SUB)CATEGORY
if( !empty($_GET['cid']) && $_GET['a'] == 1)
{
	$info_msg = '';
	$cid = (int) $_GET['cid'];
	
	$categories = a_list_cats_simple();
	
	$parents = $children = array();
	foreach ($categories as $id => $cat_arr)
	{
		if ($cat_arr['parent_id'] == 0)
		{
			$parents[] = $cat_arr;
		}
		else
		{
			$children[$cat_arr['parent_id']][] = $cat_arr;
		}
	}
	
	$delete_ids = array();
	get_all_children($cid, $children, $delete_ids);
	
	// remember these values for later
	$parent_id = $categories[$cid]['parent_id'];
	$current_position = $categories[$cid]['position'];
	
	if (count($delete_ids) > 0)
	{
		$video_uniq_ids = array();
		$delete_ids_str = '';
		
		$delete_ids_str = implode(",", $delete_ids);
		
		$sql = "DELETE 
				FROM pm_categories 
				WHERE id IN (". $delete_ids_str .")";
		$result = mysql_query($sql);
		if ( ! $result) 
		{
			$info_msg  = '<div class="info_msg_err">There was a problem while updating your database!<br />';
			$info_msg .= '<strong>MySQL Reported:</strong>: '.mysql_error().'</div>';
		}
		
		// update positions for other categories
		$update_pos_ids = array();
		foreach ($categories as $id => $cat_arr)
		{
			if (($cat_arr['parent_id'] == $parent_id) && ($cat_arr['position'] > $current_position))
			{
				$update_pos_ids[] = $id;
			}
		}
		
		if (count($update_pos_ids) > 0)
		{
			$update_pos_ids = implode(',', $update_pos_ids);
			$sql = "UPDATE pm_categories 
					   SET position = position - 1 
					 WHERE id IN (". $update_pos_ids .")";
			$result = mysql_query($sql);
		}
		
		//	delete all videos that belong exclusively to this (sub)category and everything related to them (e.g comments, ratings, tags)
		foreach ($delete_ids as $k => $id)
		{
			$delete_ids_str = '';
			foreach ($delete_ids as $k => $id)
			{
				$delete_ids_str .= "'". $id ."', ";
			}
			$delete_ids_str = substr($delete_ids_str, 0, -2);
			
			$videos = array();
			
			$sql = "SELECT uniq_id, url_flv, source_id  
					FROM pm_videos 
					WHERE category IN (". $delete_ids_str .")";
			
			$result = mysql_query($sql);
			while ($row = mysql_fetch_assoc($result))
			{
				$video_uniq_ids[] = $row['uniq_id'];
				
				if ($row['source_id'] == 1)
				{
					$videos[] = $row;
				}
			}
			
			mysql_free_result($result);
			
			$result = mass_delete_videos($video_uniq_ids);
			
			if (count($videos) > 0)
			{
				foreach ($videos as $k => $video)
				{
					if (file_exists(_VIDEOS_DIR_PATH . $video['url_flv']) && strlen($video['url_flv']) > 0)
					{
						unlink(_VIDEOS_DIR_PATH . $video['url_flv']);
					}
				}
			}
			
			foreach ($video_uniq_ids as $k => $uniq_id)
			{
				if (file_exists(_THUMBS_DIR_PATH . $uniq_id.'-1.jpg'))
				{
					unlink(_THUMBS_DIR_PATH . $uniq_id.'-1.jpg');
				}
			}
			
			sleep(1);
		}
		
		autosync(true);
		
		$info_msg = '<div class="info_msg_ok">Category <b>'.$categories[$cid]['name'].'</b> has been deleted.';
		if (count($delete_ids) > 1)
		{
			$info_msg .= '<br />';
			$info_msg .= 'All subcategories have also been deleted.'; 
		}
		$info_msg .= '<br />'.count($video_uniq_ids) .' videos were erased';
		$info_msg .= '</div>';
	}
	
	unset($_video_categories);
}

if ($_GET['move'] != '' && $_GET['id'] != '')
{
	$id = (int) $_GET['id'];
	
	if ($id > 0)
	{
		$cat = a_list_cats_simple();
		
		$limit = 0;
		$is_parent = false;
		$is_child = false;

		if ($cat[$id]['parent_id'] == 0)
		{
			foreach ($cat as $c_id => $c_arr)
			{
				if ($c_arr['parent_id'] == 0)
				{
					$is_parent = true;
					$limit++;
				}
			}
		}
		else
		{
			foreach ($cat as $c_id => $c_arr)
			{
				if ($c_arr['parent_id'] == $cat[$id]['parent_id'])
				{
					$is_child = true;
					$limit++;
				}
			}
		}
		
		$current_position = $cat[$id]['position'];
		$prev_cat_id = $next_cat_id = 0;
		
		// find neighbours 
		foreach ($cat as $c_id => $c_arr)
		{
			if ($c_arr['position'] == ($current_position - 1) && $c_arr['parent_id'] == $cat[$id]['parent_id'])
			{
				$prev_cat_id = $c_id;
			}
			
			if ($c_arr['position'] == ($current_position + 1) && $c_arr['parent_id'] == $cat[$id]['parent_id'])
			{
				$next_cat_id = $c_id;
			}
		}
		
		switch ($_GET['move'])
		{
			case 'up':
				
				if ($current_position > 1 && $current_position <= $limit && $prev_cat_id)
				{
					$sql_1 = "UPDATE pm_categories
							   SET position = '". ($cat[$prev_cat_id]['position'] + 1) ."' 
							 WHERE id = '". $prev_cat_id ."'";
					$sql_2 = "UPDATE pm_categories
							   SET position = '". ($cat[$id]['position'] - 1) ."' 
							 WHERE id = '". $id ."'";
				}
				
			break;
	
			case 'down':
				
				if ($current_position >= 1 && $current_position < $limit && $next_cat_id)
				{
					$sql_1 = "UPDATE pm_categories
							   SET position = '". ($cat[$id]['position'] + 1) ."' 
							 WHERE id = '". $id ."'";
					
					$sql_2 = "UPDATE pm_categories
							   SET position = '". ($cat[$next_cat_id]['position'] - 1) ."' 
							 WHERE id = '". $next_cat_id ."'";
				}
				
			break;
		}
		
		if ($sql_1 != '' && $sql_2 != '')
		{
			if ( ! ($result = mysql_query($sql_1)))
			{
				$info_msg  = '<div class="info_msg_err">There was a problem while updating your database!<br />';
				$info_msg .= '<strong>MySQL Reported:</strong>: '.mysql_error().'</div>';
			}
			else
			{
				if ( ! ($result = mysql_query($sql_2)))
				{
					$info_msg  = '<div class="info_msg_err">There was a problem while updating your database!<br />';
					$info_msg .= '<strong>MySQL Reported:</strong>: '.mysql_error().'</div>';
				}
			}
			
			unset($_video_categories);
		}
	}
	
	if ($info_msg == '')
	{
		echo '<meta http-equiv="refresh" content="0;URL=cat_manager.php" />';
		exit();
	}
}

$total_categories = count_entries('pm_categories', '', '');

$categories_dropdown_options = array('first_option_text' => '- Root -', 
									 'selected' => $_POST['category']
									);
?>
<div id="sub_menu">

</div>
<div id="content">
<h2>Video categories</h2>
<?php echo $info_err_msg;?>
<?php echo $info_msg;?>
<table width="100%" border="0" cellspacing="1" cellpadding="3">
  <tr>
    <td valign="top">
		<form name="search" action="cat_manager.php" method="post">
		<input name="name" type="text" onclick='value=""' value="<?php echo ($_POST['name'] != '') ? $_POST['name'] : 'Category Name';?>" size="22" />
		<input name="tag" type="text" onclick='value=""' value="<?php echo ($_POST['tag'] != '') ? $_POST['tag'] : 'tag';?>" size="10" /> 
		Create in:
		<?php echo categories_dropdown($categories_dropdown_options); ?>
		
		<input name="submit" type="submit" value="Add category" class="inputbutton" />
		</form>
		<small>* tags are required and are used in URLs. Tags can only contain numbers, letters, dashes '-' and underscores '_'.</small>
	</td>
    <td width="220" valign="top"><div class="totals">Total categories: <?php echo $total_categories; ?></div></td>
  </tr>
</table>
<table width="100%" class="tablesorter" cellspacing="1">
 <thead>
  <tr>
  	<th width="5%">ID</th>
	<th width="25%">Category Name</th>
    <th width="30%">Tag</th>
    <th width="25%">Parent Category</th>
	<th width="5%">Videos</th>
	<th width="5%">Position</th>
    <th width="10%" align="center">Action</th>
  </tr>
 </thead>
 <tbody>
	<?php
	echo a_list_cats();
	?>
 </tbody>
</table>
</div>
<?php
include('footer.php');
?>