<?php
	//require_once ('includes/mysql_connect.php');

    include ('includes/db1config.php');
    include ('../includes/mysql_connect.php');
    include ('includes/admin-config.php');
	//if $allow_order_edits = 1, add controls to change the order
	//echo "allow editing: ".$allow_order_edits;
	include('menudatabase.php');
	$viewarchive = $_GET['archive'];	
	$ordernumber            = $_GET["onum"];
	if($viewarchive==1){
		$ordertable = "orderHistory";
		$itemtable = "itemHistory";
	} else {
		$ordertable = "orders";
		$itemtable = "orderItem";
	}
 //include main order info
           $query = "SELECT * FROM $ordertable where orderNumber = '" . $ordernumber . "'";
		   //echo $query; 	//for testing
           $rt=mysql_query($query);
          // query executed
		      echo mysql_error();
		      	echo '<div align="center"><h2>Order Detail</h2>';
		      	

$archive = $_POST['chkArchive'];
$delete = $_POST['chkDelete'];
$remove = $_REQUEST['rem'];
$parent = $_REQUEST['parent'];
if(!empty($remove)){
	$qry = "delete from orderItem where uniqueKey='$remove'";
	mysql_query($qry);
	if(!empty($parent)){
		$qry = "delete from orderItem where parentLineNum='$parent'";
		mysql_query($qry);
	}
	
}
//save qty change if any
if($_POST['change_qty']){
	$chg_item_key = $_POST['itemid'];
	$chg_item_qty = mysql_real_escape_string($_POST['qty']);
	if($chg_item_qty>0){
		//update qty
		$qry = "update orderItem set qty ='$chg_item_qty' where recordKey='$chg_item_key' or parentLineNum='$chg_item_key'";
		if(mysql_query($qry)){$order_msg="The quantity has been changed.";} else {$order_msg="There was a problem changing the quantity.";}
	} else {
		//remove item and sub-items from order
		$qry = "delete from orderItem where recordKey='$chg_item_key' or parentLineNum='$chg_item_key'";
		if(mysql_query($qry)){$order_msg="The item has been removed.";} else {$order_msg="There was a problem removing the item.";}
		
	}
}

//save store comments, if any
if($_POST['order_notes']){
	$qry = "update orders set store_comments ='".$_POST['order_notes']."' where orderNumber='$ordernumber'";
	if(mysql_query($qry)){$order_msg="Notes added to order.";} else {$order_msg="There was a problem adding your notes to the order.";}
}
//add cost adjustment line item if any
if($_POST['add_adjustment']){
	$adjust_amount = $_POST['price_adjust'];
	$adjust_reason = $_POST['price_adjust_reason'];
	$order_number = $_POST['ordernumber'];
	$qry="insert into orderItem (orderNumber, price_adjust, adjust_reason) values ('$order_number', '$adjust_amount', '$adjust_reason')";
	if(mysql_query($qry)){$order_msg="The cost adjustment has been saved.";} else {$order_msg="There was a problem adding the cost adjustment.";}
}


if(!empty($order_msg)){
	echo "<div align='center' style='color:red;'>$order_msg</div>";
}
 ?>
 <table>
 <td width="500">

 <div align="right">
<style type="text/css" media="print">
.printbutton {
  visibility: hidden;
  display: none;
}
</style>

<script>
document.write("<input type='button' " +
"onClick='window.print()' " +
"class='printbutton' " +
"value='Print'/>");
</script></table>

