<?php
$action          = $_GET["a"];
$topping          = $_GET["t"];
$item          = $_GET["item"];
$qty          = $_GET["qty"];
$parent          = $_GET["p"];
$crust          = $_GET["crust"];
$newkey            = $_GET["new"];

//************process any actions first


if ($action=="rem"){
	$query = "Delete from couponItem Where recordKey = '" . $item . "'";
	$rt=mysql_query($query);          // query executed 
	echo mysql_error();  
}
if ($crust =="update"){
    $query = "Update couponItem set itemNumber = '" . $newkey . "' where recordKey = '" . $item . "'";
    //echo $query ;
     mysql_query($query);          // query executed
     echo mysql_error(); 	//show any error

}
if ($action=="empty"){
	$query = "Delete from couponItem Where  customerID = '" . $_SESSION['UserKey'] . "'";
	$rt=mysql_query($query);          // query executed 
	echo mysql_error();  
}
if ($action=="update"){
	$query = "Update couponItem set qty = '" . $_POST['quantity'] . "' Where recordKey = '" . $item . "'";
	$rt=mysql_query($query);          // query executed 
	echo mysql_error();  

	$query = "Update couponItem set qty = '" . $_POST['quantity'] . "' Where parentLineNum = '" . $item . "'";
	$rt=mysql_query($query);          // query executed 
	echo mysql_error();  
}
if ($action=="addsub"){
	
		$query = "Insert into couponItem (qty, itemNumber, parentLineNum, customerID) values ('" . $qty . "', '" . $item . "', '" . $parent . "', '" .  $_SESSION['UserKey'] . "')";

	//echo $query;
	$rt=mysql_query($query);          // query executed 
	echo mysql_error();  
	$action="editsubs";
}

// *************check store preferences for tax rate and delivery charge if any
$query = "Select salesTax, deliveryCharge from storePrefs";
	$rt=mysql_query($query);          // query executed 
	echo mysql_error();               // if any error is there that will be printed to the screen
	if (mysql_num_rows($rt) !== 0) {
		while($nt=mysql_fetch_array($rt)){
			$tax = $nt[salesTax];
			$delivery = $nt[deliveryCharge];
		}
	} else {
		$tax = 0;
	}
	mysql_close;

//***********initialize variables
	$gtotal = 0;
	$totaltax = 0;
	//require_once ('mysql_connect.php');

//**********Look up couponItem list from database for logged in user
	$query = "Select recordKey, itemNumber, qty, parentLineNum, size, subitems from couponItem where customerID = '" . $_SESSION['UserKey'] . "' AND parentLineNum = ''";
	$rt=mysql_query($query);          // query executed 
		echo mysql_error();                    // if any error is there that will be printed to the screen

