<?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;
	}

    $action   = $_GET["a"];
    $userKey  = $_GET["key"];
     if ($action == "add") {
         echo '<div class="mainForm">
                        <form action="' . $_SERVER['PHP_SELF'] . '?a=save" method="post">
                            <div class="leftForm">
                            <table>    
                                <tr><td>First Name:</td><td><input type="text" name="first_name" id="Item" size="20"></td></tr>

                                <tr><td>Last Name:</td><td><input type="text" name="last_name" id="Item" size="20" ></td></tr>

                                <tr><td>Company Name :</td><td><input type="text" name="company_name" id="Item" ></td></tr>

                                <tr><td>Address 1:</td><td><input type="text" name="address_1" id="Item" size="20"></td></tr>

                                <tr><td>Address 2:</td><td><input type="text" name="address_2" id="Item" size="20"></td></tr>

                                <tr><td>City:</td><td><input type="text" name="city" id="Item" size="20"></td></tr>

                                <tr><td>State</td><td><input type="text" name="state" id="Item" size="20" ></td></tr>

                                <tr><td>Zip</td><td><input type="text" name="zip" id="Item" size="20" ></td></tr>

                                <tr><td>Address Type</td><td><input type="text" name="address_type" id="Item" ></td></tr>

                                <tr><td>Phone</td><td><input type="text" name="phone" id="Item" size="20" ></td></tr>

                                <tr><td>Email (User)</td><td><input type="text" name="email" id="Item" size="20" ></td></tr>

                                <tr><td>Password</td><td><input type="text" name="password" id="Item" size="20" ></td></tr>
                                
                                <tr><td>On Hold</td><td><input type="checkbox" name="on_hold" value="1" ></td></tr>

                                <tr><td>Comments</td><td><input type="text" name="comments" id="Item" size="20"></td></tr>

                                 <tr><td>Active:</td><td><input type="checkbox" name="active" value="1" ></td></tr>

                                 <tr><td>Member id:</td><td><input type="text" name="member_id" id="Item" size="20" ></td></tr>

                                 <tr><td>Delivery Zone:</td><td><input type="text" name="delivery_zone" id="Item" ></td></tr>

                                 <tr><td>Address Verified:</td><td><input type="text" name="address_verified" id="Item" ></td></tr>

                                <tr><td>Subscribed:</td><td><input type="checkbox" name="subscribed"  value="1"  ></td></tr>

                                <tr><td>
                                <input id="save-button" type="submit" name="edit" value="SAVE" />
                                </td></tr>
                            </table>
                         </div>
                         <div class="saveButton">
                             
                         </div>   
               </div>  
                ';
    }else if ($action == "update" || $action == "save") {

        $setQuery = array(); 

        if (isset($_POST["first_name"])) {
           $setQuery[] = " FirstName = '" . mysql_real_escape_string($_POST['first_name']). "'"; 
        }

        if (isset($_POST["last_name"])) {
           $setQuery[] = " LastName = '" . mysql_real_escape_string($_POST['last_name']). "'"; 
        }

        if (isset($_POST["company_name"])) {
           $setQuery[] = " CompanyName = '" . mysql_real_escape_string($_POST['company_name']). "'"; 
        }

        if (isset($_POST["address_1"])) {
           $setQuery[] = " Address1 = '" . mysql_real_escape_string($_POST['address_1']). "'"; 
        }

        if (isset($_POST["address_2"])) {
           $setQuery[] = " Address2 = '" . mysql_real_escape_string($_POST['address_2']). "'"; 
        }

        if (isset($_POST["city"])) {
           $setQuery[] = " City = '" . mysql_real_escape_string($_POST['city']). "'"; 
        }

        if (isset($_POST["state"])) {
           $setQuery[] = " State = '" . mysql_real_escape_string($_POST['state']). "'"; 
        }

        if (isset($_POST["zip"])) {
           $setQuery[] = " Zip = '" . mysql_real_escape_string($_POST['zip']). "'"; 
        }

        if (isset($_POST["address_type"])) {
           $setQuery[] = " addressType = '" . mysql_real_escape_string($_POST['address_type']). "'"; 
        }

        if (isset($_POST["phone"])) {
           $setQuery[] = " Phone = '" . mysql_real_escape_string($_POST['phone']). "'"; 
        }

        if (isset($_POST["email"])) {
            $setQuery[] = " Email = '" . mysql_real_escape_string($_POST['email']). "'"; 
            if($action == "save"){
                $setQuery[] = " UserId = '" . mysql_real_escape_string($_POST['email']). "'"; 
            }
        }

        if (isset($_POST["on_hold"]) && $_POST["on_hold"] == "1") { 
            $setQuery[] = " onHold = 1"; 
        }else{
            $setQuery[] = " onHold = 0"; 
        }

        if (isset($_POST["comments"])) {
           $setQuery[] = " comments = '" . mysql_real_escape_string($_POST['comments']). "'"; 
        }

        if (isset($_POST["subscribed"]) && $_POST["subscribed"] == "1") { 
            $setQuery[] = " subscribed = 1"; 
        }else{
            $setQuery[] = " subscribed = 0"; 
        }

        if (isset($_POST["active"]) && $_POST["active"] == "1") { 
            $setQuery[] = " Active = 1"; 
        }else{
            $setQuery[] = " Active = 0"; 
        }

        if (isset($_POST["member_id"])) {
           $setQuery[] = " member_id = '" . mysql_real_escape_string($_POST['member_id']). "'"; 
        }

        if (isset($_POST["delivery_zone"])) {
           $setQuery[] = " delivery_zone = '" . mysql_real_escape_string($_POST['delivery_zone']). "'"; 
        }

        if (isset($_POST["address_verified"])) {
           $setQuery[] = " address_verified = '" . mysql_real_escape_string($_POST['address_verified']). "'"; 
        }


        if($setQuery > 0){
            if($action == "save"){

                if (isset($_POST["password"])) {
                   $setQuery[] = " password = PASSWORD('" . mysql_real_escape_string($_POST['password']). "')"; 
                }

                $query = "INSERT INTO guestLogin SET " . implode(',', $setQuery);
                //echo $query  ;
                mysql_query($query) or die(mysql_error());   //execute query
                //confirmation message that delete worked...
                echo '<div align="center"><font color=red>Customer Added successfully.</font></div>';
            }
            
            if($action == "update"){
               // print_r($_POST);
               if($_POST['delete']){
               	$query = "Delete from guestLogin WHERE UserKey = '" . $_GET['key'] ."'" ;
				        mysql_query($query) or die(mysql_error());
				        echo '<div align="center"><font color=red>Customer deleted successfully here.</font></div>';
                echo "<script>parent.location.href=parent.location.href;</script>";
               } else {
	                $query = "UPDATE guestLogin SET " . implode(',', $setQuery) . " WHERE UserKey = '" . $_GET['key'] ."'" ;
	                //echo $query  ;
	                mysql_query($query) or die(mysql_error());   
	                //confirmation message that update worked...
	                echo '<div align="center"><font color=red>Customer updated successfully.</font></div>';
			   }
                $action="edit";   //change so that edited item will be displayed again after update
            }
        }


    } else if ($action =="edit") {
        $query = "SELECT * from guestLogin WHERE UserKey ='" . $userKey . "'";
        $rt=mysql_query($query);          // query executed 
        echo mysql_error(); // if any error is there that will be printed to the screen
        while($nt=mysql_fetch_array($rt)){
            echo '<div class="mainForm">
                        <form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $userKey . '" method="post">
                            <div class="leftForm">
                            <table>    
                                <tr><td>First Name:</td><td><input type="text" name="first_name" id="Item" size="20" value="' . $nt[FirstName] . '"></td></tr>

                                <tr><td>Last Name:</td><td><input type="text" name="last_name" id="Item" size="20" value="' . $nt[LastName] . '"></td></tr>

                                <tr><td>Company Name :</td><td><input type="text" name="company_name" id="Item" size="20" value="' . $nt[CompanyName] . '"></td></tr>

                                <tr><td>Address 1:</td><td><input type="text" name="address_1" id="Item" size="20" value="' . $nt[Address1] . '"></td></tr>

                                <tr><td>Address 2:</td><td><input type="text" name="address_2" id="Item" size="20" value="' . $nt[Address2] . '"></td></tr>

                                <tr><td>City:</td><td><input type="text" name="city" id="Item" size="20" value="' . $nt[City] . '"></td></tr>

                                <tr><td>State</td><td><input type="text" name="state" id="Item" size="20" value="' . $nt[State] . '"></td></tr>

                                <tr><td>Zip</td><td><input type="text" name="zip" id="Item" size="20" value="' . $nt[Zip] . '"></td></tr>

                                <tr><td>Address Type</td><td><input type="text" name="address_type" id="Item" size="20" value="' . $nt[addressType] . '"></td></tr>

                                <tr><td>Phone</td><td><input type="text" name="phone" id="Item" size="20" value="' . $nt[Phone] . '"></td></tr>

                                <tr><td>Email (User)</td><td><input type="text" name="email" id="Item" size="20" value="' . $nt[Email] . '"></td></tr>
                                
                                <tr><td>Password</td><td><input type="password" name="password" id="Item" size="20" ></td></tr>
                                
                                <tr><td>On Hold</td><td><input type="checkbox" name="on_hold" ' . (($nt[onHold] == 1)? "checked" : "") . ' value="1" ></td></tr>

                                <tr><td>Comments</td><td><input type="text" name="comments" id="Item" size="20" value="' . $nt[comments] . '"></td></tr>

                                 <tr><td>Active:</td><td><input type="checkbox" name="active" ' . (($nt[Active] == 1)? "checked" : "") . ' value="1" ></td></tr>

                                 <tr><td>Member id:</td><td><input type="text" name="member_id" id="Item" size="20" value="' . $nt[member_id] . '"></td></tr>

                                 <tr><td>Delivery Zone:</td><td><input type="text" name="delivery_zone" id="Item" size="20" value="' . $nt[delivery_zone] . '"></td></tr>

                                 <tr><td>Address Verified:</td><td><input type="text" name="address_verified" id="Item" size="20" value="' . $nt[address_verified] . '"></td></tr>

                                <tr><td>Subscribed:</td><td><input type="checkbox" name="subscribed" ' . (($nt[subscribed] == 1)? "checked" : "") . ' value="1"  ></td></tr>

                                <tr><td><input id="save-button" type="submit" name="edit" value="SAVE" /> <input id="save-button" type="submit" name="delete" class="deleteUser" value="DELETE USER" /></td></tr>
                            </table>
                         </div>
                         <div class="saveButton">
                            
                         </div>   

               </div>  
                ';
                    
        }

    }else{

		$query = "SELECT * from coupon order by couponNumber DESC";
		$rt=mysql_query($query);          // query executed
		echo mysql_error();                    // if any error is there that will be printed to the screen

    echo '<br>';
	


	if(isset($_GET["page"]))
	$page = (int)$_GET["page"];
	else
	$page = 1;

	$setLimit = 15;
	$pageLimit = ($page * $setLimit) - $setLimit;

	$where = $url = '';
	if(isset($_GET['search'])){
		$value = mysql_real_escape_string(trim($_GET['search']));
		$where = " WHERE `FirstName` LIKE '%$value%' OR `LastName` LIKE '%$value%' OR Email LIKE '%$value%' "; 
		$url = "?search=$value";
	}
	
	

      //display customer list
        $query2="select UserKey, FirstName, LastName, Email from guestLogin $where LIMIT ".$pageLimit." , ".$setLimit;
		// where UserID in(select UserKey as UserID from orderHistory)";
        $rs2=mysql_query($query2);
        echo '<style type="text/css" media="screen">
            td {
                width: 10%;
            }
        </style>';
		
		echo '<div class="formsearch"><form method="get">
			<label>Search</label> 
			<input name="search" type="text" /> 
			<input name="send" type="submit" value="Search" />
		</form> ';
		
		if($where !=''){
			echo '<a href="customers_new.php" class="show" >Show All</a>';
		}
		echo '</div>';
		
        echo'<center><table width=100% cellpadding=5 cellspacing=5><tr><td colspan="2"><strong>CUSTOMER NAME</strong></td><td><strong>EMAIL ADDRESS</strong></td><td style="width: 10%;"><strong>Action</strong></td></tr>
		<tr><td colspan="4"><hr /></td></tr>';
        while($nt2=mysql_fetch_array($rs2)){
              echo'<tr><td width=20%>' . $nt2[FirstName] . '</td><td width=20%>' . $nt2[LastName] . '</td><td width=60%>' . $nt2[Email] .'</td><td width=20%><input id="save-button" style="margin-bottom:3px;margin-left:5px;" class="popup edit-menu-item edit-menu-item-' . $nt2[UserKey] . '" data-popup-id="' . $nt2[UserKey] . '" data-cat-key="' . $nt2[UserKey] . '" type="submit" name="edit" value="Edit" />&nbsp;<input id="save-button" style="margin-bottom:3px;margin-left:5px;" class="sendcustomerEmail" data-id="' . $nt2[UserKey] . '" type="submit" value="Send an email" /><div class="toPopDiv menu-item" id="popup_' . $nt2[UserKey] . '"> <div class="close"></div>
                    <span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
                    <iframe class="menu-item-iframe edit" id="iframe-'.$nt2[UserKey].'" data-menu-id="' . $nt2[UserKey] . '" src=""></iframe>
                </div> <!--toPopup end--> </td></tr>';
        }
		
		echo "<tr><td colspan='5'>".displayPaginationBelow($setLimit,$page,$where,$url)."</td></tr>";
		
/*		for ($i=1; $i<=$total_pages; $i++) { 
					echo "<tr><td colspan='5'><a href='customers.php?page=".$i."'>".$i."</a></td></tr>"; 
		};*/		
		
 
        echo '<tr><td colspan="4"></td></tr><tr><td colspan="2" style="text-align:center";>
        <a style="width:150px;" class="popup add-menu-item" id="save-button" class="popup add-menu-item" data-popup-id="add">New Customer</a></td><td ></td></tr>';
        
        mysql_close;
        echo'</table>';
        // Add menu item popup
        echo "
            <div class='toPopDiv menu-item' id='popup_add'> 
                <div class='close'></div>
                <span class='ecs_tooltip'>Esc to close <span class='arrow'></span></span>
                <iframe class='menu-item-iframe' id='iframe-add' src=''></iframe>
            </div> <!--toPopup end-->
        ";
        
        echo '<div align="center"><br><br>';

        echo '<br>
		
		</div></table></center>';
	
}


  function displayPaginationBelow($per_page,$page,$where,$url){
	   $page_url = "?";
	   if($where != ''){
		   $page_url = $url."&";
	   }
    	$query = "SELECT COUNT(*) as totalCount FROM guestLogin $where ";
    	$rec = mysql_fetch_array(mysql_query($query));
    	$total = $rec['totalCount'];
        $adjacents = "2"; 

    	$page = ($page == 0 ? 1 : $page);  
    	$start = ($page - 1) * $per_page;								
		
    	$prev = $page - 1;							
    	$next = $page + 1;
        $setLastpage = ceil($total/$per_page);
    	$lpm1 = $setLastpage - 1;
    	
    	$setPaginate = "";
    	if($setLastpage > 1)
    	{	
    		$setPaginate .= "<ul class='setPaginate'>";
                    $setPaginate .= "<li class='setPage'>Page $page of $setLastpage</li>";
    		if ($setLastpage < 7 + ($adjacents * 2))
    		{	
    			for ($counter = 1; $counter <= $setLastpage; $counter++)
    			{
    				if ($counter == $page)
    					$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
    				else
    					$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";					
    			}
    		}
    		elseif($setLastpage > 5 + ($adjacents * 2))
    		{
    			if($page < 1 + ($adjacents * 2))		
    			{
    				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
    				{
    					if ($counter == $page)
    						$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
    					else
    						$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";					
    				}
    				$setPaginate.= "<li class='dot'>...</li>";
    				$setPaginate.= "<li><a href='{$page_url}page=$lpm1'>$lpm1</a></li>";
    				$setPaginate.= "<li><a href='{$page_url}page=$setLastpage'>$setLastpage</a></li>";		
    			}
    			elseif($setLastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
    			{
    				$setPaginate.= "<li><a href='{$page_url}page=1'>1</a></li>";
    				$setPaginate.= "<li><a href='{$page_url}page=2'>2</a></li>";
    				$setPaginate.= "<li class='dot'>...</li>";
    				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
    				{
    					if ($counter == $page)
    						$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
    					else
    						$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";					
    				}
    				$setPaginate.= "<li class='dot'>..</li>";
    				$setPaginate.= "<li><a href='{$page_url}page=$lpm1'>$lpm1</a></li>";
    				$setPaginate.= "<li><a href='{$page_url}page=$setLastpage'>$setLastpage</a></li>";		
    			}
    			else
    			{
    				$setPaginate.= "<li><a href='{$page_url}page=1'>1</a></li>";
    				$setPaginate.= "<li><a href='{$page_url}page=2'>2</a></li>";
    				$setPaginate.= "<li class='dot'>..</li>";
    				for ($counter = $setLastpage - (2 + ($adjacents * 2)); $counter <= $setLastpage; $counter++)
    				{
    					if ($counter == $page)
    						$setPaginate.= "<li><a class='current_page'>$counter</a></li>";
    					else
    						$setPaginate.= "<li><a href='{$page_url}page=$counter'>$counter</a></li>";					
    				}
    			}
    		}
    		
    		if ($page < $counter - 1){ 
    			$setPaginate.= "<li><a href='{$page_url}page=$next'>Next</a></li>";
                $setPaginate.= "<li><a href='{$page_url}page=$setLastpage'>Last</a></li>";
    		}else{
    			$setPaginate.= "<li><a class='current_page'>Next</a></li>";
                $setPaginate.= "<li><a class='current_page'>Last</a></li>";
            }

    		$setPaginate.= "</ul>\n";		
    	}
    
    
        return $setPaginate;
    } 
	

?>
<script type="text/javascript">
    $('.popup.edit-menu-item').click(function() {
        var popupId = $(this).data('popup-id');
        $('#iframe-'+popupId).attr('src', 'customeriframe.php?a=edit&key='+popupId);
    });

    $('.popup.add-menu-item').click(function() {
        var popupId = $(this).data('popup-id');
        $('#iframe-'+popupId).attr('src', 'customeriframe.php?a=add');
    });


    $('.deleteUser').click(function() {
      var retVal = confirm("Are you sure you want to delete this user account?");
      if( retVal == true ){
        return true;
      } else{
        return false;
      }
    });


</script>