<?php
          echo '<table border=1 bordercolor="blue" cellspacing=0 cellpadding=4>';
          echo '<tr><td><div align="center">Order #<td><div align="center">Time of order<td><div align="center">Del/PU<td><div align="center">Order due<td><div align="center">Pymt <br>form<td><div align="center">Processed';
           while($nt=mysql_fetch_array($rt)){
                   echo '<tr><td><div align="center">' . $nt[orderNumber] . '<td><div align="center">' . date ('h:i', strtotime($nt[orderTime])) . '<br>' . date ('l F j, Y', strtotime($nt[orderTime])) . '<td><div align="center">';
				   if(empty($_POST['order_notes'])){
						$order_notes = $nt[store_comments];
					} else {
						$order_notes =($_POST['order_notes']);
					}
                   $query2="Select * from guestLogin where UserKey='" . $nt[UserKey] . "'";
                     //echo $query2;
                     $rt2=mysql_query($query2);
		                 echo mysql_error();
		                 
                     //get address & phone info
                     while($nt2=mysql_fetch_array($rt2)){
                     $address = $nt2[FirstName] . ' ' . $nt2[LastName];
                     $firstname =  $nt2[FirstName];
                     $lastname =  $nt2[LastName];
                     if (!empty($nt2[CompanyName])){$address .= '<br>' . $nt2[CompanyName];}
                     $address .= '<br>' . $nt2[Address1] ;
                     if (!empty($nt2[Address2])){$address .= '<br>' . $nt2[Address2];}
                     $address .=  '<br>' . $nt2[City] . ', '. $nt2[State] . ' ' .$nt2[Zip];
                     $cardtype = $nt2[cardType];
                     $cardmonth = $nt2[cardExpMonth];
                     $cardyear = $nt2[cardExpYear];
                     $cardnumber = $nt2[cardNumber];
                     $cardsec = $nt2[cardSec];
                     $cardholder = $nt2[cardholder];
                     $cardzip = $nt2[cardzip];
                     $guestphone = $nt2[Phone];
					 $email = $nt2[Email];
                   }
					
						//require_once ('mysql_connect.php');
						$query = "Select webURL 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) {
							//not found, do nothing
						} else {
							while($ntz=mysql_fetch_array($rt)){
								$webaddress = $ntz[webURL];
							}
						}
						mysql_close;
	
					$guesthtml.= "This email is regarding your order from ".$webaddress. ". Please review the order for accuracy and contact us if you feel there is an error.<br><br>"; 
					$guesthtml.="<br>Order#: $nt[orderNumber]<br>";
					$guesthtml.="Order time: ".date ('l F j, Y', strtotime($nt[orderTime]))."<br>";
					
					
                   if($nt[delivery]==1){

                     echo '<font color="red">Delivery</font><br>to:<br>' . $address . '<br>' . $guestphone  ;
                       $delivery = 1;
                     }else {
                       echo 'Pick Up<br>' . $firstname  . ' ' . $lastname  . '<br>' .$guestphone ;
                     }
                   echo '<td><div align="center">';
                   if(!empty($nt[schedule])){
                        echo $nt[schedule];
                   } else {
                        echo 'Now/ASAP';
                   }
                   echo '<td><div align="center">';
                   if($nt[payMethod]!=="card"){
                     echo $nt[payMethod];
                   }else{

		                 //while($nt2=mysql_fetch_array($rt2)){
                     echo $cardtype . '<br>' . $cardnumber . '<br>Cardholder: ' . $cardholder . '<br>Exp: ' . $cardmonth . '/'. $cardyear . '<br>Sec. code: ' . $cardsec . '<br>Billing zip: ' . $cardzip;
                    // }
                   }
                   echo'<td><div align="center">';
					if($viewarchive==1){
						echo "Archived";
					}else{
						echo'<form action="' . $_SERVER['PHP_SELF'] . '?onum=' . $nt[orderNumber] . '" method="post">
						Archive <input type="checkbox" name="chkArchive"> Delete <input type="checkbox" name="chkDelete"> <input type="submit" name="view" value="Submit">
						</form>';
					}
                 }
           echo '</table><br><br>';

    //include line item detail and pricing
// *************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];
			if ($delivery==1) {
			     $deliverychg = $nt[deliveryCharge];
			}else {
           $deliverychg = 0;
		  }
	}
	} else {
		$tax = 0;
		$deliverychg = 0;
	}
	mysql_close;

//***********initialize variables
	$gtotal = 0;
	$totaltax = 0;


