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

date_default_timezone_set($_SESSION['timezone']);

if($_POST['ref_code']){	//a ref code here means a tip is being processed on this reference code
	$tipamount=$_POST['tipamount'];
	if(!empty($tipamount)){	//if tip amount not empty, process now
		include('includes/capture_tip.php');
		if($approved=='1'){
			$query = "update orders set cc_tip_paid='1' where cc_ref_code='$_POST[ref_code]'";
			mysql_query($query);
		} else {
			echo "error processing tip.";
		}
	}
}
//include('../timezone.php');
//date_default_timezone_set($timezone);


//require_once ('mysql_connect.php');
$ordernumber = $_GET["onum"];
$archive     = $_POST['chkArchive'];
$delete      = $_POST['chkDelete'];
$process     = $_GET['process'];
$reports     = $_GET['reports'];


 if (!empty($process)) {
	  //set order new flag to 0 since order has been marked as processed
 $query = "update orders set new = 0, in_production=NOW() where orderNumber = '" . $process . "'";
           mysql_query($query);
 }
  if (!empty($archive)) {
        $aquery = "INSERT INTO orderHistory (orderNumber, approved, delivery, payMethod, comments, orderTotal, UserKey,
        note, orderTime) SELECT orderNumber, approved, delivery, payMethod, comments, orderTotal, UserKey, note, orderTime
        FROM orders WHERE orderNumber = '" . $ordernumber ."'" ;
        //echo $aquery . '<br />';
        if (!mysql_query($aquery)){
					echo $aquery;
  					die('Error: ' . mysql_error());
			     }
        $aquery = "INSERT INTO itemHistory (UserKey, itemNumber, qty, recordKey, parentLineNum, size, subitems, halfA, halfB,
        crust, categoryKey, couponCode, orderNumber, freeTopping) SELECT UserKey, itemNumber, qty, recordKey, parentLineNum,
        size, subitems, halfA, halfB, crust, categoryKey, couponCode, orderNumber, freeTopping
        FROM orderItem WHERE orderNumber = '" . $ordernumber ."'" ;
        //echo $aquery ;
        if (!mysql_query($aquery)){
					echo $aquery;
  					die('Error: ' . mysql_error());
			     }
  $delete = 1; //set so that data will be deleted after archiving
  
  
}

if (!empty($delete)) {
  //remove line items for selected order number
			$query = "Delete From orderItem WHERE orderNumber = '" . $ordernumber ."'" ;

			if (!mysql_query($query)){
					echo $query;
  					die('Error: ' . mysql_error());


			}
			//remove order record for selected order number
			$query = "Delete From orders WHERE orderNumber = '" . $ordernumber ."'" ;

			if (!mysql_query($query)){
					echo $query;
  					die('Error: ' . mysql_error());
 			 } else {
         if(!empty($archive )){
          echo "<div align=center><font color=red>Order # '" . $ordernumber ."' archived successfully.</font></div>";
         }   else {
				  echo "<div align=center><font color=red>Order # '" . $ordernumber ."' deleted successfully.</font></div>";
				 }
			}

		}





		$query = "SELECT * from orders";


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





$query = "SELECT * FROM orders order by new desc, orderTime desc";
 $rt=mysql_query($query);
    //echo '<div align="center"><div style="padding:1% 2% 0% 2%"><font color="red">Click the "Process order" link to remove the NEW status from an order and move it to the bottom.<br /><br /></font></div></div>
	
	echo'<ul id="live-order-buttons">';
	if($reports<>""){
		$menubar = '<li><a href="?LiveOrders">View Live Orders</a></li>
		<li><a href="?reports=DailySummary">Daily Summary Report</a></li>
		<li><a href="?reports=CustomerOrders">Order Report</a></li>

		<li><a href="" onclick="close_window();return false;">Exit</a></li>';
	} else {
		$menubar = '<li><a href="">Refresh</a></li>
		<li><a href="?reports=all">Reports</a></li>
		<li><a href="?archive=all">Archive All</a></li>
		<li><a href="" onclick="close_window();return false;">Exit</a></li>';
	}
	echo $menubar;
	echo '</ul>';

