

<?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></div></div>';
    exit;
}


//require_once ('mysql_connect.php');
$action       = $_GET["a"];
$action2      = $_GET["action2"];
$move         = $_GET["d"];
$editchoice   = $_GET["editchoice"];
$choicekey    = $_GET["ckey"];
$deleteoption = $_GET["del"];
$active       = $_POST['chkactive'];
$multisized   = $_POST['chksizes'];
$taxable      = $_POST['chktaxable'];
$oldnum       = $_POST['oldnum']; //get original order number so we know if it has been changed
$itemKey      = $_GET["key"];
$sizeKey      = $_GET["sizekey"];
$upsell       = $_POST['chkupsell'];

//variables for size upselling options
$upsellsizes       = $_POST['chkupsellsize'];
$upsell_cost       = $_POST['upgrade_cost'];
$upsell_discount   = $_POST['upgrade_discount'];
$upsell_nodiscount = $_POST['chk_nodiscount'];

$upsellcat   = $_GET["upsellcat"];
$editfixings = $_GET["editfixings"];

//function to build seo-friendly url link
setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $replace = array(), $delimiter = '-') {
    if (!empty($replace)) {
        $str = str_replace((array) $replace, ' ', $str);
    }
    
    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    $clean = strtolower(trim($clean, '-'));
    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
    
    return $clean;
}


//set catfilter based on selected category key
if (!empty($_POST["catfilter"])) {
    $catfilter = $_POST["catfilter"];
} elseif (!empty($_GET["catkey"])) {
    $catfilter = $_GET["catkey"];
}

if ($action == "delimage") {
    $query1 = "update products set imagePath = Null where itemKey =" . $itemKey;
    mysql_query($query1);
    echo "<font color='red'>Image was deleted.</font>";
    $action = "edit"; //change action flag to edit so changed record will be displayed again
}

if ($action == "upload") {
    include('prod-img.php');
    $action = "edit"; //change action flag to edit so changed record will be displayed again
    echo "<font color='red'>Image was uploaded.</font>";
}

if (!empty($move)) { //menu item being moved up or down
    unset($previouskey);
    unset($nextkey);
    $query = "SELECT orderNum from products WHERE itemKey =" . $itemKey; //get current ordernumber for item being moved
    $rt    = mysql_query($query);
    while ($nt = mysql_fetch_array($rt)) {
        $ordernumber = $nt[orderNum];
    }
    mysql_close;
    
    $query = "SELECT * from products WHERE categoryKey =" . $catfilter . " order by orderNum";
    $rt    = mysql_query($query);
    while ($nt = mysql_fetch_array($rt)) {
        //echo 'itemkey: ' .$nt[itemKey] . ' - ord#: ' . $nt[orderNum]. '<br>';
        if ($nt[orderNum] < $ordernumber) { //if current record is not record selected to be moved, save itemkey as previous record
            $previouskey = $nt[itemKey];
            $previousnum = $nt[orderNum];
            //echo 'checkpoint 1<br>';
            //echo 'previouskey ' . $nt[itemKey] . '<br>';
            //echo 'previous #' . $nt[orderNum] . '<br>';
        }
        if ($nt[orderNum] > $ordernumber) { //if
            $nextkey = $nt[itemKey];
            $nextnum = $nt[orderNum];
            //echo 'checkpoint 2<br>';
            break; //go to end of loop, stop looking thru records
        }
    } //end of loop to check through item numbers
    
    if ($move == "dn") {
        //echo 'checkpoint 3<br>';
        if (!empty($nextkey)) {
            //echo 'checkpoint 4<br>';
            $query = "Update products set orderNum =" . $nextnum . " where itemKey = " . $itemKey;
            mysql_query($query);
            //echo $query . '<br>';
            $query = "Update products set orderNum =" . $ordernumber . " where itemKey = " . $nextkey;
            mysql_query($query);
            //echo $query . '<br>';
        }
    }
    if ($move == "up") {
        if (!empty($previouskey)) {
            $query = "Update products set orderNum =" . $previousnum . " where itemKey = " . $itemKey;
            mysql_query($query);
            //echo $query . '<br>';
            $query = "Update products set orderNum =" . $ordernumber . " where itemKey = " . $previouskey;
            mysql_query($query);
            //echo $query . '<br>';
        }
    }
    
}
//echo 'item key = ' . $itemKey; //(for testing)
//require_once ('config.inc');
if (!empty($choicekey)) { //if choice item key is populated, insert choice item into option table, or delete selected item
    if ($deleteoption == "del") {
        $query = "Delete from options where optionkey = " . $choicekey;
        if (!mysql_query($query)) {
            echo $query;
            die('Error: ' . mysql_error());
        }
    } else {
        //check for duplicate first
        $update = "Select * from options where choice = " . $editchoice . " AND parentkey = " . $itemKey . " AND itemkey = " . $choicekey;
        $rt     = mysql_query($update); // query executed
        echo mysql_error();
        if (mysql_num_rows($rt) == 0) {
            
            
            $query = "insert into options (choice, parentkey, itemkey, price) values (" . $editchoice . ", " . $itemKey . ", " . $choicekey . ", ";
            $q2    = "Select itemPrice from products where itemKey = " . $choicekey;
            $rt    = mysql_query($q2); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            while ($nt = mysql_fetch_array($rt)) {
                $itemprice = $nt[itemPrice];
            }
            if (empty($itemprice)) {
                $itemprice = 0;
            }
            $query .= "'" . $itemprice . "')";
            if (!mysql_query($query)) {
                echo $query;
                die('Error: ' . mysql_error());
            }
            
        } else {
            //record already exists - do nothing?
        }
    }
}

