<?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 = '9';
include('header.php');

function manage_ad_form($action = 'addnew', $id = 0, $position = '', $code = '', $active = 0)
{
	$target = '';
	switch($action)
	{
		case 'addnew':
			$target = 'ad_manager.php?act=addnew';
		break;
		case 'edit':
			$target = ($id != 0) ? 'ad_manager.php?act=edit&id='.$id : 'ad_manager.php?act=edit';
		break;
	}
	// generate form
	$form	=	'<form name="ad_manager" method="post" action="'.$target.'">';
	$form  .= '
	<table width="100%" border="0" cellpadding="4">
	  <tr class="table_row1">
		<td class="fieldtitle" width="10%">Name:</td>
		<td><input type="text" name="position" value="'.$position.'" size="40" /></td>
	  </tr>
	  <tr class="table_row1">
		<td class="fieldtitle" valign="top">HTML Code:</td>
		<td><textarea name="code" cols="60" rows="7">'.$code.'</textarea></td>
	  </tr>
	  <tr class="table_row1">
		<td class="fieldtitle">Status</td>
		<td><label><input name="active" type="radio" value="0" />Inactive</label> <label><input name="active" type="radio" value="1" checked="checked"/> Active</label></td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
		<td><input type="submit" name="Submit" value="Submit" class="inputbutton" /></td>
	  </tr>
	</table>
	';	
	return $form;
}

$action = $_GET['act'];
if( $action == '' || empty($action))
	$action = '';

?>

<div id="sub_menu">
<li><a href="ad_manager.php">Ads Manager</a></li>
<li><a href="videoads.php">Video Ads Manager</a></li>
</div>
<div id="content">
<h2>Ad Manager</h2>
<br />
<?php if($action != 'addnew' && $action != 'edit') { ?>
<a href="ad_manager.php?act=addnew" class="b_edit">Create new ad</a>
<?php } ?>
<?php echo $info_msg; ?>
<?php


