<?php
if ($_SESSION['FirstName'] == "") {
	echo 'You are not authorized to view this page. <br><br>You may <a href="index.php">log in here.</a>';
	exit;
	}


//require_once ('mysql_connect.php');
$action          = $_GET["a"];
$editcoupon          = $_POST["coupon"];
if(empty($editcoupon)){
	$editcoupon=$_GET["coupon"];
}
//echo '$editcoupon='.$editcoupon;
$showfantools          = $_GET["fantools"];
if(empty($editcoupon)){
$editcoupon          = $_GET["key"];
}
	//echo 'Action = ' . $action; (for testing)
//require_once ('config.inc');
if ($action == "upload") {
    include('cpn-img.php');
    
}

if ($action == "delimage") {
    $query1 = "update coupon set imageName = Null where couponNumber =" . $editcoupon ;
		mysql_query($query1);

}

if ($action == "add") {
			
			$query = "Insert into coupon (title, body, footer, expiration) Values ('" . $_POST['title'] . "', '" .  $_POST['body']  . "', '" .  $_POST['footer'] . "', '" .  $_POST['expiration'] . "' )";

			if (!mysql_query($query)){
					echo $query;
  					die('Error: ' . mysql_error());
 			 } else {
				echo "<div align=center><font color=red>Coupon added successfully.</font></div>";
				
			}
		}
 if ($action == "delitem") {
       $delqry = "delete from couponItem where itemNumber='" . $_GET['key'] . "' AND categoryKey ='" . $_GET['list'] . "' AND couponCode ='" . $_GET['coupon'] . "'";
      //echo $delqry;
       mysql_query($delqry);
 }
  if ($action == "size") {
       $updsize = "update couponItem set size='" . $_GET['size'] . "' where itemNumber='" . $_GET['key'] . "' AND categoryKey ='" . $_GET['list'] . "' AND couponCode ='" . $_GET['coupon'] . "'";
      //echo $delqry;
       mysql_query($updsize);
	   $editcoupon=$_GET['couponkey'];
 }
if ($action == "update") {
	$delete = $_POST['chkdelete'];
	$active = $_POST['chkactive'];
	$online = $_POST['chkonline'];
	$fbpost = $_POST['chkfacebook'];

	if (empty($delete)) {
		//delete not checked, save other updated info

		$query = "UPDATE coupon SET title = '" . $_POST['title'] . "',  body = '" . $_POST['body'] . "', footer= '" . $_POST['footer'] . "', expiration = '" . $_POST['expiration'] .  "', Active ='";
		if (empty($active)){
			$query = $query . "0'";
		} else {
			$query = $query . "1'";
		}
		$query .= ", onlineOnly ='";	
		if (empty($online)){
			$query = $query . "0'";
		} else {
			$query = $query . "1'";
		}	
		$query .= ", code ='" . $_POST['code'] . "'";
		$query .= ", discountAmount ='" . $_POST['discount'] . "'";
		$query .= ", discountPercent ='" . $_POST['percent'] . "'";
		$query .= ", couponPrice ='" . $_POST['price'] . "'";
		$query .= ", linktoURL ='" . $_POST['couponlink'] . "'";
		$query .= ", minOrder ='" . $_POST['minorder'] . "'";

		if(!empty($_POST['coupontype'])){
		 $query .= ", couponType ='" . $_POST['coupontype'] . "'";

		}

		$query = $query . " WHERE couponNumber = '" . $_GET['key'] ."'" ;
		//echo $query;
		mysql_query($query) or die(mysql_error());   //execute query
		//if coupon type3, need to save any items selected to go on this coupon
 
		$qry="Select max(categoryKey) as categoryKey from couponItem where couponCode='" . $_POST['code'] . "'";
		 $rslt=mysql_query($qry);
		 //echo $qry ;
		 while($cn=mysql_fetch_array($rslt)){
		   $highestnum=$cn[categoryKey] + 1;
		 }
		$count=1;
		 while($count <= $highestnum){
		   $itemNum = "couponitem" . $count;
		   //echo "<br>itemNum=" . $itemNum ;
		 $couponitem =  $_POST[$itemNum];
		  //echo "<br>couponitem=" . $couponitem ;
		   if (!empty($couponitem)){
				$cpnaddqry= "Insert into couponItem (itemNumber, qty, couponCode, categoryKey) values ('".$couponitem . "', '1', '" . $_POST['code'] . "', '". $count . "')";
				//echo '<br>' . $cpnaddqry;
				mysql_query($cpnaddqry);
		   }
		   $count = $count +1;
		 }
		//confirmation message that delete worked...
		echo "<div id='submission-success-message-wrapper'><font color=red> ****** Coupon updated successfully ******</font></div>";
    //if (!empty($fbpost)) {   //post to facebook page
	//	         $postdata = "Special coupon offer: " . $_POST['title'] .  "<br><a href='http://www.restaurantonline.biz/wwwroot/activetest2/order.php?coupon='" . $_POST['code'] . "'>Use Coupon</a>";
	//	         include('posttofb.php');

    //}
	} else { 
		
		
	$query = "DELETE FROM coupon WHERE couponNumber = '" . $_GET["key"] ."'" ;
	
	

	mysql_query($query) or die(mysql_error());   //execute query

	//confirmation message that delete worked...
	echo "<font color=red>Coupon deleted successfully.</font>";

		}
	}	//end of update query
	

	echo "<div align=center><font color='#368ff2'>Note:</font> this page is used to manage the coupons shown on your coupon page.<br>
	If you want to change the other content on the coupon page, <a href='editpages.php?a=select&pagename=COUPONS'><font color='#368ff2'>click here</font></a>.</font></div>";
	
   //create selector to choose coupon to edit
 echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=select" method="post">';
 echo'Choose coupon to edit:<br /><select style="width:200px;" name="coupon"><optionvalue="">Make Selection</option>';
 $pages="Select couponNumber, title from coupon";
 $pg=mysql_query($pages);
  while($pnt=mysql_fetch_array($pg)){
   echo '<option value='. $pnt[couponNumber];
   if($pnt[couponNumber]==$editcoupon){echo ' selected="selected"';}
   echo'>' .$pnt[title] . '</option>';
}

