<script type="text/javascript">
function openwin(url, width, height) {
var name = "popup"; // popup name
var width = width; // popup width
var height = height; // popup height
var left = (screen.width - width) / 2 ;
var top = (screen.height - height) / 2;
var windowproperties = "width="+ width +",height="+ height +",left="+ left +",top="+ top +",scrollbars=1";
window.open(url, name, windowproperties);
}
</script>
<script src="js/image_select_dialog.js"></script>

<style type="text/css">
	.image-select-container > a {
		display: inline-block;
		margin: 5px;
		width: 120px;
		height: 90px;
		vertical-align: middle;
		text-align: left;
		position: relative;
	}
	.image-select-container > a:hover {
		outline: solid 2px orange;
		outline-offset: 2px;
	}
	.image-select-container > a img {
		max-height: 60px;
		max-width: 100px;
	}
	.image-select-container > a > div {
		position: absolute;
		bottom: 0;
		width: 120px;
	}
	.toPopDiv .popup-header-image img {
		max-width: 120px;
		max-height: 90px;
	}
</style>


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

//print_r($_POST); 

//require_once ('mysql_connect.php');
$action         = $_GET["a"];
$active         = $_POST['chkactive'];
$headerimg      = $_POST['headerimg'];
$parent_cat_num = $_POST['parent_cat_num'];

$catkey   = $_GET["catkey"];
$showdesc = $_GET["description"];
if(stristr($_SERVER['HTTP_HOST'], "pilotwebs.com")){
	$root_folder = $_SESSION['root_folder'];
} else {
	$root_folder = "";
}
//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;
}

// Change parent category

// the JOIN isn't necessary here, but could be useful in the future
$parent_cat_query  = "SELECT 
                                c.recordKey, 
                                c.categoryName, 
                                c.category_type, 
                                c.parent_cat_num, 
                                p.categoryName as parent_categoryName
                          FROM productCategory c
                          LEFT OUTER JOIN productCategory p
                               on p.recordKey = c.parent_cat_num
                          ORDER BY p.categoryName DESC
                          ";
$parent_cat_result = mysql_query($parent_cat_query);
// recordID->recordID (child->parent)
$parent_cat_map    = array();
// recordID->name
$cat_names_map     = array();
if ($parent_cat_result) {
    while ($myarr = mysql_fetch_array($parent_cat_result)) {
        $parent_cat_map[$myarr[recordKey]] = $myarr[parent_cat_num];
        $cat_names_map[$myarr[recordKey]]  = $myarr[categoryName];
    }
}
// validate whether $child_id can logically have $parent_id as
// it's new parent_cat.
function is_valid_parent($child_id, $parent_id, $parent_cat_map) {
    if ($child_id == "0") {
        // root category can't be re-parented.
        return false;
    }
    if ($child_id == $parent_id) {
        // a category cannot be its own parent.
        return false;
    }
    if ($parent_id == "0") {
        // root category can always accept a new child.
        return true;
    }
    if (!array_key_exists($parent_id, $parent_cat_map)) {
        // parent doesn't appear to exist. (note that the root category isn't in this array, so we test
        // for $parent_id == "0" above)
        return false;
    }
    // Check that $parent_id is not a descendant of $child_id.
    $tmp_id = $parent_id;
    while ($tmp_id && $tmp_id != "0") {
        if ($tmp_id == $child_id) {
            return false;
        }
        $tmp_id = $parent_cat_map[$tmp_id];
    }
    // No conflict found.
    return true;
}

