<?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');

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


function manage_ad_form($action = 'addnew', $id = 0, $name = '', $flv_url = '', $redirect_url = '', $redirect_type = '', $active = 0)
{
	$target = '';
	switch($action)
	{
		case 'addnew':
			$target = 'videoads.php?act=addnew';
		break;
		case 'edit':
			$target = ($id != 0) ? 'videoads.php?act=edit&id='.$id : 'videoads.php?act=edit';
		break;
	}
	// generate form
	$form	=	'<form name="videoad" method="post" action="'.$target.'">';
	$form  .= '
	<table width="100%" border="0" cellpadding="4">
	  <tr class="table_row1">
		<td class="fieldtitle" width="210px">Name:</td>
		<td><input type="text" name="name" value="'.$name.'" size="40" /></td>
	  </tr>
	  <tr  class="table_row1">
		<td class="fieldtitle" valign="top">Video Ad location<br /><small>Supported file types: <span style="color:#000">*.flv</span></small></td>
		<td><input type="text" name="flv_url" value="'.$flv_url.'" size="120" /></td>
	  </tr>
	  <tr  class="table_row1">
		<td class="fieldtitle" valign="top">Advertised URL</td>
		<td><input type="text" name="redirect_url" value="'.$redirect_url.'" size="120" /></td>
	  </tr>
	  <tr  class="table_row1">
		<td class="fieldtitle" valign="top">Redirect Type</td>
		<td><label><input type="radio" name="redirect_type" value="0"';
			if($redirect_type == 0)
				$form .= ' checked ';
			$form .= ' /> Open <em>Advertised URL</em> in new window</label><br />';
			
		$form .= '<label><input type="radio" name="redirect_type" value="1"';
			if($redirect_type == 1)
				$form .= ' checked ';
			$form .= ' /> Open <em>Advertised URL</em> in the same window</label>';
	$form.= '</td>
	  </tr>
	  <tr  class="table_row1">
		<td class="fieldtitle">Status</td>
		<td><label><input name="status" type="radio" value="0" />Inactive</label> <label><input name="status" type="radio" value="1" checked/> Active</label></td>
	  </tr>
	  <tr>
		<td>&nbsp;</td>
		<td><input type="submit" name="Submit" value="Submit" class="inputbutton" /></td>
	  </tr>
	</table>
	';	
	return $form;
}

?>

<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>Video Ads Manager</h2>
<br />
<?php if($action != 'addnew' && $action != 'edit') { ?>
<a href="videoads.php?act=addnew" class="b_edit">Create new video ad</a>
<?php } ?>
<?php echo $info_msg; ?>
<?php

if ($config['video_player'] == 'jwplayer')
{
	?>
	<div class="info_msg_err">
	 Sorry, this feature is not compatible with the 'JW FLV Player'. 
	</div>
	<?php
}