if (!empty($fixingkey)) { //if fixings item key is populated, insert fixings item into fixings table, or delete selected item
    if ($deleteoption == "del") {
        $query = "Delete from fixings where fixingkey = " . $fixingkey;
        if (!mysql_query($query)) {
            echo $query;
            die('Error: ' . mysql_error());
        }
    } else {
        //check for duplicate first
        $update = "Select * from fixings where parentkey = " . $itemKey . " AND itemkey = " . $fixingkey;
        $rt     = mysql_query($update); // query executed
        echo mysql_error();
        if (mysql_num_rows($rt) == 0) {
            
            
            $query = "insert into fixings (parentkey, itemkey, price) values (" . $itemKey . ", " . $fixingkey . ", ";
            $q2    = "Select itemPrice from products where itemKey = " . $fixingkey;
            $rt    = mysql_query($q2); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            while ($nt = mysql_fetch_array($rt)) {
                $itemprice = $nt[itemPrice];
            }
            $query .= "'" . $itemprice . "')";
            if (!mysql_query($query)) {
                echo $query;
                die('Error: ' . mysql_error());
            }
            
        } else {
            //record already exists - do nothing?
        }
    }
}
if ($action2 == "unblocksize") {
    $record = $_GET['record'];
    $delete = "delete from crust_bad_size where recordkey = '$record'";
    mysql_query($delete);
    
    $action = "edit"; //change action flag to edit so changed record will be displayed again
}
if ($action2 == "blocksize") {
    $record = $_GET['record'];
    $insert = "insert into crust_bad_size (itemkey, sizekey) values ('$_GET[key]', '$_GET[sizekey]')";
    mysql_query($insert);
    
    $action = "edit"; //change action flag to edit so changed record will be displayed again
}
if (($action == "addsize") && ($_POST['newsize'] !== "")) {
    $newsize = $_POST['newsize'];
    //echo $newsize . '<br>';
    
    $query = "Insert into itemSize (size, itemKey) Values ('" . $newsize . "', '" . $itemKey . "')";
    if (!mysql_query($query)) {
        echo $query;
        die('Error: ' . mysql_error());
    } else {
        //echo $query .'<br>';    //for testing 
        echo "<div align=center><font color=red>Size added successfully.</font></div>";
        $action = "edit"; //reset so edit item view will be shown again after update
    }
}
if ($action == "copysize") {
    //remove existing sizes
    $query = "Delete from itemSize where itemKey = '" . $itemKey . "'";
    //echo $query."<br>";
    mysql_query($query); // query executed
    echo mysql_error(); //display any error
    //copy sizes from passed in item
    $squery = "Select * from itemSize where itemKey='" . $_POST["copyfrom"] . "'";
    //echo $squery."<br>";
    $srt6   = mysql_query($squery); // query executed
    while ($snt6 = mysql_fetch_array($srt6)) {
        $query = "insert into itemSize (itemKey, size, price) values ('" . $itemKey . "', '" . $snt6["size"] . "', '" . $snt6["price"] . "')";
        mysql_query($query); // query executed
        //echo $query."<br>";
        
    }
    mysql_close;
    
    $action = "edit"; //change action flag to edit so changed record will be displayed again
    echo "<div align=center><font color=red>Size table updated successfully.</font></div>";
}
if ($action == "delsize") {
    $query = "Delete from itemSize where recordKey = '" . $sizeKey . "'";
    mysql_query($query); // query executed
    echo mysql_error(); //display any error
    
    $action = "edit"; //change action flag to edit so changed record will be displayed again
    echo "<div align=center><font color=red>Size table updated successfully.</font></div>";
}
if ($action == "sizeupd") {
    
    //this item selected for upsell, clear other in this category
    $upsellqry = "Update itemSize set upsell='0' WHERE itemKey = '" . $_GET["key"] . "'";
    mysql_query($upsellqry); // query executed 
    echo mysql_error(); //display any error
    
    $query = "Update itemSize Set size = '" . $_POST['size'] . "', price = '" . $_POST['sizeprice'] . "'";
    
    if (empty($upsell)) {
        $query = $query . ", upsell='0'";
    } else {
        $query = $query . ", upsell='1'";
    }
    
    
    $query = $query . " Where recordKey = '" . $sizeKey . "'";
    
    
    
    
    
    if (!mysql_query($query)) {
        echo $query;
        die('Error: ' . mysql_error());
    } else {
        //echo $query .'<br>';    //for testing
        echo "<div align=center><font color=red>Size table updated successfully.</font></div>";
        
    }
    
    $action = "edit"; //change action flag to edit so changed record will be displayed again
}
if (($action == "add") && ($_POST['newitem'] !== "")) {
    //get highest ordernum before adding new record - will increase by one and assign to new Item
    $query = "Select max(orderNum) as maxnum from products";
    $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)) {
        $highnum = ($nt[maxnum] + 1);
        
    }
    $dirty     = $_POST['newitem'];
    $permalink = toAscii($dirty);
    
    if ($catfilter != "") { //if filtered by category, add category to new item being added
        $query = "Insert into products (ItemName, orderNum, categoryKey, permalink) Values ('" . $_POST['newitem'] . "', '$highnum', '$catfilter', '$permalink')";
    } else {
        $query = "Insert into products (ItemName, orderNum, permalink) Values ('" . $_POST['newitem'] . "', '$highnum', '$permalink')";
    }
    if (!mysql_query($query)) {
        echo $query;
        die('Error: ' . mysql_error());
    }
    $itemKey = mysql_insert_id();

    //item has been added - now change to edit mode and bring up new item to add details
    $query = "Select * from products where itemKey ='" . $itemKey . "'";
    $rt    = mysql_query($query);
    $nt = mysql_fetch_assoc($rt);

    $action  = "edit";
    mysql_close;
}