if($reports<>""){
	if($reports=="DailySummary"){
		//print_r($_POST);
		$x=0;
		$date = date("Y-m-d");
		$date_selector = "<select name='selectDate'>";
		$selectedDate = $_POST['selectDate'];
		//echo "selected: $selectedDate ";
		while($x<14){
		    $date = strtotime("-$x day");		    
		    //echo date("m-d-Y", $date)."<br>";
			$date_selector .= "<option value='".date("Y-m-d", $date)."'";
			if($selectedDate==date("Y-m-d", $date)){$date_selector .= " selected='selected'";}
			$date_selector .= ">".date("l m-d-Y", $date)."</option>";		    
			$x++;
		}
		$date_selector .= "</select>";
		echo "<form action='liveorders.php?reports=DailySummary' method='POST'>".$date_selector."<input type='submit' name='submit' value='Show Daily Summary'></form>";
		
	
		
		
		if($_POST[submit]=="Show Daily Summary" && $selectedDate<>""){
			$query       = "SELECT * FROM orders WHERE DATE(orderTime) = '".$selectedDate."' ORDER BY recordKey DESC";
			//echo $query;
			$rt          = mysql_query($query); 
			
			$str = '<center>
		    		
		            <table width=100% cellpadding=5 cellspacing=5 id="invoiceTable" >
		            <tr>
		                <td>
		                    <strong>Order Number</strong>
		                </td>
		                <td>
		                    <strong>Customer Name</strong>
		                </td>
		                <td>
		                    <strong>Order Date & Time</strong>
		                </td>
		                <td>
		                    <strong>Order Total</strong>
		                </td>
		                <td>
		                    <strong>Action(s)</strong>
		                </td>
		            </tr>
		            <tr class="appendInvoice">
		                <td colspan="8"><hr /></td>
		            </tr>';
		            $grandTotal = 0;
		            while ( $row = mysql_fetch_array($rt)) {
		            	// echo "<pre>";print_r($row);die('here');
		                    $str.='<tr class="orders">
		                            <td width=20%>' . $row['orderNumber'] . '</td>
		                            <td width=20%>' . $arr[$row['UserKey']] . '</td>
		                            <td width=25%>' . $row['orderTime'] . '</td>
		                            <td width=20%>' . $row['orderTotal'] . '</td>
		                            <td style="padding:4px 4px;" width=25%><a style="width:50px;" id="save-button" class="popup add-menu-item"  href="orderdetail.php?onum='.$row['orderNumber'].'" target="_blank" >View Order</a></td></tr>';
	                    $grandTotal+=$row['orderTotal'];
		            }
	
		            if( $grandTotal != 0 ){
		            	$str.='<tr><td colspan="4"><div align="right"><br>Daily Total: <b>$'.$grandTotal.'</b></div></td></tr>';
		            }
		                
		            $str.='</table>
		            </table>
		            </center>';
		    echo $str;
	    }
	}	
	if($reports=="CustomerOrders"){
		//echo "<form action='liveorders.php?reports=DailySummary' method='POST'>".$date_selector."<input type='submit' name='submit' value='Show Daily Summary'></form>";
		
		if($_POST[submit]=="Show Daily Summary" && $selectedDate<>""){
			$query = "SELECT * FROM orders WHERE DATE(orderTime) = '".$selectedDate."' ORDER BY recordKey DESC";
			$rt    = mysql_query($query); 
		} else {
			echo"<div id='report-selection-area' style='background:#b2b0b0;margin: 0;margin-top:-10px;padding: 0px;padding-bottom:9px;'><p style='font-size: 24px;font-weight: bold;margin-left:10px;'>Search</p><form method='POST' action='liveorders.php?reports=CustomerOrders'>";
			echo "<label><b>Start Date:&nbsp;&nbsp;</b><input type='text' name='beginDate' value='".$_POST['beginDate']."' id='datepicker1'  value='' style='' ></label>";
			echo "<div class='search-area-break3'><label><b>End Date:&nbsp;&nbsp;</b><input type='text' name='endDate' id='datepicker2' value='".$_POST['endDate']."' style='' ></label></div>";
			echo "<div class='search-area-break'><label><b>Customer Name:&nbsp;&nbsp;</b><input type='text' name='customerName' value='".$_POST['customerName']."' style='' ></label>";
			echo "<div class='search-area-break3'><label><b>Order #:&nbsp;&nbsp;</b><input type='text' name='orderNumber' value='".$_POST['orderNumber']."' style=';' ></label></div></div>";
			echo "<div class='search-area-break2'><label><input id='save-button' type='submit' value='Search'></label>&nbsp;&nbsp;<label><input id='save-button' type='button' class='reset' value='Reset'></label></div></form></div>";

			if( $_POST['beginDate'] != '' && $_POST['endDate'] != '' && $_POST['customerName']=='' && $_POST['orderNumber']=='' ){
				$query  = "SELECT * FROM orders WHERE DATE(orderTime) >= '".$_POST['beginDate']."' AND DATE(orderTime) <= '".$_POST['endDate']."' ORDER BY recordKey DESC";

			} elseif ( $_POST['customerName'] != '' && $_POST['beginDate'] == '' && $_POST['endDate'] == '' && $_POST['orderNumber']=='' ) {
				$query  = "SELECT * FROM orders INNER JOIN guestLogin ON guestLogin.UserKey = orders.UserKey WHERE (guestLogin.FirstName LIKE '%" . $_POST['customerName'] . "%' OR guestLogin.LastName LIKE '%" . $_POST['customerName'] . "%') ORDER BY orders.recordKey DESC";

			} elseif ( $_POST['customerName'] == '' && $_POST['beginDate'] == '' && $_POST['endDate'] == '' && isset($_POST['orderNumber']) && $_POST['orderNumber'] != '' ) {
				$query  = "SELECT * FROM orders WHERE orderNumber = '".$_POST['orderNumber']."' ORDER BY recordKey DESC";

			} elseif ( $_POST['beginDate'] != '' && $_POST['endDate'] != '' && $_POST['customerName'] != '' && $_POST['orderNumber'] == '') {
				$query  = "SELECT * FROM orders INNER JOIN guestLogin ON guestLogin.UserKey = orders.UserKey WHERE (guestLogin.FirstName LIKE '%" . $_POST['customerName'] . "%' OR guestLogin.LastName LIKE '%" . $_POST['customerName'] . "%') AND DATE(orderTime) >= '".$_POST['beginDate']."' AND DATE(orderTime) <= '".$_POST['endDate']."' ORDER BY orders.recordKey DESC";

			} elseif ( $_POST['customerName'] != '' && $_POST['orderNumber'] != '' && $_POST['beginDate'] == '' && $_POST['endDate'] == '' ) {
				$query  = "SELECT * FROM orders INNER JOIN guestLogin ON guestLogin.UserKey = orders.UserKey WHERE (guestLogin.FirstName LIKE '%" . $_POST['customerName'] . "%' OR guestLogin.LastName LIKE '%" . $_POST['customerName'] . "%') AND orderNumber = '".$_POST['orderNumber']."' ORDER BY orders.recordKey DESC";

			} elseif (  $_POST['beginDate'] != '' && $_POST['endDate'] != '' && $_POST['orderNumber'] != ''  && $_POST['customerName'] == '' ) {
				$query  = "SELECT * FROM orders WHERE DATE(orderTime) >= '".$_POST['beginDate']."' AND DATE(orderTime) <= '".$_POST['endDate']."' AND orderNumber = '".$_POST['orderNumber']."' ORDER BY recordKey DESC";

			} else if ( $_POST['beginDate'] != '' && $_POST['endDate'] != '' &&  $_POST['customerName'] != '' && $_POST['orderNumber'] !='' ){
				$query  = "SELECT * FROM orders INNER JOIN guestLogin ON guestLogin.UserKey = orders.UserKey WHERE (guestLogin.FirstName LIKE '%" . $_POST['customerName'] . "%' OR guestLogin.LastName LIKE '%" . $_POST['customerName'] . "%') AND DATE(orderTime) >= '".$_POST['beginDate']."' AND DATE(orderTime) <= '".$_POST['endDate']."' AND orderNumber = '".$_POST['orderNumber']."' ORDER BY orders.recordKey DESC";

			} else if ( $_POST['beginDate'] != '' && $_POST['endDate'] == '' && $_POST['customerName'] == '' && $_POST['orderNumber'] == '' ) {
				$query  = "SELECT * FROM orders WHERE DATE(orderTime) >= '".$_POST['beginDate']."' ORDER BY recordKey DESC";
 
			} else if(  $_POST['beginDate'] == '' && $_POST['endDate'] != '' && $_POST['customerName'] == '' && $_POST['orderNumber'] == '' ){
				$query  = "SELECT * FROM orders WHERE DATE(orderTime) <= '".$_POST['endDate']."' ORDER BY recordKey DESC";

			} else {
				$query       = "SELECT * FROM orders ORDER BY recordKey DESC";
			}
			//echo $query;
			$rt          = mysql_query($query); 
		}	
			$str = '<center>
		    		
		            <table width=100% cellpadding=5 cellspacing=5 id="invoiceTable" >
		            <tr>
		                <td>
		                    <strong>Order Number</strong>
		                </td>
		                <td>
		                    <strong>Customer Name</strong>
		                </td>
		                <td>
		                    <strong>Order Date & Time</strong>
		                </td>
		                <td>
		                    <strong>Order Total</strong>
		                </td>
		                <td>
		                    <strong>Action(s)</strong>
		                </td>
		            </tr>
		            <tr class="appendInvoice">
		                <td colspan="8"><hr /></td>
		            </tr>';
		            $grandTotal = 0;
		            while ( $row = mysql_fetch_array($rt)) {
		            	// echo "<pre>";print_r($row);die('here');
		            	
		            	$query99 = "select FirstName, LastName from guestLogin where UserKey = '".$row['UserKey']."'";
		                $result = mysql_query($query99);
						while($data = mysql_fetch_array($result)){
							$username = $data['LastName'].", " . $data['FirstName'];
						}
						    $str.='<tr class="orders">
		                            <td width=20%>' . $row['orderNumber'] . '</td>
		                            <td width=20%>' . $username . '</td>
		                            <td width=25%>' . $row['orderTime'] . '</td>
		                            <td width=20%>' . $row['orderTotal'] . '</td>
		                            <td style="padding:4px 4px;" width=25%><a style="width:50px;" id="save-button" class="popup add-menu-item"  href="orderdetail.php?onum='.$row['orderNumber'].'" target="_blank" >View Order</a></td></tr>';
	                    //<td width=20%>' . $username . " ".$arr[$row['UserKey']] . '</td>
	                    $grandTotal+=$row['orderTotal'];
		            }
	
		            if( $grandTotal != 0 ){
		            	$str.='<tr><td colspan="4"><div align="right"><br>Grand Total: <b>$'.$grandTotal.'</b></div></td></tr>';
		            }
		                
		            $str.='</table>
		            </table>
		            </center>';
		    echo $str;
	   // }
	}
	//echo "<div><a href='liveorders.php?reports=DailySummary'>Daily Summary</a></div>";
	//echo "<div><a href='liveorders.php?reports=CustomerOrders'>Orders</a></div>";	
} else {	
	echo '<table id="live-order-table" width=100% border=0 bordercolor="#000" cellspacing=0 cellpadding=0>';
    echo '<tr id="live-header"><th><div align="center">Order #</div><th><div align="center">Type/Payment</div><th><div align="center">Order Detail</div><th><div align="center">Final</div>';
 while($nt=mysql_fetch_array($rt)){
     $note = "";
     echo '<tr><td  style="border-bottom:none;" valign="top" class="order-no-column"><div>';
     if ($nt['new']==1){echo '<span class="new-indicator">NEW</span>' ;}
	
	 
	 //$orderTime = date("h:i:A", strtotime($nt['orderTime']) + date('Z') +$_SESSION['server_offset']);
	 $orderTime = date("h:i:A", strtotime($nt['orderTime'])+ date('Z'));
//echo date('Z'); die();
	//echo "db time: ".$nt[orderTime]."<br>";
	//echo "offset: " . date('Z')."<br>";
	//echo "zone time: ". strtotime($nt['orderTime'])+ date('Z')."<br>";
	//.$nt[orderTime]; echo ": ".date('Z'). "zone time: " $nt[orderTime] + date('Z')."<br>"; 

     echo $nt[orderNumber] . '<br /><span id="mobile-hide">Date: </span>'.date ('m/d/Y', strtotime($nt[orderTime])).'<br /><span id="mobile-hide">Time: </span>'.$orderTime.'</div><td style="border-bottom:none;" valign="top" class="type-column"><div>Type: ';
     //echo $nt[orderNumber] . '<br /><span id="mobile-hide">Date: </span>'.date ('m/d/Y', strtotime($nt[orderTime])).'<br /><span id="mobile-hide">Time: </span>'.date ('h:i:A', $orderTime).'</div><td style="border-bottom:none;" valign="top" class="type-column"><div>Type: ';
	 
     if($nt[delivery]==1){echo '<font color="red">Delivery</font>';}else{echo 'Pick Up';}
	//echo '</div><td class="order-total-column"><div>$' . $nt[orderTotal] . '</div><td class="payment-method-column"><div>' . $nt[payMethod] . '</div><td class="order-detail-column"><div>';
	if($nt[note]!="n/a" && $nt[note]!=""){
		$note = "<br><i><b>* See cust notes</b></i>"; 	
    }
    echo '<br>Total: $' . $nt[orderTotal] . '<br>Pymt: ' . $nt[payMethod] . $note .'</div>';
    echo '<td class="order-detail-column" rowspan="2">';
	//if((!empty($nt[cc_ref_code]))&&($nt[payMethod]=="card")&&($nt[cc_tip_paid]=='0')){ //show tip form for cc orders with a reference code, and that have not already been charged a tip
	//	echo '<div class="add-tip-box"><form action="'.$_SERVER[PHP_SELF].'" method="post">Add tip to card: <input type="text" size=5 name="tipamount"> ';
	//	echo'<input type="hidden" size=5 name="ref_code" value="'.$nt[cc_ref_code].'"><input id="save-button" type="submit" id="update" name="addtip" value="Process"></form>';
	//}
    echo '<form action="orderdetail.php?onum=' . $nt[orderNumber] . '" target=blank" method="post">';
        if ($nt['new']!=1){$button_id = "live-order-button_full";} else {$button_id="live-order-button";}
		echo '<input id="'.$button_id.'" type="submit" name="view" id="update" value="View/Print">';
		if ($nt['new']==1){
			echo '<a id="live-order-button2" href="' . $_SERVER['PHP_SELF'] . '?process=' . $nt[orderNumber] . '">MARK AS READ <span id="mobile-hide"></span></a>';
		}	
		echo'</form></div>';
		echo'<td class="final-column" rowspan="2"><div><form action="' . $_SERVER['PHP_SELF'] . '?onum=' . $nt[orderNumber] . '" method="post">
		<div class="archive-inline"><input type="checkbox" name="chkArchive"> Archive</div><div class="archive-inline"><input type="checkbox" name="chkDelete"> Delete</div><input type="submit" id="save-button" name="view" value="Submit">
		</form></div>';
	echo "<tr><td colspan='2' style='border-top:none;'>";
	/*if((!empty($nt[cc_ref_code]))&&($nt[payMethod]=="card")&&($nt[cc_tip_paid]=='0')){ //show tip form for cc orders with a reference code, and that have not already been charged a tip
		echo '<div class="add-tip-box"><form action="'.$_SERVER[PHP_SELF].'" method="post">Add tip<span id="mobile-hide"> to card</span>: <input type="text" size=3 name="tipamount"> ';
		echo'<input type="hidden" size=3 name="ref_code" value="'.$nt[cc_ref_code].'"><input id="save-button" type="submit" id="update" name="addtip" value="Process"></form></div>';
	}*/
 }
    echo '</table></div></div>';
}
	
	

?>

    