// Returns map of categoryKey=>[ images ]
function get_all_product_images() {
    $result = mysql_query("select categoryKey, imagePath, thumbnail_path 
    					   from products  where imagePath <> '' and thumbnail_path <> ''");
    $images_by_category = array();
    if ($result) {
        while ($arr = mysql_fetch_array($result, MYSQL_ASSOC)) {
            if (!array_key_exists($arr[categoryKey], $images_by_category)) {
                $images_by_category[$arr[categoryKey]] = array();
            }
            $imagedata = array(
                "normal" => $arr[imagePath],
                "thumb" => $arr[thumbnail_path]
            );
            array_push($images_by_category[$arr[categoryKey]], $imagedata);
        }
    }
    return $images_by_category;
}

function get_category_images($num, $parent_cat_map) {
	$images = array();
	$cat_images = get_all_product_images();
	
	foreach ($parent_cat_map as $id => $pid) {
		if ($pid != $num) {
			continue;
		}
		// found a sub category... 
		if (array_key_exists($id, $cat_images)) {
			// ...with images
			$images = array_merge($images, $cat_images[$id]);
		}
	}
	return $images;
}

// return a string like "Apparel: Summer Apparel: T-Shirts"
function get_category_text($num, $parent_cat_map, $cat_names_map) {
    if ($num == "0")
        return "";
    if (!array_key_exists($num, $cat_names_map)) {
        return "";
    }
    // start with the name
    $str = $cat_names_map[$num];
    if (array_key_exists($num, $parent_cat_map)) {
        // prepend the parent names
        $str = get_category_text($parent_cat_map[$num], $parent_cat_map, $cat_names_map) . ": " . $str;
    }
    return trim($str, ": ");
}
// end

//test for any categories with 0 as order number...to correct any ordering issues from creating records
$query = "Select * from productCategory where orderNum ='0'";
//echo $query;
$rt    = mysql_query($query); // query executed
//echo mysql_error();
while ($nt = mysql_fetch_array($rt)) {
    //get highest ordernum before adding new record - will increase by one and assign to new category
    $query2 = "Select max(orderNum) as maxnum from productCategory";
    $rt2    = mysql_query($query2); // query executed 
    //echo $query2;
    echo mysql_error(); // if any error is there that will be printed to the screen
    while ($nt2 = mysql_fetch_array($rt2)) {
        //echo "maxnum=" . $nt2[maxnum] . "<br>";
        $updqry = "Update productCategory set orderNum = '" . ($nt2[maxnum] + 1) . "' where RecordKey = " . $nt[RecordKey];
        //echo $updqry;
        mysql_query($updqry);
    }
    mysql_close;
}
mysql_close;



//echo 'Action = ' . $action; (for testing)
if (($action == "add") && ($_POST['newcat'] !== "")) {
    //check for duplicate before adding
    $query = "Select * from productCategory where categoryName ='" . $_POST['newcat'] . "'";
    $rt    = mysql_query($query); // query executed
    echo mysql_error();
    if (mysql_num_rows($rt) == 0) { //if no existing record by this name... 
        //get highest ordernum before adding new record - will increase by one and assign to new category
        $query = "Select max(orderNum) as maxnum from productCategory";
        $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['newcat'];
        $permalink = toAscii($dirty);
        
        if (empty($parent_cat_num)) {
            $parent_cat_num = 0;
        }
        $query = "Insert into productCategory (categoryName, orderNum, parent_cat_num, permalink) Values ('" . $_POST['newcat'] . "', '" . $highnum . "', '$parent_cat_num', '$permalink')";
        
        if (!mysql_query($query)) {
            echo $query;
            die('Error: ' . mysql_error());
        } else {
            echo "<div align=center><font color=red>Category added successfully.</font></div>";
            
        }
    } else {
        echo "<div align=center><font color=red>!Error: Duplicate category not added.</font></div>";
    }
}
if ($_POST['action'] == "update") {
    $checkbox = $_POST['chkdelete'];
    
    
    if (empty($checkbox)) { //delete not checked, save other updated info
        
        
        if (isset($_POST["category"])) { //will not be set and able to update if category selected is disabled...
            $query = "UPDATE productCategory SET categoryName = '" . $_POST['category'] . "', Active ='";
            if (empty($active)) {
                $query = $query . "0'";
            } else {
                $query = $query . "1'";
            }
            //$query = $query . ", orderNum = '" . $_POST['ordernum'] . "'";
            //if(!empty($_POST['description'])) {
            $query = $query . ", description = '" . $_POST['description'] . "'";
            //}
            $query = $query . ", category_type = '" . $_POST['cattype'] . "'";
            
            if ($headerimg > "") {
                $query = $query . ", headerImg = '" . $headerimg . "'";
                
            }
            if (isset($_POST["parent_cat_num"])) {
                if (is_valid_parent($_POST['categorykey'], $_POST['parent_cat_num'], $parent_cat_map)) {
                    $query = $query . ", parent_cat_num = '" . $_POST['parent_cat_num'] . "'";
                }
            }
            if (isset($_POST["headerImg"])) {
                $query = $query . ", headerImg = '" . $_POST['headerImg'] . "'";
            }
            $query = $query . " WHERE recordKey = '" . $_POST['categorykey'] . "'";
            // echo $query."<br>";
            mysql_query($query) or die(mysql_error()); //execute query
            
            //confirmation message that update worked...
            echo "<font color=red>Category updated successfully.</font>";
            
        }
        
    } else {
        
        
        $query = "DELETE FROM productCategory WHERE recordKey = '" . $_POST['categorykey'] . "'";
        
        
        //echo "delete qry = " . $query;
        mysql_query($query) or die(mysql_error()); //execute query
        
        //confirmation message that delete worked...
        echo "<font color=red>Category deleted successfully.</font>";
        
    }
} //end of update query

$catkey = $_REQUEST['catkey'];
if (empty($catkey)) {
    $catkey = '0';
}

$query    = "SELECT recordKey, categoryName, category_type, active, orderNum, description, headerImg from productCategory where parent_cat_num ='$catkey' Order By orderNum";
$rt       = mysql_query($query);
$rowcount = mysql_num_rows($rt);

echo '<div id="single-admin-button">
<ul>
<a href="index.php"><li>BACK TO HOME ADMIN</li></a>
<a href="editproducts.php"><li>EDIT PRODUCTS</li></a>
</ul>
</div>';

echo '<form action="' . $_SERVER['PHP_SELF'] . '?a=add" method="post">Add new category: <br><input type="text" name="newcat" size=50> <input type="hidden" name="catkey" value="' . $catkey . '"> <input type="hidden" name="parent_cat_num" value="';
echo $catkey . '"><input id="save-button" type="submit" name="save" value="Save"></form>';


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

//get parent category's parent category, for up level button
$query = "SELECT parent_cat_num from productCategory  where RecordKey ='$catkey' Order By orderNum";
$rt    = mysql_query($query);
while ($nt = mysql_fetch_array($rt)) {
    $parent_cat = $nt[parent_cat_num];
}
$query = "SELECT recordKey, categoryName, category_type, active, orderNum, description, headerImg, parent_cat_num from productCategory  where parent_cat_num ='$catkey' Order By orderNum";
$rt    = mysql_query($query);
echo "<ul id='catsort'><p class='drag-header'><strong>TO CHANGE ORDER:</strong> simply drag below category to desired placement. To edit category settings click the settings icon on the right of the category link.</p>";
if ($catkey != 0) {
    echo "<a href='editprodcat.php?catkey=" . $parent_cat . "'><img src='images/up-arrow.png' title='Go up a level' alt='Go up a level'></a>";
}
if (mysql_num_rows($rt) == 0) {
    echo "<p>There are no categories to display. You can add them in the New Category box above.</p>";
}

$my_product_images = get_all_product_images();
$x                 = 1;
while ($nt = mysql_fetch_array($rt)) {
    //add dynamic css
    /*echo"<style>
    #toPopup_$x {
    font-family: 'lucida grande',tahoma,verdana,arial,sans-serif;
    background: none repeat scroll 0 0 #FFFFFF;
    border: 10px solid #ccc;
    border-radius: 3px 3px 3px 3px;
    color: #333333;
    display: none;
    font-size: 14px;
    left: 50%;
    margin-left: -402px;
    position: fixed;
    top: 20%;
    width: 400px;
    z-index: 2;
    }
    </style>";*/
    $class = 'category';
    
    
    $id = "cat-" . $nt[recordKey];
    echo '<li id="' . $id . '" name="' . $id . '" class="' . $class . '"';
    //if($nt['active'] != '1') {
    //    echo ' style="display:none;"';
    //}
    echo '><span id="catName-' . $nt['recordKey'] . '">' . $nt[categoryName] . '</span><span class="remove-icon"><a href="editproducts.php?catkey=' . $nt['recordKey'] . '"><img src="images/detail.png" alt="Edit Products" title="Edit Products"></a> <a href="editprodcat.php?catkey=' . $nt['recordKey'] . '"><img src="images/category.png" alt="Sub Categories" title="Sub Categories"></a> <a class="popup" href="#" alt="Change Category Settings" data-popup-id="' . $nt['recordKey'] . '"><img src="images/gear-icon.png" title="Category Settings"></a></li>';
    
    echo '<div id="popup_' . $nt['recordKey'] . '" class="toPopDiv catSettings">
        <div class="close"></div>
        <span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
        <div id="popup_content"> <!-- your content start -->';
    echo "<h3>Editing settings for category: " . $nt[categoryName] . "</h3>
            <form action='editprodcat.php' method='POST'>
            <input type='hidden' name='action' value='update'>
            <input type='hidden' name='categorykey' value='" . $nt['recordKey'] . "'>";
    
    echo '<br>Category name: <a name="' . $nt[categoryName] . '"></a><input id="catName_' . $nt['recordKey'] . '" type="text" name="category" size="30" value="' . $nt[categoryName] . '"';
    if (($pizza == '1') || ($nt[categoryName] == 'Options') || ($nt[categoryName] == 'Fixings')) {
        echo ' readonly=readonly';
    }
    echo '>';
    
    // Parent Category
    echo "<br />";
    echo "<label for=\"parentCat_" . $nt[recordKey] . "\">Parent Category:</label> <select id=\"parentCat_" . $nt[recordKey] . "\" class=\"select_parent_category\" name=\"parent_cat_num\">";
    echo "<option value=\"0\"";
    if ($nt[parent_cat_num] == "0") {
        echo " selected=\"1\"";
    }
    echo ">None (top level)</option>";
    foreach ($parent_cat_map as $k => $v) {
        if (!is_valid_parent($nt[recordKey], $k, $parent_cat_map)) {
            continue;
        }
        echo '<option value="' . $k . '"';
        if ($nt[parent_cat_num] == $k) {
            echo " selected=\"1\"";
        }
        echo '>';
        echo get_category_text($k, $parent_cat_map, $cat_names_map);
        echo "</option>";
    }
    echo "</select>";
    // end Parent Category
    
    // category thumbnail
    
    $current_header_image = $nt[headerImg];
?>
	<br />
	<!--
		Note: image URL format is /custom/images/products/item1.png
	-->
	<label for="headerImg_<?= $nt[recordKey] ?>">Header Image</label>
	<div class="popup-header-image">
		<?
			if ($current_header_image) {
				$thumb_image = preg_replace('/\.(jpg|png)$/', "_thumb.$1", $current_header_image);
				?><img src="../custom/images/products/<?= $thumb_image ?>" /><?
			}
		?>
	</div>
	<input type="hidden" name="headerImg" id="headerImg_<?= $nt[recordKey] ?>" value="<?= $current_header_image ?>" />
	<a href="#" class="popup-choose-header" data-categoryid="<?= $nt[recordKey] ?>">Choose Image...</a>
<?
    echo "<br>Category Description: <br>
            <textarea id='catDesc_" . $nt['recordKey'] . "' name='description' cols=60 rows=3>$nt[description]</textarea><br>
            <i><font size=2>This will show up below the category name on your menu.</font></i><br>";
    //active option
    if (($pizza == '1') || ($nt[categoryName] == 'Options') || ($nt[categoryName] == 'Fixings')) {
        //don't allow changing status here on these categories
        echo '<input id="catActive_' . $nt['recordKey'] . '" type="checkbox" name="chkactive" value="true" checked style="display:none;">';
    } else {
        echo '<br>Active: <input id="catActive_' . $nt['recordKey'] . '" type="checkbox" name="chkactive"';
        if (!empty($nt[active])) {
            echo 'checked=true';
        }
        echo '>';
    }
    
    //delete category option
    if (($pizza == '1') || ($nt[categoryName] == 'Options') || ($nt[categoryName] == 'Fixings')) {
        echo '<input id="catDelete_' . $nt['recordKey'] . '" type="checkbox" name="chkdelete" value="true" style="display:none;">';
    } else {
        echo '<br>Delete: <input id="catDelete_' . $nt['recordKey'] . '" type="checkbox" name="chkdelete" value="false">';
    }
    
    echo '<br><input type="submit" name="submit" value="Save Changes"><!--<button class="update-menu" data-cat-id="' . $nt['recordKey'] . '">Save Changes</button>-->';
    echo "</form><br>
            <br>";
    
    
    echo '</div> <!-- your content end -->
    </div> <!-- to popup end -->';
    
    $x++;
    
    //reset pizza category flag
    $pizza = 0;
}

/*echo '<input id="cur-popup-id" type="hidden" name="curCatId" value="" />';
echo '<div id="catImgPopup" class="toPopDiv catHeaderImg">
<div class="close imgPopup"></div>
<span class="ecs_tooltip">Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!-- your content start -->';
echo "Select an image below to replace this header image.<br>";
//buildImageList("../images/cat-headers/");
echo '</div> <!-- your content end -->
</div> <!-- to popup end -->';
*/
echo '<input id="cur-popup-id" type="hidden" value="" />';
echo "</ul>";

echo "</ul></div>";
//echo '</ul></div></div></table></div>';

?>
<script>$("#catsort").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_prod_cat_order.php'
        });
    }
});
</script>