if ($action == "update") {
    $checkbox = $_POST['chkdelete'];
    
    
    if (empty($checkbox) && !empty($_POST['Item'])) {
        //delete not checked, save other updated info
        
        
        if (isset($_POST["Item"])) {
            $query = "UPDATE products SET ItemName = '" . mysql_real_escape_string($_POST['Item']) . "', Active ='";
            if (empty($active)) {
                $query = $query . "0'";
            } else {
                $query = $query . "1'";
            }
            
            if (empty($multisized)) {
                $query = $query . ", multisized='0'";
            } else {
                $query = $query . ", multisized='1'";
            }
            
            if (empty($_POST["chkforsale"])) {
                $query .= ", for_sale='0'";
            } else {
                $query .= ", for_sale='1'";
            }
            
            
            if (empty($taxable)) {
                $query = $query . ", taxable='0'";
            } else {
                $query = $query . ", taxable='1'";
            }
            $query = $query . ", categorykey ='" . $_POST['category'] . "', description = '" . mysql_real_escape_string($_POST['descrip']) . "'";
            
            $query .= ", product_id = '" . $_POST['Item_id'] . "'";
            
            if (!empty($_POST['price'])) {
                $query .= ", itemPrice='" . $_POST['price'] . "'";
            } else {
                $query .= ", itemPrice=null";
            }
            
            
            $query .= " WHERE itemKey = '" . $_GET['key'] . "'";
            //echo $query  ;
            mysql_query($query) or die(mysql_error()); //execute query
            
            //confirmation message that delete worked...
            echo '<div align="center"><font color=red>Item updated successfully.</font></div>';
            $action = "edit"; //change so that edited item will be displayed again after update
            
        }
        
    } else {
        
        //delete item    
        $query = "DELETE FROM products WHERE itemKey = '" . $_GET["key"] . "'";
        mysql_query($query) or die(mysql_error()); //execute query
        //delete any other sizes set up for item
        $query = "DELETE FROM itemSize WHERE itemKey = '" . $_GET["key"] . "'";
        mysql_query($query) or die(mysql_error()); //execute query
        
        //confirmation message that delete worked...
        if (!empty($checkbox)) {
            echo "<font color=red>Item deleted successfully.</font>";
        }
    }
} //end of update query