switch($action)
{
	case 'addnew':
		if($_GET['act'] == 'addnew')
		{
			if(isset($_POST['Submit']))
			{
				
				$arr_fields = array('name' => "Name", 'flv_url' => "Video Ad location", 'redirect_url' => 'Advertised URL', 'status' => '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>";	
				}
				if($errors != '')
				{
					echo "<div class=\"info_msg_err\"><ul>".$errors."</ul></div><br />";
					echo manage_ad_form('addnew', 0, $_POST['name'], $_POST['flv_url'], $_POST['redirect_url'], $_POST['redirect_type'], $_POST['status']);
				}
				else
				{
					$status = ($_POST['status'] == 1) ? 1 : 0;
					$redirect_url = trim($_POST['redirect_url']);
					$name = trim($_POST['name']);
					$flv_url = trim($_POST['flv_url']);
					$redirect_type = trim($_POST['redirect_type']);
					$hash = md5( rand(0,123) . time() );
					
					if( !preg_match("/http:\/\//", $redirect_url) )
						$redirect_url = "http://".$redirect_url;
					if( !preg_match("/http:\/\//", $flv_url) )
						$flv_url = "http://".$flv_url;
					
					$sql = "INSERT INTO pm_videoads SET hash = '".$hash."',
														name = '".secure_sql($name)."', 
														flv_url = '".secure_sql($flv_url)."',
														redirect_url = '".secure_sql($redirect_url)."', 
														redirect_type = '".secure_sql($redirect_type)."',
														status = '".$status."'";
														
					
					$query = mysql_query($sql);
					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">Your video ad was created!';
						if($status == 0)
							$msg .= "<br /><small>P.S. Don't forget to activate it.</small>";
						$msg .= '</div>';
						$msg .= '<input name="continue" type="button" value="&laquo; Return to Video Ad Manager page" onClick="location.href=\'videoads.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('name' => "Name", 'flv_url' => "Video Ad location", 'redirect_url' => 'Advertised URL', 'status' => 'Status');
				$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('addnew', $id, $_POST['name'], $_POST['flv_url'], $_POST['redirect_url'], $_POST['redirect_type'], $_POST['status']);
					echo "</div>";
					include('footer.php');
					exit();
				}
				$status = ($_POST['status'] == 1) ? 1 : 0;
				$redirect_url = trim($_POST['redirect_url']);
				$name = trim($_POST['name']);
				$flv_url = trim($_POST['flv_url']);
				$redirect_type = trim($_POST['redirect_type']);
				
				if( !preg_match("/http:\/\//", $redirect_url) )
					$redirect_url = "http://".$redirect_url;					
				if( !preg_match("/http:\/\//", $flv_url) )
					$flv_url = "http://".$flv_url;
				
				$sql = "UPDATE pm_videoads SET name = '".secure_sql($name)."', 
												flv_url = '".secure_sql($flv_url)."',
												redirect_url = '".secure_sql($redirect_url)."', 
												redirect_type = '".secure_sql($redirect_type)."',
												status = '".$status."'
										 WHERE id = '".$id."' ";
				$query = mysql_query($sql);
				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\">Updated!</a></div>";
					echo '<input name="continue" type="button" value="&laquo; Return to Video Ad Manager page" onClick="location.href=\'videoads.php\'" class="inputbutton" />';
				}
			}
			else
			{
				$query = mysql_query("SELECT * FROM pm_videoads 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['name'], $ad['flv_url'], $ad['redirect_url'], $ad['redirect_type'], $ad['status']);
			}
		}
	
	break;
	case 'delete':
	case 'activate':
	case 'deactivate':
	case 'reset':
	default:
		
		$total_ads = count_entries('pm_videoads', '', '');
		
		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>";
			else
			{
				$query = mysql_query("DELETE FROM pm_videoads 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_videoads SET status='1' WHERE id = '".$id."' LIMIT 1";
				else
					$sql = "UPDATE pm_videoads SET status='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>";
				}
			}
		}
		if($action == 'reset')
		{
			$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 = "UPDATE pm_videoads SET impressions='0', clicks='0' WHERE id='".$id."'";
				$query = mysql_query($sql);
				if( !$query )
					echo "<div class=\"info_msg_err\">There was a problem while resetting your ad's CTR<br /><strong>MySQL returned:</strong> ".mysql_error()."</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" cellspacing="1">
 <thead> 
  <tr>
    <th>Name</th>
	<th width="8%">Impressions</th>
	<th width="7%">Clicks</th>
	<th width="7%">CTR</th>
    <th width="10%">Status</th>
	<th width="23%">Action</th>
  </tr>
 </thead>
 <tbody>
  <?php
	
	// display all ads
	$query = mysql_query("SELECT * FROM pm_videoads ORDER BY id ASC");
	$display = '';
	$i = 0;
	while($row = mysql_fetch_assoc($query))
	{	
		$clean_title = str_replace(array('"', "'"), array('', "\'"), $row['name']);
		$col = ($i++ % 2) ? 'table_row1' : 'table_row2';
		$display = '';
		$display .= '<tr class="'.$col.'">';
		$display .= '<td>'.$row['name'].'</td>';
		$display .= '<td align="center">'.$row['impressions'].'</td>';
		$display .= '<td align="center">'.$row['clicks'].'</td>';
		$display .= '<td align="center">';
			$display .= "<b>";
			if($row['clicks'] == 0 && $row['impressions'] == 0)
			{
				$display .= '0';
			}
			else
			{
				$display .= round( ($row['clicks']*100/$row['impressions']), 2);
			}
		$display .='%</b></td>';
		$display .= '<td align="center">';
			$display .= "<small>";
			$display .= ($row['status'] == 1) ? "Active" : "Inactive";
			$display .= "</small>";
		$display .= '</td>';
		$display .= '<td align="center">';		
			$display .= '<a href="videoads.php?act=edit&id='.$row['id'].'" class="b_edit">Edit</a> | <a href="#" onClick="delete_ad(\''. $clean_title .'\', \'videoads.php?act=delete&id='.$row['id'].'\')" class="b_delete">Delete</a>';
			$display .= ($row['status'] == 0) ? ' | <a href="videoads.php?act=activate&id='.$row['id'].'" class="b_edit">Activate</a>' : ' | <a href="videoads.php?act=deactivate&id='.$row['id'].'" class="b_delete">Deactivate</a>';
			$display .= ' | <a href="videoads.php?act=reset&id='.$row['id'].'" class="b_delete">Reset CTR</a>';
		$display .= '</td>';
		$display .= '</tr>';
		echo $display;
	}
	mysql_free_result($query);
	
	$total_active_ads = count_entries('pm_videoads', 'status', '1');
	update_config('total_videoads', $total_active_ads);
	
	break;
}

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