<?php
//===============================================================================
// Search the orders for any field that matches the search criterea 
//===============================================================================
    error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);      //all error but warnigns & notices

    session_start();                            //get a handle to session

    if (! $_SESSION['cust_id'])                 //if there is no session for customer                           
        header("Location: shop.php");           //redirect to login page
?>
<html>
<head>
<title>Search data in database</title>
<style>
a     {text-decoration:none; color:brown}
table {font-family:arial; font-size:11pt; background-color:f9f9f9; border:2px solid brown}
td    {border:1px solid gray} 
</style>
</head>
<body bgcolor=lightyellow>
<h1><center>The Ice Cream Shop</center></h1>

<?php

    $data = array();                            #define an array
    
    display_form();

    if ($_GET)                                  
    {
        read_data();
        display_result();
    }

//===============================================================================
// Display search form
//===============================================================================
    function display_form()
    {

        print "<h3>Welcome back $_SESSION[cust_fname]</h3>";

        $search = $_GET['q'];                   #get the search argument
        $sort   = $_GET['s'];                   #get the sort order

        print "<form method=get action=$_SERVER[PHP_SELF]>                
               Search for: 
               <input type=text   name=q value='$search'>
               <input type=submit        value=Search>
                 use <b>%</b> for all
               <hr> \n";
    }

//===============================================================================
// Read / search for orders based on search criterea
//===============================================================================
    function read_data()
    {
        global $host, $data;   

        $host      = 'localhost';
        $DBname    = 'demo2';
        $DBuser    = 'demo2';
        $DBpswd    = 'demo2';
 
        $search = "'%". $_GET[q] ."%'";                         #wrap the search in % wildcards
        $search = str_replace(' ','%',$search);                 #for multi-words, insert % wildcard                                             

        if (!$_GET[s])                                          #if no sort order is provided 
             $_GET[s] = 'order_id-desc';                        #sort by last order_id

        $sort   = explode('-', $_GET[s]);                       #split on '-'
        $field  = $sort[0]; 
        $seq    = $sort[1]; 

        $connect = mysqli_connect($host,$DBuser,$DBpswd,$DBname);   #connect to db server 
        if (! $connect) 
            die('Could not connect: ' . mysqli_connect_error());

        $query = "SELECT firstname,lastname,address,flavor,topping,creditCard,order_id 
                  FROM cust_order
                  WHERE (cust_id = $_SESSION[cust_id])          
                    AND (lower(firstname) LIKE $search
                     OR  lower(lastname)  LIKE $search
                     OR  lower(address)   LIKE $search
                     OR        flavor     LIKE $search
                     OR        topping    LIKE $search
                     OR        creditCard LIKE $search
                     OR        order_id   LIKE $search) 
                  ORDER BY $field $seq";                        

        $cursor = mysqli_query($connect,$query);                #execute the query
        if (! $cursor) 
            die('Could not execute query: ' . mysqli_error($connect));
       
        $i=0;
        while ($row = mysqli_fetch_array($cursor))              #get each row as an array
            $data[$i++] = $row;                                 #store row in 2 dim array    

        mysqli_free_result($cursor);                            #free result buffer
        mysqli_close($connect);                                 #close connection
    }

//===============================================================================
// Display the list of matching orders in an HTML table
// allow sorting of columns 
//===============================================================================
    function display_result()
    {
        global $data;   

        $search = $_GET[q];                     #get the search argument
        $sort   = $_GET[s];                     #get the sort order

        if (! $search)
        {
            print '<font color=red>Please enter search criteria, or % </font>';
            return;
        }

        $name_seq = ($sort =='lastname-asc')  ? 'lastname-desc'   : 'lastname-asc';
        $addr_seq = ($sort =='address-asc')   ? 'address-desc'    : 'address-asc';
        $flav_seq = ($sort =='flavor-asc')    ? 'flavor-desc'     : 'flavor-asc';
        $topg_seq = ($sort =='topping-asc')   ? 'topping-desc'    : 'topping-asc';
        $card_seq = ($sort =='creditCard-asc')? 'creditCard-desc' : 'creditCard-asc';
        $ordr_seq = ($sort =='order_id-asc')  ? 'order_id-desc'   : 'order_id-asc';

        print "<table width=800> 
               <tr bgcolor=tan>
               <th><a href=$_SERVER[PHP_SELF]?q=$search&s=$name_seq>Name</a>
               <th><a href=$_SERVER[PHP_SELF]?q=$search&s=$addr_seq>Address</a>     
               <th><a href=$_SERVER[PHP_SELF]?q=$search&s=$flav_seq>Flavors</a>     
               <th><a href=$_SERVER[PHP_SELF]?q=$search&s=$topg_seq>Toppings</a>    
               <th><a href=$_SERVER[PHP_SELF]?q=$search&s=$card_seq>Credit Card</a> 
               <th><a href=$_SERVER[PHP_SELF]?q=$search&s=$ordr_seq>Order Num</a> 
               <th width=110>Action</th> \n";

        foreach($data as $row)
        {
            $first      = $row[0];
            $last       = $row[1];
            $address    = $row[2];
            $flavor     = $row[3];
            $topping    = $row[4];
            $creditCard = $row[5];
            $order_id   = $row[6];
                
            $address2  = nl2br($address);                       #change all \n to <br>
            $flavor2   = str_replace("," , "<br>", $flavor);    #put multiple values
            $topping2  = str_replace("," , "<br>", $topping);   #on separate lines

            print "<tr valign=top>";
            print "
                   <td>$first $last</td><td>$address2</td><td>$flavor2</td>
                   <td>$topping2</td><td>$creditCard</td><td>$order_id</td>
                   <td><a href=shopDBUpd.php?order=$order_id><img src=update.gif title=update border=0></a>
                       <a href=shopDBUpd.php?order=$order_id><img src=delete.gif title=delete border=0></a></td> \n";              
        }    

        print "</table> <hr>\n";
    }

//===============================================================================

?>

<?php include "../../include.php"; ?>              <!-- hyperlink to see the code -->

<center>
<base href=/~sultans/php/demo/5session/shop/ >
<a href=shopCart.php>   shop          </a> |
<a href=shopDBAdd.php > checkout      </a> | 
<a href=shopDBList.php> list orders   </a> |
                        search             |
<a href=shopProf.php>   profile       </a> |
<a href=shop.php?out=y> logout        </a>
</center>
</body>
</html>