switch($action)
{
	case 'addnew':
		if($_GET['act'] == 'addnew')
		{
			if(isset($_POST['Submit']))
			{
				$arr_fields = array('position' => "Name", 'code' => "Code", 'active' => 'Status');
				$errors = '';
				foreach($_POST as $k => $v)
				{
					if(trim($v) == '' && array_key_exists($k, $arr_fields) === TRUE)
							$errors .= "<li>The '".$arr_fields[$k]."' field shouldn't be empty</li>";	
					//$_POST[$k] = str_replace('"', "", $v);
				}
				if($errors != '')
				{
					echo "<div class=\"info_msg_err\"><ul>".$errors."</ul></div><br />";
					echo manage_ad_form('addnew', 0, $_POST['position'], $_POST['code'], $_POST['active']);
				}
				else
				{
					$position = secure_sql($_POST['position']);
					$code = secure_sql($_POST['code']);
					$active = ($_POST['active'] == 1) ? 1 : 0;
					
					$query = mysql_query("INSERT INTO pm_ads SET position = '".$position."', code = '".$code."', active = '".$active."'");
					if(!$query)
						echo "<div class=\"info_msg_err\">There was a problem while inserting new ad in database<br />
							  <strong>MySQL returned:</strong> ".mysql_error()."</div>";
					else
					{
						$new_ad_id = mysql_insert_id();
						$msg = '<div class="info_msg">Done!<br /><br />
						<p>
						Your ad zone has been created. Now you have to edit the PHP Melody template to display this ad zone.
						</p>
						<ol>
						<li>Pick the page you wish to display your ad on (e.g. header.tpl, index.tpl, footer.tpl)</li>
						<li>Paste the following code wherever you wish to display your ad: <strong>{$ad_'.$new_ad_id.'}</strong></li>
						</ol>';
						if($_POST['active'] == 0)
							$msg .= "<br /><small>P.S. Don't forget to activate it.</small>";
						//$msg .= '<br /><a href="ad_manager.php">&laquo; Return to Ad Manager page</a>';
						$msg .= '</div>';
						$msg .= '<input name="continue" type="button" value="&laquo; Return to Ad Manager page" onClick="location.href=\'ad_manager.php\'" class="inputbutton" />';
						
						echo $msg;
					}
				}
			}
			else
			{
				echo manage_ad_form('addnew');
			}
		}	
	break;
	
	case 'edit':
		$id = $_GET['id'];
		if($id <= 0 || !is_numeric($id) || $id == '')
			echo "<div class=\"info_msg_err\">ID is not a valid value or missing</div>";
		
		else
		{
			if(isset($_POST['Submit']))
			{
				$arr_fields = array('position' => "Name");
				$errors = '';
				foreach($_POST as $k => $v)
				{
					if(trim($v) == '' && array_key_exists($k, $arr_fields) === TRUE)
							$errors .= "<div class=\"info_msg_err\">The '".$arr_fields[$k]."' field shouldn't be empty</div>";	
					//$_POST[$k] = str_replace('"', "", $v);
				}				
				if($errors != '')
				{
					echo $errors."<br />";
					echo manage_ad_form('edit', $id, $_POST['position'], $_POST['code'], $_POST['active']);
					echo "</div>";
					include('footer.php');
					exit();
				}
				$position = secure_sql($_POST['position']);
				$code = secure_sql($_POST['code']);
				$active = ($_POST['active'] == 1) ? 1 : 0;
				
				$query = mysql_query("UPDATE pm_ads SET position = '".$position."',
														code = '".$code."',
														active = '".$active."'
													WHERE id='".$id."'");
				if ( ! $query)
				{
					echo "<div class=\"info_msg_err\">There was a problem while inserting new ad in database<br />
						  <strong>MySQL returned:</strong> ".mysql_error()."</div>";
				}
				else
				{
					echo "<div class=\"info_msg\">Your ad was updated!</a></div>";
					echo '<input name="continue" type="button" value="&laquo; Return to Ad Manager page" onClick="location.href=\'ad_manager.php\'" class="inputbutton" />';
				}
					
			}
			else
			{
				$query = mysql_query("SELECT * FROM pm_ads WHERE id='".$id."'");
				if(!$query)
				{
					echo "<div class=\"info_msg_err\">There was a problem while getting data from your database<br />
							  <strong>MySQL returned:</strong> ".mysql_error()."</div>";
					echo "</div>";
					include('footer.php');
					exit();
				}
				
				$ad = mysql_fetch_assoc($query);
				if($ad['id'] == '')
					echo "<div class=\"info_msg_err\">Cannot find this ad in your database.</div>";
				else
					echo manage_ad_form('edit', $ad['id'], $ad['position'], $ad['code'], $ad['active']);
			}
		}
	
	break;
	
	case 'delete':
	case 'activate':
	case 'deactivate':
	case '':
	default:
	
		$total_ads = count_entries('pm_ads', '', '');

		if($action == 'delete')
		{
			$id = $_GET['id'];
			if($id <= 0 || !is_numeric($id) || $id == '')
				echo "<div class=\"info_msg_err\">ID is not a valid value or missing</div>";
			elseif(in_array($id, array(1, 2, 3)) !== FALSE)
			{
				echo "<div class=\"info_msg_err\">You can't delete the default ad spots.</div>";
			}
			else
			{
				$query = mysql_query("DELETE FROM pm_ads WHERE id = '".$id."'");
				if( !$query )
					echo "<div class=\"info_msg_err\">There was a problem while deleting your ad<br /><strong>MySQL returned:</strong> ".mysql_error()."</div>";
				else
					echo "<div class=\"info_msg\">Deleted</div>";
			}
		}
		if($action == 'activate' || $action == 'deactivate')
		{
			$id = $_GET['id'];
			if($id <= 0 || !is_numeric($id) || $id == '')
				echo "<div class=\"info_msg_err\">ID is not a valid value or missing</div>";
			else
			{	
				$sql = '';
				if($action == "activate")
					$sql = "UPDATE pm_ads SET active='1' WHERE id = '".$id."' LIMIT 1";
				else
					$sql = "UPDATE pm_ads SET active='0' WHERE id = '".$id."' LIMIT 1";
				
				$query = mysql_query($sql);
				if( !$query )
					echo "<div class=\"info_msg_err\">There was a problem while activating/deactivating your ad<br /><strong>MySQL returned:</strong> ".mysql_error()."</div>";
				else
				{
					if($action == "activate")
						echo "<div class=\"info_msg\">The ad is now active.</div>";
					else
						echo "<div class=\"info_msg\">The ad was deactivated.</div>";
				}
			}
		}
	?>
<table width="100%" border="0">
  <tr>
    <td>&nbsp;</td>
    <td width="220"><div class="totals" align="right">Total ads: <?php echo $total_ads; ?></div></td>
  </tr>
</table>
<table width="100%" class="tablesorter">
 <thead> 
  <tr>
    <th>Name</th>
	<th align="center" width="10%">TPL Code</th>
    <th align="center" width="15%">Status</th>
	<th align="center" width="15%">Action</th>
  </tr>	
 </thead>
 <tbody>
  <?php
	
	// display all ads
	$query = mysql_query("SELECT * FROM pm_ads ORDER BY id DESC");
	$display = '';
	$i = 0;
	while($row = mysql_fetch_assoc($query))
	{	
		$clean_title = str_replace(array('"', "'"), array('', "\'"), $row['position']);
		$col = ($i++ % 2) ? 'table_row1' : 'table_row2';
		$display = '';
		$display .= '<tr class="'.$col.'">';
		$display .= '<td>'.$row['position'].'</td>';
		$display .= '<td align="center">{$ad_'.$row['id'].'}</td>';
		$display .= '<td align="center"><small>';
		$display .= ($row['active'] == 1) ? "Active" : "Inactive";
		$display .= '</small></td>';
		$display .= '<td align="center">';		
			$display .= '<a href="ad_manager.php?act=edit&id='.$row['id'].'" class="b_edit">Edit</a> | <a href="#" onClick="delete_ad(\''. $clean_title .'\', \'ad_manager.php?act=delete&id='.$row['id'].'\')" class="b_delete">Delete</a>';
			$display .= ($row['active'] == 0) ? ' | <a href="ad_manager.php?act=activate&id='.$row['id'].'" class="b_edit">Activate</a>' : ' | <a href="ad_manager.php?act=deactivate&id='.$row['id'].'" class="b_delete">Deactivate</a>';
		$display .= '</td>';
		$display .= '</tr>';
		$display .= '<tr><td colspan="5">'.$row['code'].'</td></tr>';
		echo $display;
	}
	mysql_free_result($query);
	break;
}

?>
 </tbody>
</table>
</div>	<!-- end div id="content" -->
<?php
include('footer.php');
?>