//**********Look up item list from database for selected order
	$query = "Select * from $itemtable where orderNumber = '" . $ordernumber . "' AND crust=0  AND parentLineNum=0 AND price_adjust ='0.00'";
	$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) {
//************nothing in orderItem for selected order, display message...
	//echo $query;
	echo '<div align="center"><font color="red"><i>Order detail not found.</i></font><br><br></div>';
} else {	
//***********orderItem found for user...display current user's orderItem contents
	if(!empty($menudatabase)){	//select shared menu database for store for prices and detail
		include ('includes/db2config.php');
		include ('includes/mysql_connect.php');
	}
	if($allow_order_edits=='1'){
		echo"<center><form action='orderdetail.php?onum=$ordernumber' method='POST'>Send order update to: <input name='guest_email' type='text' value='$email' size='40'><input type='submit' value='Send'></form></center>";
	}
	echo '<table border=1 bordercolor="blue" cellpadding=5 cellspacing=0><tr><td><u><b>Qty<td><u><b>Item<td><u><b>Size<td><u><b>Total';
	$guesthtml.='<table border=1 bordercolor="blue" cellpadding=5 cellspacing=0><tr><td><u><b>Qty<td><u><b>Item<td><u><b>Size<td><u><b>Total';
	while($nt=mysql_fetch_array($rt)){
		if($allow_order_edits=='1'){
			//if($nt[price_adjust]=='0.00'){
				$qty_field = "<form action='' method='POST'><input type='text' name='qty' value='$nt[qty]' size='3'><input type='hidden' name='itemid' value='$nt[recordKey]' size='3'><input type='submit' name='change_qty' value='update' style='padding:0px;'></form><a href='orderdetail.php?onum=$ordernumber&rem=".$nt[uniqueKey]."&parent=".$nt[recordKey]."' title='Remove item'><div style='padding:0px; color:red;text-align:right;vertical-align:top;'>(X)</div></a>";
			//} else {
			//	$qty_field = "<form action='' method='POST'><input type='hidden' name='qty' value='0' size='3'><input type='hidden' name='itemid' value='$nt[recordKey]' size='3'><input type='submit' name='change_qty' value='X' //style='padding:0px; color:red;text-align:right;'></form>";
			//}
		} else {
			$qty_field =$nt[qty];
		}
		echo '<tr><td>' . $qty_field;
		$guesthtml.='<tr><td>' . $nt[qty];
		//***********for each item in orderItem, look up name, price and tax status from menu item table
		$query2 = "Select itemName, itemPrice, taxable, pizzaTopping 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];
				$guesthtml.='<td><div align="left">' . $nt2[itemName];
				if(!empty($nt[choicea])){ echo '<br>' . $nt[choicea]; $guesthtml.='<br>' . $nt[choicea];}
				if(!empty($nt[choiceb])){ echo '<br>' . $nt[choiceb]; $guesthtml.='<br>' . $nt[choiceb];}
				if(!empty($nt[choicec])){ echo '<br>' . $nt[choicec]; $guesthtml.='<br>' . $nt[choicec];}
             echo '</div>';
			 $guesthtml.='</div>';
				} 
			
				echo '<td>';
				 $guesthtml.='<td>';

				//************if a size is selected, look up price for selected size
				if($nt[size]!==""){	
					echo  '&nbsp;&nbsp;' . $nt[size];
					$guesthtml.='&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;
				} else  {
               echo ' - ';
			   $guesthtml.= ' - ';
        }

				//************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)

			}

			//**********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
				echo  '<td>$' . number_format($total, 2, '.', ',');
				 $guesthtml.='<td>$' . number_format($total, 2, '.', ',');
				//echo  '<td>' ;

			//***********if subitems allowed (for additional pizza toppings) - display currently selected toppings and add option to add more
				//if ($nt[subitems]==1){


            if(!empty($menudatabase)){	//select main database for store to access items on order
                include ('includes/db1config.php');
                include ('includes/mysql_connect.php');
            }
			//**********list any current subitems (toppings) added to pizza
 			$query5 = "Select * FROM $itemtable where parentLineNum = '" . $nt[recordKey] . "' order by crust DESC, halfA DESC, halfB DESC ";
			$rt5=mysql_query($query5);          // query executed
			echo mysql_error();                    // show any error
            if(mysql_num_rows!==0){
               if(!empty($menudatabase)){	//select shared menu database for store to access local store settings
                       include ('includes/db2config.php');
                       include ('includes/mysql_connect.php');
                       }
						while($nt5=mysql_fetch_array($rt5)){
						//***********for each topping (sub item) found in orderItem 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];
              		//************if a size is selected, look up price for selected size
               if($nt[size]!==""){
               $query3 = "Select price from itemSize where itemKey = '" . $nt5[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;
				        }
							$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, '.', ',');
					//	}


								
						//************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><tr><td><td colspan=2><div align="left">+ ' . $name;
								$guesthtml.='</i></div><tr><td><td colspan=2><div align="left">+ ' . $name;
								if(($allow_order_edits)=='1'){
									echo"<a href='orderdetail.php?onum=$ordernumber&rem=".$nt5[uniqueKey]."' title='Remove item'><div style='padding:0px; color:red;text-align:right;vertical-align:top;'>(X)</div></a>";
								}
								//***********display any left or right side selections
						                           echo '<i>' ;
												   $guesthtml.='<i>' ;
								if($nt5[halfA]=='1'){
									echo ' (Left half only)';
									$guesthtml.=' (Left half only)';
								} elseif($nt5[halfB]=='1'){
									echo ' (Right half only)';
									$guesthtml.=' (Right half only)';
								}
								
						                           echo '</div><td>$'; echo number_format(($qty * $price), 2, '.', ',');
												   $guesthtml.='</div><td>$'; $guesthtml.= 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;



              }             //end of topping loop
              

				
				}
}
	      if(!empty($menudatabase)){	//select main database for store to access local store settings
        include ('includes/db1config.php');
        include ('includes/mysql_connect.php');
        }
	             $dquery = "Select deliveryCharge, taxdelivery, salesTax from storePrefs";
             $dq=mysql_query($dquery);
                     echo mysql_error();
                     while($ntdq=mysql_fetch_array($dq)){
                       if($ntdq[salesTax] >0){
                               $taxrate = $ntdq[salesTax];
                         }  else {
                               $taxrate =0;
                     }
                         if(($ntdq[deliveryCharge] >0)&&($delivery ==1)){ //delivery charge applies & order is for delivery
                               $delcharge = $ntdq[deliveryCharge];
                               if(!empty($ntdq[taxdelivery])){    //if delivery charge is taxable, calculate here
                                     $deltax = $delcharge  *  $taxrate ;
                               }
                         }  else {       //order for carryout or no delivery charge applies
                               $delcharge =0;
                               $deltax = 0;
                     }

              }
	
	//**********Look up deductions/credits in order item list for selected order
	$query2 = "Select * from $itemtable where orderNumber = '" . $ordernumber . "' AND price_adjust <>'0.00'";
	$rt2=mysql_query($query2);          // query executed 
	//echo mysql_error();  
	while($nt2=mysql_fetch_array($rt2)){
		echo "<tr><td>Price adjust:<td colspan='2'>$nt2[adjust_reason]";
		$guesthtml.="<tr><td>Price adjust:<td colspan='2'>$nt2[adjust_reason]";
		echo"<a href='orderdetail.php?onum=$ordernumber&rem=".$nt2[uniqueKey]."' title='Remove item'><div style='padding:0px; color:red;text-align:right;vertical-align:top;'>(X)</div></a>";
		
		echo"<td>$nt2[price_adjust]";
		$guesthtml.="<td>$nt2[price_adjust]";
		$gtotal = $gtotal + $nt2[price_adjust];
	}
	
	if($allow_order_edits=='1'){
		echo"<tr><td valign='top'>Order Notes<td colspan=2><form action='' method='POST'><textarea name='order_notes' rows='3' cols='40'>$order_notes</textarea>";
		echo "<input type='hidden' name='ordernumber' size='40' value='$ordernumber'><div align='right'><input type='submit' name='add_notes' value='Save'></div></form>";
	}
	$guesthtml.="<tr><td valign='top'>Order Notes<td colspan=2>$order_notes";
	//if($allow_order_edits=='1'){
		//echo"<tr><td><td colspan=2><input type='submit' value='Add item to order'>";
	//}
	if($allow_order_edits=='1'){
		echo"<tr><td valign='top'>Manual line item or cost adjustment<td colspan=2><form action='' method='POST'>
		<input type='hidden' name='ordernumber' size='40' value='$ordernumber'>
		Line item:<br><input type='text' name='price_adjust_reason' size='40'>
		<br>Amount: <input type='text' name='price_adjust' size='3'>";
		echo "<input type='submit' name='add_adjustment' value='Save'><td></form>";
	}
	echo '<tr><td colspan=4 height=1 bgcolor="black">';
	$guesthtml.='<tr><td colspan=4 height=1 bgcolor="black">';
	echo'<tr><td colspan=3><div align="right">Subtotal: <td><div align="right"><b>$' . $gtotal . '</b></div>
  	<tr><td colspan=3><div align="right">Delivery: <td><div align="right"><b>$' . number_format($deliverychg, 2, '.', ',') . '</b></div>
  <tr><td colspan=3><div align="right">tax: <td><div align="right"><b>$' . number_format(($totaltax + $deltax ), 2, '.', ',') . '</b></div>
	<tr><td colspan=3><div align="right">Total: <td><div align="right"><b>$' . number_format(($gtotal + $totaltax + $deliverychg + $deltax), 2, '.', ',') . '</b></div>';
	
	$guesthtml.='<tr><td colspan=3><div align="right">Subtotal: <td><div align="right"><b>$' . $gtotal . '</b></div>
  	<tr><td colspan=3><div align="right">Delivery: <td><div align="right"><b>$' . number_format($deliverychg, 2, '.', ',') . '</b></div>
  <tr><td colspan=3><div align="right">tax: <td><div align="right"><b>$' . number_format(($totaltax + $deltax ), 2, '.', ',') . '</b></div>
	<tr><td colspan=3><div align="right">Total: <td><div align="right"><b>$' . number_format(($gtotal + $totaltax + $deliverychg + $deltax), 2, '.', ',') . '</b></div>';
	echo '</table><br>';
	$guesthtml.='</table><br>';

}

mysql_close;

if(!empty($_POST['guest_email'])){
	if(!empty($guesthtml)){
		$guestemail=$email;
		include('email_update.php');
	}
}


?>

</div>