if ($upsell!=="1") { 	//show couponItem if upsell flag not set		
if (mysql_num_rows($rt) == 0) {
//************nothing in couponItem for logged in user, display message...
	//echo $query;
	echo '<div align="center"><font color="red"><i>Enter items for this coupon here.<br> Please enter a quantity by the the item you want and click the "add to coupon" button.</i></font><br><br></div>';
} else {	
//***********couponItem found for user...display current user's couponItem contents	
	echo '<div align="center">Coupon items';
	echo '<table width=100% border=0 cellpadding=5 cellspacing=5><tr><td><td><u><b>Qty<td><td><u><b>Item<td><u><b>Size<td><u><b>Total<td>';
	while($nt=mysql_fetch_array($rt)){
		echo '<tr><td><form action="' . $_SERVER['PHP_SELF'] .'?a=update&item=' .  $nt[recordKey] .'" method="post"><td><input type="text" name="quantity" size=1 maxlength=2 value="' . $nt[qty] . '"><td> - &nbsp;';

		//***********for each item in couponItem, look up name, price and tax status from menu item table
		$query2 = "Select itemName, itemPrice, taxable From menuItem Where itemKey = '" . $nt[itemNumber] . "'";
		$rt2=mysql_query($query2);          // query executed 
		echo mysql_error();                    // show any errors

			if (mysql_num_rows($rt2) !== 0) {
			//**********if item found, use to set price and tax status variables
				while($nt2=mysql_fetch_array($rt2)){
					$price = $nt2[itemPrice];
					$taxable = $nt2[taxable];
				echo '<td><div align="left">' . $nt2[itemName] . '</div>';
					
				} 
			
				echo '<td>';

				//************if a size is selected, look up price for selected size
				if($nt[size]!==""){	
					echo  '&nbsp;&nbsp;' . $nt[size];
					$query3 = "Select price from itemSize where itemKey = '" . $nt[itemNumber] . "' AND size = '"  . $nt[size] . "'" ;
					$rt3=mysql_query($query3);          // query executed 
					echo mysql_error();                    // if any error is there that will be printed to the screen
					while($nt3=mysql_fetch_array($rt3)){
						$price = $nt3[price];
					} 
					mysql_close;
				} 

				//************if menu item is set as taxable, add tax amount to running tax total
				if($taxable==1){
						$totaltax = number_format($totaltax + ($tax * ($price * $nt[qty])), 2, '.', ',');
					}
				
			} else {	//**********if item is not found in item table, do nothing (probably suggests an error)
					echo '<td>';
			}

			//**********for current item, add pricing to running total and running grand total
				$total = number_format(($price * $nt[qty]), 2, '.', ',');
				$gtotal = number_format(($gtotal + $total), 2, '.', ',');
			
			//**********for current item, display line item total cost, delete button, update button
				echo  '<td>$' . number_format($total, 2, '.', ',');
				echo  '<td width=30><a href="' . $_SERVER['PHP_SELF'] .'?a=rem&item=' .  $nt[recordKey] .'"><img src="images/delete.png" 				title="remove"></a>' ;
				echo  '<td><input type="submit" name="save" value="Update Qty"></form></div>' ;

			//***********if subitems allowed (for additional pizza toppings) - display currently selected toppings and add option to add more
				if ($nt[subitems]==1){
					//**********Since this is a pizza, show crust or show default and insert default crust selection into couponItem
					$query5 = "Select * FROM couponItem where parentLineNum = '" . $nt[recordKey] . "' and crust = '1'";
					$rt5=mysql_query($query5);          // query executed
						echo mysql_error();                    // show any error
						if (mysql_num_rows($rt5) == 0) {	//a crust record does not exist for this pizza
							$sq = "Select itemKey from menuItem Where defaultCrust = '1'";
							$rt1=mysql_query($sq);          // query executed
							echo mysql_error();                    // show any error
							if (mysql_num_rows($rt) !== 0) { 
								 while($nt1=mysql_fetch_array($rt1)){
                         $crustKey = $nt1[itemKey];
								}
							}

						$sq2 = "Insert into couponItem (ParentLineNum, qty, customerID, itemNumber, crust) values ('" . $nt[recordKey] . "', '";
            $sq2 = $sq2 . $nt[qty] . "', '" . $_SESSION['UserKey']  . "', " . $crustKey  . ", '1')" ;
            //echo $sq2;
            mysql_query($sq2);          // query executed
						echo mysql_error(); 	//show any error

						}


					//**********list any current subitems (toppings) added to pizza
                                      				$query5 = "Select * FROM couponItem where parentLineNum = '" . $nt[recordKey] . "' order by crust DESC";
						$rt5=mysql_query($query5);          // query executed
						echo mysql_error();                    // show any error
						
						while($nt5=mysql_fetch_array($rt5)){
						//***********for each topping (sub item) found in couponItem for this item, look up price, item name & tax status		
							$query2 = "Select itemName, itemPrice, taxable From menuItem Where itemKey = '" . 								$nt5[itemNumber] . "'";
							$rt2=mysql_query($query2);          // query executed 
							echo mysql_error();                    // show any error
						//***********if topping/subitem found in menu item table, copy info to variables
						while($nt2=mysql_fetch_array($rt2)){
							$price = $nt2[itemPrice];
							$taxable = $nt2[taxable];
							$name = $nt2[itemName];
							$qty = $nt5[qty];
										//**********for current topping item, add pricing to running total and running grand total
				      $total = number_format(($price * $nt[qty]), 2, '.', ',');
				      $gtotal = number_format(($gtotal + $total), 2, '.', ',');
						}

						//***********display any left or right side selections
						                           echo '<tr><td colspan=2><div align="center"><i>' ;
								if($nt5[halfA]=='1'){
									echo 'Left half only';
								} elseif($nt5[halfB]=='1'){
									echo 'Right half only';
								}
								
						//************if item is a crust selection, show option to change
                       $cq = "select recordKey from menuCategory where categoryName = 'Pizza Crust'";
                       $cq1=mysql_query($cq);          // query executed
								       	echo mysql_error();
                       	while($rs6=mysql_fetch_array($cq1)){
                                 $catKey =     $rs6[recordKey];
                         }
                         mysql_close;

						//************display topping name, price
								echo  '</i></div><td><td><div align="left">+ ' . $name . '</div>';
						                           echo '<td><td>$'; echo number_format(($qty * $price), 2, '.', ','); 

						//************if topping set as taxable, add tax to running tax total
								if($taxable==1){
								$totaltax = number_format($totaltax + ($tax * ($price * $nt[qty])), 2, '.', ','); 
									}
			$total = $total + ($qty * $price);
			//echo $total;
									echo '<td><a href="' . $_SERVER['PHP_SELF'] .'?a=rem&item=' .  $nt5[recordKey] .'"><img src="images/delete.png" title="remove"></a>';

       //*********This item is a crust selection - give option to change                                }
       if($nt5[crust]=='1'){	//this item is a crust...
								if(($crust=="change")&&($item==$nt5[recordKey])){	//show other crust options here:
									$crustqry = "Select itemKey, itemName, itemPrice from menuItem Where categoryKey='" . $catKey . "'";
									$cq=mysql_query($crustqry);          // query executed
									echo mysql_error();

									while($rs5=mysql_fetch_array($cq)){

										echo '<tr><td colspan=2><td colspan=3><div align="left"><i><a href="' . $_SERVER['PHP_SELF'] .'?crust=update&item=' .
										$nt5[recordKey] .'&new=' . $rs5[itemKey] . '"><font color="blue">' . $rs5[itemName] . ' - ($' . number_format(($rs5[itemPrice]*$nt5[qty]), 2, '.', ',') . ')</font></a></i></div>';

									}

								} else {    //this item is not chosen for a change, give option to change
								echo '<tr><td colspan=2><td colspan=2><a href="' . $_SERVER['PHP_SELF'] .'?crust=change&item=' .  $nt5[recordKey] .'"><i>Change crust</i></a>';
								}
								}
              }             //end of topping loop
              
			//**************if in "add topping" mode & current item was selected, show topping addition section
				if(($action=="editsubs")&&($item==$nt[recordKey])){	//show edit section to add/remove toppings
		
         				 $query6 = "SELECT recordKey, categoryName from menuCategory WHERE active ='1' And categoryName = 'Pizza Toppings'";
          				$rt6=mysql_query($query6);          // query executed
	         			echo mysql_error();                    // if any error is there that will be printed to the screen

				//************If there is a Pizza Topping category, look up category key
	         			while($nt6=mysql_fetch_array($rt6)){
		                                       $categoryKey = $nt6[recordKey];	//get category key for pizza topping category
	                                       	 }
	                                       	 if (mysql_num_rows($rt6) !== 0) {

				 //***********get item name, description & price for all items in Pizza Topping category
		                                      $query2 = "SELECT itemKey, ItemName, itemPrice, description from menuItem WHERE active = '1' AND categoryKey='"  . 						$categoryKey . "' Order By ItemName";
		                                      //echo $query2;
		                                      $rt2=mysql_query($query2);          // query executed
		                                      echo mysql_error();                    // if any error is there that will be printed to the screen

				//************build list of toppings with buttons for guest to add to pizza
			                    echo '<tr><td colspan=6><div align="center"><i><font color="red">Add toppings:</font></i></div>';
		                                     while($nt2=mysql_fetch_array($rt2)){
			                                   echo '<tr><td><td valign="top"><a href="' . $_SERVER['PHP_SELF'] .'?a=addsub&t=l&qty=' . $nt[qty]  . '&item=' .  					$nt2[itemKey] .'&p=' . $nt[recordKey] . '"><img src="images/left.png" title="Add to left side only"></a>&nbsp; &nbsp;<a 					href="' . $_SERVER['PHP_SELF'] .'?a=addsub&t=r&qty=' . $nt[qty]  . '&item=' .  $nt2[itemKey] .'&p=' . $nt[recordKey] 					.'"><img src="images/right.png" title="Add to right side only"></a>&nbsp;&nbsp; <a href="' . $_SERVER['PHP_SELF'] 					.'?a=addsub&t=a&qty=' . $nt[qty]  . '&item=' .  $nt2[itemKey] .'&p=' . $nt[recordKey] .'"><img src="images/whole.png" 					title="Add to whole pizza"></a><td><td colspan=2><div align="left">' . $nt2[ItemName] . '&nbsp;&nbsp;<i>($' . 					number_format($nt2[itemPrice], 2, '.', ',') . ')</i></div>';
		                                  }
                                    echo '<br>';
	                                     }

             }   else     {

				               echo '<tr><td colspan=4><div align="right"><a href="' . $_SERVER['PHP_SELF'] .'?a=editsubs&item=' .  $nt[recordKey]	.'&qty=' . $nt[qty] . '"><i>Add more toppings</i></a></div>';
				     }
				
				}

	}
	
	echo '<tr><td colspan=8 height=1 bgcolor="black"><tr><td colspan=5><div align="right">Subtotal: <td><div align="right"><b>$' . $gtotal . '</b></div>
	<tr><td colspan=5><div align="right">tax: <td><div align="right"><b>$' . number_format($totaltax, 2, '.', ',') . '</b></div>
	<tr><td colspan=5><div align="right">Delivery: <td><div align="right"><b>$' . number_format($delivery, 2, '.', ',') . '</b></div>
	<tr><td colspan=5><div align="right">Total: <td><div align="right"><b>$' . number_format(($gtotal + $totaltax + $delivery), 2, '.', ',') . '</b></div>';
	echo '</table><br>';
	echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=submit" method="post"><input type="submit" name="order" value="Continue"></form></div>';
		echo '<br><div align="center"><a href="' . $_SERVER['PHP_SELF'] . '?a=empty">Clear Order & Start Over</a></div>';
}
	
}  else {	//upsell flag is set. prompt user to see if they are interested in an upsell item

}
	mysql_close;

   
?>