if ($action == "edit") {
    // echo '<div align="center"><a href="editproducts.php#add"><font color="blue">Add New Item</font></a></div><br><br>';
    $query = "SELECT * from products WHERE itemKey ='" . $itemKey . "'";
    //echo $query . "<br>";
    
    $rt = mysql_query($query); // query executed 
    echo mysql_error(); // if any error is there that will be printed to the screen
    echo '<div align="left"><table border=0 width="100%">';
    while ($nt = mysql_fetch_array($rt)) {
        echo '<tr><td><form action="' . $_SERVER['PHP_SELF'] . '?a=update&key=' . $nt[itemKey] . '" method="post">
            <td valign=top>Item name: <td valign=top><input type="text" name="Item" id="Item" size="35" value="' . $nt[itemName] . '">
            <tr><td><td valign=top>Item ID: <td valign=top><input type="text" name="Item_id" id="Item_id" size="35" value="' . $nt[product_id] . '">';
        
        $result2 = mysql_query("SELECT categoryName, category_type, recordKey FROM productCategory where active=1 order by categoryName");
        if (!$result2) {
            print("There was a problem getting categories: <b>" . mysql_error());
            exit();
        }
        $counter = 0;
        
        // Create the HTML code for the label and select list
        $catSelectList .= " <tr><td><td valign=top>Category: <td valign=top><select name='category' id='productCategory'><option value='' size='10'> - select a category - </option>\n";
        while ($row = mysql_fetch_array($result2)) {
            if ($row["recordKey"] == $nt[categoryKey]) { // add selected argument if option matches
                
                $catSelectList .= "<option value='" . $row["recordKey"] . "' selected='selected'>" . $row["categoryName"] . "</option>\n";
                $selectedcat   = $row["categoryName"];
                $category_type = $row["category_type"];
                $catselection  = $row["recordKey"];
                
            } else {
                $catSelectList .= "<option value='" . $row["recordKey"] . "'>" . $row["categoryName"] . "</option>\n";
            }
            $counter++;
            if ($row["categoryName"] == "Options") {
                $selectedcatkey = $row["recordKey"];
            }
            if ($row["categoryName"] == "Fixings") {
                $fixingcatkey = $row["recordKey"];
            }
        }
        $catSelectList .= "</select>";
        
        if ($counter == 0) {
            echo "<input type=hidden name='category' value=''>";
        } else {
            echo $catSelectList;
        }
        
        $counter       = 0;
        $catSelectList = "";
        
        
        echo '<tr><td><td valign="top">Description: <td valign=top><textarea name="descrip" cols="35" rows="3">' . $nt[description] . '</textarea><tr><td><td valign=top><div align=left>';
        
        //alow multi-size option here if not a sauce or crust category
        if (($selectedcat !== "Pizza Crust") && ($selectedcat !== "Pizza Sauce")) {
            echo '<tr><td><td valign=top><div align=left>Multiple sizes: <td valign=top><input type="checkbox" name="chksizes"';
            if (!empty($nt[multisized])) {
                echo 'checked=true';
                $multisized = 1; //set variable here - to be used to show multiple size boxes below if this option is selected
            } else {
                $multisized = 0;
            }
            echo '>';
        }
        
        
        
        
        echo '<tr><td><td valign=top><div align=left>Taxable: <td valign=top><input type="checkbox" name="chktaxable"';
        if (!empty($nt[taxable])) {
            echo 'checked=true';
        }
        echo '>';
        echo '<tr><td><td valign=top><div align=left>Active: <td valign=top><input type="checkbox" name="chkactive"';
        if (!empty($nt[active])) {
            echo 'checked=true';
        }
        echo '>';
        
        
        if ($selectedcat !== "Options") {
            echo '<tr><td><td valign=top><div align=left>Upsell: <td valign=top><input type="checkbox" name="chkupsell"';
            if (!empty($nt[upsell])) {
                echo 'checked=true';
            }
            echo '>';
            echo '<font color="red"><i>&nbsp;&nbsp;(Select one upsell item per category. Upsell occurs at checkout.)</i></font>';
            if ($multisized == 1) {
                echo '<tr><td><td valign=top><div align=left>Upsell next size: <td valign=top><input type="checkbox" name="chkupsellsize"';
                if (!empty($nt[upsellSizes])) {
                    echo 'checked=true';
                }
                echo '>';
                echo '<font color="red"><i>&nbsp;&nbsp;(When item added to cart, offer upgrade to next size.)</i></font>';
            }
            if (!empty($nt[upsellSizes])) { //show options for size upsell
                echo '<br><div align=left>Size upgrade flat cost: <input type="text" size="3" name="upgrade_cost" id="upgrade_cost" value="' . $nt[upsell_cost] . '" onchange="updateDiscount()"> <img src="images/question.png" title="This will offer a flat upgrade cost from any one size to the next. Example: If you set the cost to $2.00, the Small to Medium upgrade is $2.00, the Medium to Large upgrade is $2.00, etc...">';
                echo '<br><div align=left>Size upgrade discount %: <input type="text" size="3" name="upgrade_discount" id="upgrade_discount" value="' . $nt[upsell_pct_disc] . '" onchange="updateCost()"> <img src="images/question.png" title="This will offer a discount price when upgrading from one size to the next. Example: If a Large is $5 more than a Medium, and you set the discount percent to .5 (50%), the upgrade will be offered at $2.50. *** NOTE: The discount is a multiplier and should always be entered in decimal form. 10% should be entered as .10, NOT 10.0">';
                echo '<br><div align=left>No discount: <input type="checkbox" name="chk_nodiscount"';
                if (((empty($nt[upsell_pct_disc])) && (empty($nt[upsell_cost]))) || (($nt[upsell_pct_disc] == "0.00") && ($nt[upsell_cost] == "0.00"))) {
                    echo 'checked=true';
                }
                echo ' disabled="disabled">';
            }
            echo '<tr><td><td valign=top><div align=left>Available online: <td valign=top><input type="checkbox" name="chkforsale"';
            if (!empty($nt[for_sale])) {
                echo 'checked=true';
            }
            echo '>';
        }
        if (($multisized == 1) || ($selectedcat == "Options")) {
            //do not display price here, need to add to each size offered
        } else {
            echo '<tr><td><td valign=top>Price: <td valign=top>';
            echo '<input type="text" name="price" size="10" value="' . $nt[itemPrice] . '">';
        }
        echo '<tr><td><td valign=top><div align=left>Delete:<td valign=top><input type="checkbox" name="chkdelete" value="true"><tr><td><td><td valign=top><div align=left><input id="save-button" type="submit" name="save" value="Save"></form></div><tr><td colspan=3></table>';
        echo '<br><h2>Product image:</h2><center>';
        if (!empty($nt[imagePath])) {
            
            echo '<br><img src="../custom/images/products/' . $nt[imagePath] . '?' . time() . '" width=150>
      <br><a href="' . $_SERVER['PHP_SELF'] . '?a=delimage&key=' . $nt[itemKey] . '"><font color="red">Remove image</font></a>';
        }
        echo '</center>';
?> <!--************************BEGINNING OF IMAGE UPLOAD *************************-->
        <?php
        if (isset($_REQUEST['upload_message'])) {
?>
           <div class="upload_message_<?php
            echo $_REQUEST['upload_message_type'];
?>">
            <?php
            echo htmlentities($_REQUEST['upload_message']);
?>
           </div>
        <?php
        }
        
        
        echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=upload&key=' . $nt[itemKey] . '#' . $nt[itemKey] . '" method="post" enctype="multipart/form-data" name="image_upload_form" id="image_upload_form" style="margin-bottom:0px;">
<label>Image file (JPG or PNG only), maximum 4MB:</label><br />
          <input name="image_upload_box" type="file" id="image_upload_box" size="40" />
          <input type="submit" name="submit" value="Upload image" />

     <br />
    <br />
    <input name="max_width_box" type="hidden" id="max_width_box" value="100" size="4">
      <input name="max_height_box" type="hidden" id="max_height_box" value="100" size="4">
<input name="submitted_form" type="hidden" id="submitted_form" value="image_upload_form" />
          </form>';
        
        
        //add multiple size boxes here if multisized option selected
        if ($multisized == 1) {
            $query = "SELECT recordKey, itemKey, size, price, upsell FROM itemSize WHERE itemKey ='" . $itemKey . "'";
            //echo $query . "<br>";
            echo '<hr><div align="center"><A NAME="sizes"><h2>Sizes Offered</h2></A>';
            
            echo '</div>';
            
            $rt3 = mysql_query($query); // query executed 
            echo mysql_error(); // if any error is there that will be printed to the screen
            if (mysql_num_rows($rt3) == 0) {
                echo '<br><font color="red">No sizes have been set up yet. Please use the selector below to add new sizes.</font>';
            } else {
                echo '<br><div align="center"><table border=0><tr><td><td><div align="center">Upsell<td><div align="center">Size</div><td><div align="center">Price</div><td><div align="center">Save Changes';
                while ($nt3 = mysql_fetch_array($rt3)) {
                    echo '<tr><td><form action="' . $_SERVER['PHP_SELF'] . '?a=sizeupd&key=' . $itemKey . '&sizekey=' . $nt3[recordKey] . '&upsellcat=' . $nt[categoryKey] . '#sizes" method="post"><td>
<input type="checkbox" name="chkupsell"';
                    if (!empty($nt3[upsell])) {
                        echo 'checked=true';
                        
                    }
                    echo '><td><input type="text" name="size" size=20 maxlength=20 value="' . $nt3[size] . '" readonly="readonly"> <td><input type="text" name="sizeprice" size=10 maxlength=10 value="' . $nt3[price] . '"><td><input type="submit" name="sizeupd" value="Update"><td><a href="' . $_SERVER['PHP_SELF'] . '?a=delsize&key=' . $itemKey . '&sizekey=' . $nt3[recordKey] . '#sizes"><font color="red">Remove size</font></a></form>';
                }
                echo '</table></div>';
            }
            echo '<div align="center"><form action="' . $_SERVER['PHP_SELF'] . '?a=addsize&key=' . $itemKey . '#sizes" method="post"><br>';
            //get size list
            $result2 = mysql_query("SELECT sizeName, recordKey FROM sizeMaster order by sizeName");
            if (!$result2) {
                print("There was a problem getting sizes: <b>" . mysql_error());
                exit();
            }
            $counter = 0;
            
            // Create the HTML code for the label and select list
            $sizeSelectList .= " <tr><td><td valign=top>Available sizes: <td valign=top><select name='newsize'><option value='' size='10'> - select a size - </option>\n";
            while ($row = mysql_fetch_array($result2)) {
                
                $sizeSelectList .= "<option value='" . $row["sizeName"] . "'>" . $row["sizeName"] . "</option>\n";
                
                $counter++;
            }
            $sizeSelectList .= "</select>";
            
            if ($counter == 0) {
                echo "<input type=hidden name='category' value=''>";
            } else {
                echo $sizeSelectList;
            }
            $counter        = 0;
            $sizeSelectList = "";
            
            //end of size list
            
            echo ' <input type="submit" name="save" value="Add this Size">
        </form>';
            //add option to copy pricing from similar item - (for reference: $catfilter = selected category key)
            $priceqry = "Select * from itemSize where itemKey in(select itemKey from products where categoryKey = '" . $catselection . "')";
            //echo $priceqry;
            $pqrt     = mysql_query($priceqry);
            if (mysql_num_rows($pqrt) > 0) {
                $sizesfound = 1;
            }
            mysql_close;
            if ($sizesfound == 1) {
                echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=copysize&key=' . $itemKey . '#sizes" method="post">Copy sizes & pricing from: <select name="copyfrom">';
                $comps = "select itemName, itemKey from products where categoryKey='" . $catselection . "'";
                $crt   = mysql_query($comps);
                while ($cnt = mysql_fetch_array($crt)) {
                    echo "<option value='" . $cnt[itemKey] . "'>" . $cnt[itemName] . "</option>";
                }
                mysql_close;
                
                echo '</select>';
                echo '<input type="submit" value="Apply"></form>';
            }
            echo '</div><hr><br>';
        }
        
    }
    if (($selectedcat !== "Fixings") && ($selectedcat !== "Options") && ($selectedcat !== "Pizza Toppings") && ($selectedcat !== "Pizza Crust") && ($selectedcat !== "Pizza Sauce")) {
        //add section for user choices:
        echo '<a name="choices"><div align="center"><h2>Choices Offered</h2></div></a>';
        //show any existing choice lists here, split into 3 columns
        echo '<table width=100%>';
        echo '<td width="33%" valign="top"><div align="center"><u>Choice list 1</u></div>';
        $query = "Select * from options where parentkey = " . $itemKey . " AND choice = 1";
        $rt5   = mysql_query($query); // query executed
        echo mysql_error(); // if any error is there that will be printed to the screen
        
        while ($nt5 = mysql_fetch_array($rt5)) {
            $itemqry = "Select itemName from products where itemKey = " . $nt5[itemkey] . " AND active = 1";
            $rt7     = mysql_query($itemqry); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            
            while ($nt7 = mysql_fetch_array($rt7)) {
                echo '<br>' . $nt7[itemName] . ' <a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=1&ckey=' . $nt5[optionkey] . '&del=del&1=1#choices" title="remove"><font color="red"> (-)</font></a>';
            }
            mysql_close;
            
        }
        if ($editchoice == 1) {
            $query = "Select itemName, itemPrice, itemKey from products where categoryKey =" . $selectedcatkey . " AND active = 1";
            $rt6   = mysql_query($query); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            echo '<br><br><div align="center"><u>Add to list 1:</u></div>';
            while ($nt6 = mysql_fetch_array($rt6)) {
                echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=1&ckey=' . $nt6[itemKey] . '&1=1#choices"><font color="blue">' . $nt6[itemName] . '</font></a><br>';
            }
        } else { //add link to add more choices
            echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=1&1=1#choices"><div align="center"><font color="blue">Add choices</font></div></a>';
        }
        echo '<td width="33%" valign="top"><div align="center"><u>Choice list 2</u></div>';
        $query = "Select * from options where parentkey = " . $itemKey . " AND choice = 2";
        $rt5   = mysql_query($query); // query executed
        echo mysql_error(); // if any error is there that will be printed to the screen
        while ($nt5 = mysql_fetch_array($rt5)) {
            $itemqry = "Select itemName from products where itemKey = " . $nt5[itemkey] . " AND active = 1";
            $rt7     = mysql_query($itemqry); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            
            while ($nt7 = mysql_fetch_array($rt7)) {
                echo '<br>' . $nt7[itemName] . ' <a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=2&ckey=' . $nt5[optionkey] . '&del=del&1=1#choices" title="remove"><font color="red"> (-)</font></a>';
            }
            mysql_close;
            
        }
        if ($editchoice == 2) {
            $query = "Select itemName, itemPrice, itemKey from products where categoryKey =" . $selectedcatkey . " AND active = 1";
            $rt6   = mysql_query($query); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            echo '<br><br><div align="center"><u>Add to list 2:</u></div>';
            while ($nt6 = mysql_fetch_array($rt6)) {
                echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=2&ckey=' . $nt6[itemKey] . '&1=1#choices"><font color="blue">' . $nt6[itemName] . '</font></a><br>';
            }
        } else { //add link to add more choices
            echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=2&1=1#choices"><div align="center"><font color="blue">Add choices</font></div></a>';
        }
        echo '<td width="33%" valign="top"><div align="center"><u>Choice list 3</u></div>';
        $query = "Select * from options where parentkey = " . $itemKey . " AND choice = 3";
        $rt5   = mysql_query($query); // query executed
        echo mysql_error(); // if any error is there that will be printed to the screen
        while ($nt5 = mysql_fetch_array($rt5)) {
            $itemqry = "Select itemName from products where itemKey = " . $nt5[itemkey] . " AND active = 1";
            $rt7     = mysql_query($itemqry); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            
            while ($nt7 = mysql_fetch_array($rt7)) {
                echo '<br>' . $nt7[itemName] . ' <a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=3&ckey=' . $nt5[optionkey] . '&del=del&1=1#choices" title="remove"><font color="red"> (-)</font></a>';
            }
            mysql_close;
            
        }
        if ($editchoice == 3) {
            $query = "Select itemName, itemPrice, itemKey from products where categoryKey =" . $selectedcatkey . " AND active = 1";
            $rt6   = mysql_query($query); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            echo '<br><br><div align="center"><u>Add to list 3:</u></div>';
            while ($nt6 = mysql_fetch_array($rt6)) {
                echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=3&ckey=' . $nt6[itemKey] . '&1=1#choices"><font color="blue">' . $nt6[itemName] . '</font></a><br>';
            }
        } else { //add link to add more choices
            echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editchoice=3&1=1#choices"><div align="center"><font color="blue">Add choices</font></div></a>';
        }
        echo '</table><br><hr>';
    } //end of options section
    
    //add section for fixings:
    if ($fixings == 1) {
        echo '<a name="fixings"><div align="center"><h2>Fixings Offered</h2></div></a>';
        //display current fixings allowed
        echo '<table width=100% border=0><tr><td width=33%><td width=33%><td width=33%><tr>';
        $query = "Select * from fixings where parentkey = " . $itemKey;
        $rt5   = mysql_query($query); // query executed
        echo mysql_error(); // if any error is there that will be printed to the screen
        $x = 0;
        while ($nt5 = mysql_fetch_array($rt5)) {
            $itemqry = "Select itemName from products where itemKey = " . $nt5[itemkey] . " AND active = 1";
            $rt7     = mysql_query($itemqry); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            
            while ($nt7 = mysql_fetch_array($rt7)) {
                echo '<td valign="top"><div align="left">' . $nt7[itemName] . ' <a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editfixings=1&fkey=' . $nt5[fixingkey] . '&del=del&1=1#fixings" title="remove"><font color="red"> (-)</font></a></div>';
                
                //echo 'x=' . $x;
                if ($x == 2) {
                    echo '<tr>';
                    $x = 0;
                }
                $x = $x + 1;
            }
            mysql_close;
            
        }
        echo '</table>';
        //display section add more toppings available for this menu item
        
        if ($editfixings == 1) {
            $query = "Select itemName, itemPrice, itemKey from products where categoryKey =" . $fixingcatkey . " AND active = 1";
            $rt6   = mysql_query($query); // query executed
            echo mysql_error(); // if any error is there that will be printed to the screen
            echo '<br><br><div align="center"><u>Add to toppings available:</u></div>';
            echo '<table width=100% border=0><tr><td width=33%><td width=33%><td width=33%><tr>';
            $x = 0;
            while ($nt6 = mysql_fetch_array($rt6)) {
                echo '<td><a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editfixings=1&fkey=' . $nt6[itemKey] . '&1=1#fixings"><font color="blue">' . $nt6[itemName] . '</font></a><br>';
                if ($x == 2) {
                    echo '<tr>';
                    $x = 0;
                }
                $x = $x + 1;
            }
        } else { //add link to add more choices
            echo '<a href="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $itemKey . '&editfixings=1&1=1#fixings"><div align="center"><font color="blue">Add Fixings</font></div></a>';
        }
        echo '</table><hr>';
    }
} else { //$action is NOT = "edit"

    echo '<div id="single-admin-button">
    <ul>
    <a href="index.php"><li>BACK TO HOME ADMIN</li></a>
    <a href="#add"><li>ADD NEW ITEM</li></a>
    </ul>
    </div>';

    // Select all categories
    $categories = array();
    $sql = "SELECT categoryName, recordKey
            FROM productCategory
            WHERE active = 1
            ORDER BY categoryName";
    $result = mysql_query($sql) or die(mysql_error());

    while ($row = mysql_fetch_assoc($result)) {
        $row['products'] = array();
        $categories[$row['recordKey']] = $row;
    }

    // Delete products with no name
    $sql = "DELETE FROM products WHERE ItemName = ''";
    mysql_query($sql) or die(mysql_error());

    // Get all products
    $sql = "SELECT itemKey, ItemName, active, orderNum, categoryKey, itemPrice, description, taxable 
            FROM products
            ORDER BY orderNum";
    $result = mysql_query($sql) or die(mysql_error());

    while ($row = mysql_fetch_assoc($result)) {
        if (array_key_exists($row['categoryKey'], $categories)) {
            $categories[$row['categoryKey']]['products'][] = $row;
        }
    }

    echo '<form id="form-items" action="' . $_SERVER['PHP_SELF'] . '?a=filter" method="post">';
    echo '<div class="arrowlistmenu">';
    foreach ($categories as $categoryKey => $category) {
        echo "<h3 class='menuheader expandable'>".$category['categoryName']."</h3>";    
        echo'<ul class="categoryitems">';
        echo '<li>';

        echo '<div align="left">';
        echo '<table class="" border=0 cellpadding=3 cellspacing=0>';
        echo '<tr>';
        //echo '<td width="70"><div align=left><u><b><font face="verdana, arial" size=2>Move</u></b></div></td>';
        echo '<td valign=top width="200"><div align="left"><u><b><font face="verdana, arial" size=2>Item name</u></b></div></td>';
        echo '<td valign=top width="430"><font size=2 face="verdana, arial"><div align=left><u><b>Description</u></b></div></font></td>';
        echo '<td valign=top width="40"></td>';
        echo '</tr>';
        echo '</table>';

        echo '<table class="items menu-items-header" border=0 cellpadding=3 cellspacing=0>';
        foreach ($category['products'] as $product) {
            echo '<div class="item-button-area"><tr class="item-row-background">';
            //echo '<td id="item-data-left" align="left" width="70">&nbsp;<img class="handle" src="/images/icon-drag.png" />';
            echo '<input type="hidden" name="items_order[]" value="'.$product['itemKey'].'" />';
            echo '</td>';

            echo '<td valign=center width="200"><div align="left"><font size=2 color="blue" face="verdana, arial"><span id="item-name-'.$product['itemKey'].'">' . $product['ItemName']  .'</span></font></td>';

            echo '<td valign=center width="430"><font size=2 face="verdana, arial"><span id="item-description-'.$product['itemKey'].'">' . $product['description']  .'</span></font></td>';
            echo '<td valign="top" width="40">';
            // echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=edit&key=' . $product['itemKey'] . '" method="post">';
            echo '<div align="right"><input id="save-button" style="margin-bottom:3px;margin-right:5px;" class="popup edit-item edit-item-'.$product['itemKey'].'" data-popup-id="'.$product['itemKey'].'" data-cat-key="'.$product['categoryKey'].'" type="submit" name="edit" value="Edit" /></div>';
            // echo '</form>';

            echo "
                <div class='toPopDiv' id='popup_".$product['itemKey']."'> 
                    <div class='close'></div>
                    <span class='ecs_tooltip'>Esc to close <span class='arrow'></span></span>
                    <iframe class='item-iframe' id='iframe-".$product['itemKey']."' id='".$product['itemKey']."' src=''></iframe>
                </div> <!--toPopup end-->
            ";
            echo '</td>';
            echo '</tr></div><tr class="item-row-spacer"><td colspan="4"></td></tr>';
                
        }
        echo '</table>';
        echo '<br />';
        echo '<div align="right" class="new-item-button"><a class="popup add-item" id="save-button" class="popup add-item" data-popup-id="add" data-cat-key="'.$categoryKey.'">New Item</a></div>';
        echo '</div>';

        echo '</li>';
        echo '</ul>';
    }

    // Add item popup
    echo "
        <div class='toPopDiv' id='popup_add'> 
            <div class='close'></div>
            <span class='ecs_tooltip'>Esc to close <span class='arrow'></span></span>
            <iframe class='item-iframe' id='iframe-add' src=''></iframe>
        </div> <!--toPopup end-->
    ";

    // Popup background
    echo "
            <div class='loader'></div>
            <div id='backgroundPopup'></div>
            <input id='cur-popup-id' type='hidden' value='' />";

    echo '</div>'; // end .arrowlistmenu
    echo '</form>';
    ?>
    <script type="text/javascript">
        // Return a helper with preserved width of cells
        var fixHelper = function(e, ui) {
            ui.children().each(function() {
                $(this).width($(this).width());
            });
            return ui;
        };
        $(document).ready(function() {
            // set up interval to check for session expiration
            window.setInterval(function() {
                checkForSessionExpire();
            }, 30000);

            $(".items tbody").sortable({
                helper: fixHelper,
                update: function(event, ui) {
                    updateItemsOrder();
                    resetRowSpacers();
                }
            }).disableSelection();

            $('.popup.edit-item').click(function() {
                var popupId = $(this).data('popup-id');
                $('#iframe-'+popupId).attr('src', '/cmsadmin/editproductsiframe.php?a=edit&key='+popupId);
            });

            $('.popup.add-item').click(function() {
                var popupId = $(this).data('popup-id');
                var catKey = $(this).data('cat-key');
                $('#iframe-'+popupId).attr('src', '/cmsadmin/editproductsiframe.php?a=add&catkey='+catKey);
            });

            $('#backgroundPopup, .toPopDiv .close').click(function() {
                var currentPopupId = $("#cur-popup-id").val();
                if (currentPopupId.length > 0) {
                    if (currentPopupId == 'add') {
                        location.reload();
                    } else {
                        updateItemDetails(currentPopupId);
                    }
                }
            });


            $('.item-iframe').load(function() {
                var iframeLocation = $(this).get(0).contentWindow.location.search;
                if (iframeLocation.indexOf("a=update") > -1) {
                    disablePopup();
                    updateItemDetails($(this).data('id'));
                }
            });
        });

        function updateItemsOrder() {
            $.ajax({
                type: 'POST',
                url: 'save_products_order.php',
                data: $('#form-items').serialize()
            }).done(function(response) {
                if (response != '1') {
                    alert('Error updating menu items order.');
                }
            });
        }
        function updateItemDetails(itemId) {
            $.ajax({
                type: 'GET',
                url: 'editproductsiframe.php?a=details&id='+itemId
            }).done(function(response) {
                if (response != '0') {
                    response = $.parseJSON(response);
                    if (response.hasOwnProperty('category')) {
                        var category = response.category;
                        var currentCategory = $('.edit-item-'+itemId).data('cat-key');
                        if (currentCategory != category) {
                            location.reload();
                        }
                    }
                    if (response.hasOwnProperty('name')) {
                        var name = response.name;
                        $('#item-name-'+itemId).text(name);
                    }
                    if (response.hasOwnProperty('description')) {
                        var description = response.description;
                        $('#item-description-'+itemId).text(description);
                    }
                } else {
                    location.reload();
                }
            });
        }

        function disablePopup() {
                if(popupStatus == 1) {
                    var popDivs = $(".toPopDiv");
                    
                    $.each(popDivs,function(){
                        $(this).fadeOut("normal");
                    });
                    
                    //$("#toPopup_"+idNum[0]).fadeOut("normal");  
                    $("#backgroundPopup").fadeOut("normal");
                    popupStatus = 0;  // and set value to 0
            }
        }

        function checkForSessionExpire() {
            if (popupStatus == 0) return false;

            $.ajax({
                type: 'GET',
                url: 'checkifloggedin.php'
            }).done(function(response) {
                if (response != '1') {
                    location.reload();
                    return true;
                } else {
                    return false;
                }
            });
        }

        function resetRowSpacers() {
            $('.item-row-spacer').remove();
            $('.item-row-background').after('<tr class="item-row-spacer"><td colspan="4"></td></tr>');
        }
    </script>
    <?php

    echo '<div align="center">';

    echo '
    <form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new Item';
    
    
    echo ': <a name="add"></a><br><input type="text" name="newitem" size=50><input type="hidden" name="catfilter" value="' . $catfilter . '">

        <input id="save-button" type="submit" name="save" value="Save">
        </form></div></div>';
    
    
    
} //end of 'edit' loop


// echo '<div align="center"><br><a href="index.php"><font color="blue">Back to Main Admin Page</font></a>
// <br><a href="editprodcat.php"><font color="blue">Edit Categories</font></a><br><a href="editproducts.php"><font color="blue">Edit Products</font></a></div>// </div>';




?>
<script>
function updateDiscount() {
    //alert('test');
    var elem = document.getElementById("upgrade_discount");
    elem.value = "0.00";    
};

function updateCost(){
    //alert('test2');
    var percentage = document.getElementById("upgrade_discount");
    if(percentage.value >1) {
        percentage.value = percentage.value/100;
    }
    var elem = document.getElementById("upgrade_cost");
    elem.value = "0.00";        
};
</script>
<script>$("#itemsort").sortable({
    axis: 'y',
    stop: function (event, ui) {
        var data = $(this).sortable("serialize").toString();
        var idsInOrder = $(this).sortable("toArray").toString();
        //alert(idsInOrder); //popup alert to show data for testing        
        //var elem = document.getElementById("results").value = idsInOrder;    //update results input field for testing
        $.ajax({
            data: data,
            type: 'POST',
            url: 'save_item_order.php'
        });
    }
});
</script>