mysql_close;
echo '</select> <input id="save-button" type="submit" name="select" value="Edit"></form>
<div id="add-new-wrapper">
<form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new coupon: (title) <br><input type="text" name="title" size=50>

		<input id="save-button" type="submit" name="save" value="Save">
		</form>
		<br></div>

<br /><hr /><br />';


//filter based on selected coupon, or select most recently added
    if(!empty($editcoupon)){
    $query = "SELECT * from coupon where couponNumber ='" . $editcoupon ."'";
    } else{
      $query2="Select max(couponNumber) as couponNumber from coupon";
      $rs2 = mysql_query($query2);
      while($nt2=mysql_fetch_array($rs2)){
          $query = "SELECT * from coupon where couponNumber ='" . $nt2[couponNumber]."'" ;
      }
      mysql_close;
  }
	$socprefs="Select fbpage, twitterid from storePrefs";
	$socrt=mysql_query($socprefs);
	 while($socnt=mysql_fetch_array($socrt)){
		$fbpage = $socnt[fbpage];
		$twitterid = $socnt[twitterid];
	}
	mysql_close;
	

	$rt=mysql_query($query);          // query executed 
	echo mysql_error();                    // if any error is there that will be printed to the screen



//echo "coupon=" . $editcoupon;
echo '<div align="center"><table border=0 cellpadding=0 cellspacing=8>';
if(!empty($editcoupon)){
	while($nt=mysql_fetch_array($rt)){
	//set variables for use outside of record loop
	
	$cpnnumber = $nt[couponNumber];
	$code = $nt[code];
	$title = $nt[title];
	$discount = $nt[discountAmount];
	$couponprice = $nt[couponPrice];
	$description = $nt[body];
	$footer = $nt[footer];
	$expiration = $nt[expiration];
	$buttonURL = $nt[linktoURL];
	if(empty($editcoupon)){$editcoupon=$nt[couponNumber];} //set variable to default coupon since coupon not selected yet

	
  echo '<a name="' . $nt[couponNumber] . '"></a>';
	echo '<tr><td><div align=left>Coupon #:<td valign=top><div align=left><input type="text" name="number" size="30" value="' . $nt[couponNumber] . '" disabled="disabled">';



	echo '<tr><td><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[couponNumber] . '#' . $nt[couponNumber] . '" method="post">
	<tr><td><div align=left>Title:<td valign="top"><div align=left><input type="text" name="title" size="60" value="' . $nt[title] . '">';

	echo '<tr><td><div align=left>Online code#:<td valign=top><div align=left>
	<input type="text" name="code"  size="30" value="' . $nt[code] . '">';

echo '<tr><td valign="top"><div align=left>Online code only:<td valign=top><div align=left><input type="checkbox" name="chkonline"';
	if(!empty($nt[onlineOnly])){
		echo 'checked=true';
	} 
echo '> <font color="red" size=2><i>"Online code only" means it is not viewable or <br>printable, only accessible when guest enters <br>promo code.</i></font>';
$coupontype= $nt[couponType];
  echo '<tr><td><div align=left>Coupon type:<td valign=top><div align=left>
  <select name="coupontype" style="width:390px;">
  <option value="">Select type of coupon</option>
  <option value="1"';
  if ($coupontype==1){ echo ' selected="selected"';}
  echo '>Discount amount for orders over...</option>
  <option value="2"';
  if ($coupontype==2){ echo ' selected="selected"';}
  echo '>Discount percentage off of order total</option>
  <option value="3"';
  if ($coupontype==3){ echo ' selected="selected"';}
  echo '>Fixed price coupon</option>
  <option value="4"';
  if ($coupontype==4){ echo ' selected="selected"';}
  echo '>Discount amount off specific items</option>
  </select>';
  
  $currentdate= date("m/d/Y h:i:s");
    
  if ($coupontype==4){
 	echo '<tr><td><div align=left>Discount amount:<td valign=top><div align=left><input type="text" name="discount" size="40" value="' . $nt[discountAmount] . '">';

  }
  if ($coupontype==3){
	echo '<tr><td><div align=left>Coupon Price:<td valign=top><div align=left><input type="text" name="price" size="40" value="' . $nt[couponPrice] . '">';

  }
  if ($coupontype==1){
	echo '<tr><td><div align=left>Discount amount:<td valign=top><div align=left><input type="text" name="discount" size="40" value="' . $nt[discountAmount] . '">';
	echo '<tr><td><div align=left>Minimum Order:<td valign=top><div align=left><input type="text" name="minorder" size="40" value="' . $nt[minOrder] . '">';
  }
  if ($coupontype==2){
	echo '<tr><td><div align=left>Discount percent:<td valign=top><div align=left><input type="text" name="percent" size="40" value="' . $nt[discountPercent] . '">';
  echo '<tr><td><div align=left>Minimum Order:<td valign=top><div align=left><input type="text" name="minorder" size="40" value="' . $nt[minOrder] . '">';
  }
	echo '<tr><td valign="top"><div align=left><div style="margin-top:10px;">Button URL (full address):</div><td valign=top><div align=left><input type="text" name="couponlink" size="60" value="' . $nt[linktoURL] . '">
  <br><font color="red" size=2><i>Redirects guest to 3rd party ordering site if not<br> using integrated online order system.</i></font>';
	
	echo '<tr><td valign=top><div align=left>Description:<td valign=top><div align=left><textarea cols=62 rows=3 name="body">' . $nt[body] . ' </textarea>';  

	echo '<tr><td><div align=left>Disclaimer:<td valign=top><div align=left><input type="text" name="footer" size="60" value="' . $nt[footer] . '">';  

	echo '<tr><td><div align=left>Expiration date:<td valign=top><div align=left><input type="text" name="expiration" size="10" value="' . $nt[expiration] . '">';

echo '<tr><td colspan=2>';

echo '<tr><td><div align=left>Active:<td valign=top><div align=left><input type="checkbox" name="chkactive"';
	if(!empty($nt[active])){
		echo 'checked=true';
	} 
echo '>';

 echo '<tr><td valign=top><div align=left>Delete this coupon:<td valign=top><div align=left><input type="checkbox" name="chkdelete" value="true">';


       		 if(($coupontype==3)||($coupontype==4)){   //need to select specific items for this type of coupon
       		 
       		 echo '<tr><td colspan=2><div align="center"><u>Items on this coupon</u><br>
            <font color="red"><i>Guest will get to select one item from each item list below.</i></font>';
           echo '<table with=100% border =1 cellspacing=0 bordercolor="black" cellpadding=5>';
           
           include('editcpnitems.php');

                echo '</table></div>';
     }  //end of coupon item selection section



	echo '<tr><td><td valign=top><div><input id="save-button" type="submit" name="save" value="Save"></form>';
	
	echo '<tr><td colspan=2><strong>Add a coupon image</strong>:' ;
    if(!empty($nt[imageName])){
      echo '<br><img src="../images/'.$nt[imageName].'">
      <br><a href="' . $_SERVER['PHP_SELF'] . '?a=delimage&key=' . $nt[couponNumber] . '"><font color="red">Remove image</font></a>';
    }
 ?>
        <!--************************BEGINNING OF IMAGE UPLOAD *************************-->
        <?php if(isset($_REQUEST['upload_message'])){?>
            <div class="upload_message_<?php echo $_REQUEST['upload_message_type'];?>">
            <?php echo htmlentities($_REQUEST['upload_message']);?>
            </div>
		<?php }


echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=upload&key=' . $nt[couponNumber] . '#' . $nt[couponNumber] . '" method="post" enctype="multipart/form-data" name="image_upload_form" id="image_upload_form" style="margin-bottom:0px;">
<label>Image file, maximum 2MB. it can be jpg, png or gif:</label><br />
          <input name="image_upload_box" type="file" id="image_upload_box" size="40" />
          <input id="save-button" type="submit" name="submit" value="Upload image" />

     <br />
	<br />
    <input name="max_width_box" type="hidden" id="max_width_box" value="100" size="4">
      <input name="max_height_box" type="hidden" id="max_height_box" value="100" size="4">
<input name="submitted_form" type="hidden" id="submitted_form" value="image_upload_form" />
          </form>';
?>
<tr><td colspan=2><hr>
<!--<h2>Share through Social Networking</h2>-->
    <!--************************END OF IMAGE UPLOAD *************************-->
<?php
   
	}	
}

    echo '</table></div></table></div>';

?>
<?php 
/*if(!empty($editcoupon)){
if($showfantools==1){
	echo '<div align="center"><a href="' . $_SERVER['REQUEST_URI'] . '&fantools=0&coupon='.$editcoupon.'"><font color="blue">Hide Additional Options</font></a></div>';
 
}else{
	echo '<div align="center"><a href="' . $_SERVER['REQUEST_URI'] . '&fantools=1&coupon='.$editcoupon.'"><font color="blue">Show Additional Options</font></a></div>';
}
//include('fantools.php');
}
*/
?>
