<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts Multicart                     |
// +----------------------------------------------------------------------+
// | Authors: Programmer<programmer@armia.com>        		              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems, Inc and iScripts.com (c) 2005                |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+
?>
<?php
include "../includes/config.php";
include "../includes/session.php";
include "../includes/functions.php";
include_once('../classes/cls_utils.php');
include_once('../includes/S3.php');

if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}

if (isset($_SESSION["sess_adminname"]) and $_SESSION["sess_adminname"] != "") {
    $adminname = $_SESSION["sess_adminname"];
} else {
    header("Location:login.php");
    exit;
}

if (isset($_GET["catid"]) and $_GET["catid"] != "") {
    $catid = $_GET["catid"];
} else if (isset($_POST["catid"]) and $_POST["catid"] != "") {
    $catid = $_POST["catid"];
} else {
    header("Location:catalog.php");
    exit;
}

$cdn_enabled = "N";
if(ENABLE_AMAZON_S3_IMAGES=="Y"){
    $cdn_enabled  = "Y";
}
//check whether category is a leaf category
$queryLeaf = "SELECT category_id FROM " . $tableprefix . "categories WHERE parent_id ='" . addslashes($catid) . "'";
$queryLeafR = mysql_query($queryLeaf);
$leafCat = true;
if (mysql_num_rows($queryLeafR) > 0) {
    $leafCat = false;
}

if (isset($_GET["parentcatid"]) and $_GET["parentcatid"] != "") {
    $parentcatid = $_GET["parentcatid"];
} else if (isset($_POST["parentcatid"]) and $_POST["parentcatid"] != "") {
    $parentcatid = $_POST["parentcatid"];
}

$txtCategoryName = $_POST["txtCategoryName"];

if (isset($_POST["btnSaveChanges"])) {

    //Avatar Start
    $timeNow = time();
    $catfilename = '';
    $avatarError = '';
    $max_file = 10; //MB
    $newFilePrefix = 'avatar_large' . $timeNow . '_';
    $large_image_location = '../categories/' . $newFilePrefix;
    $thumb_image_location = '../categories/avatar/avatar_' . $timeNow . '_';
// Only one of these image types should be allowed for upload.
    $allowed_image_types = array('image/pjpeg', 'image/jpeg', 'image/png', 'image/x-png', 'image/gif');
    $allowed_image_exts = array("jpg", "jpeg", "png", "gif");

    $image_ext = ""; // initialise variable, do not change this.
    foreach ($allowed_image_exts as $mime_type => $ext) {
        $image_ext.= strtoupper($ext) . " ";
    }
    if (isset($_FILES["image"]['size']) && ($_FILES["image"]['size']) > 0) {

//Get the file information
        $userfile_name = $_FILES['image']['name'];
        $userfile_tmp = $_FILES['image']['tmp_name'];
        $userfile_size = $_FILES['image']['size'];
        $userfile_type = $_FILES['image']['type'];
        $filename = basename($_FILES['image']['name']);
        $file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

        //Only process if the file is a JPG, PNG or GIF and below the allowed limit
        if ((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {

            if (!(in_array($file_ext, $allowed_image_exts) && in_array($userfile_type, $allowed_image_types))) {
                $avatarError = ONLY . $image_ext . IMAGES_ACCEPTED . "<br />";
            }

            //check if the file size is above the allowed limit
            if ($userfile_size > ($max_file * 1048576)) {
                $avatarError = IMG_UNDER . $max_file . MB_SIZE;
            }
        } else {
            $avatarError = SEL_IMG_TO_UPLOAD;
        }
        //Everything is ok, so we can upload the image.
        if (strlen($avatarError) == 0) {
            if (isset($_FILES['image']['name'])) {
                //this file could now has an unknown file extension (we hope it's one of the ones set above!)
                //$large_image_location = $large_image_location;
                //$thumb_image_location = $thumb_image_location;
                $large_image_location = $large_image_location . $filename;
                //$thumb_image_location = $thumb_image_location.$filename;

                $uploaded = move_uploaded_file($userfile_tmp, $large_image_location);
                chmod($large_image_location, 0777);

                /* list($width, $height)= getimagesize($large_image_location);
                  if($width != 191 || $height != 183 )
                  {
                  $avatarError = "Images resolution must be 191px X 183px";
                  }
                  else
                  {
                  copy($large_image_location, $thumb_image_location);
                  chmod($thumb_image_location, 0777);
                  } */



                $catfilename = $newFilePrefix . $filename;
                copy($large_image_location, '../categories/avatar/' . $catfilename);
                $imagePath  = '../categories/avatar/'.$catfilename;
                $imageName  = 'categories/avatar/'.$catfilename;
                moveImageToCDN($imagePath,$imageName);


                if (file_exists($large_image_location)) {
                    unlink($large_image_location);
                }
            }
        }
    }
    $message .= $avatarError;
//Avatar End  


    if (!isNotNull($txtCategoryName)) {
        $message .= "* Category Name cannot be empty! <br>";
    } else {
        $qry = "SELECT  category_name FROM  " . $tableprefix . "categories WHERE parent_id ='" . addslashes($parentcatid) . "' and category_name = '" . addslashes($txtCategoryName) . "' AND category_id <> '" . addslashes($catid) . "' ";
        if (mysql_num_rows(mysql_query($qry)) > 0) {
            $message .= ANOTHER_CAT_EXIST . "<br>";
        }
    }
    //check whether any product already allotted options are not removed
    $existing_allotted_options = "SELECT DISTINCT o.option_id FROM " . $tableprefix . "product_option_values pov
												   INNER JOIN " . $tableprefix . "options o ON o.option_id = pov.option_id
												   INNER JOIN " . $tableprefix . "product_options po ON po.product_option_id = pov.product_option_id
												   INNER JOIN " . $tableprefix . "products p ON p.product_id = po.product_id
												   WHERE p.product_category = '" . $catid . "'";
    $existing_allotted_options_q = mysql_query($existing_allotted_options);
    $allotted_options_arr = array();
    while ($existing_allotted_optionsObj = mysql_fetch_object($existing_allotted_options_q)) {
        $allotted_options_arr = $existing_allotted_optionsObj->option_id;
    }
    if (count($allotted_options_arr) > 0) {
        if (count($_POST['category_options'])) {
            foreach ($allotted_options_arr AS $allotted_options) {
                if (!in_array($allotted_options, $_POST['category_options'])) {
                    $message = OPTIONS_USED;
                }
            }
        } else {
            $message = OPTIONS_USED;
        }
    }
    if ($message == "") {
        
         if($_POST['product_name_old']!=$txtCategoryName){
         //Generate Alias name for product
         $aliasname = Utils::generateAlias($tableprefix . "categories", $txtCategoryName);
        } 
        
        $sql = "UPDATE  " . $tableprefix . "categories SET 
		category_name = '" . addslashes($txtCategoryName) . "',cdn_images_moved='".addslashes($cdn_enabled)."'";
        if ($catfilename != '') {
            $sql .= ",avatar = '" . addslashes($catfilename) . "'";
        }
         if($aliasname!=NULL)$sql .=",alias = '".$aliasname."'";
        $sql .= "WHERE category_id = '" . addslashes($catid) . "' ";
        $res = mysql_query($sql) or die(mysql_error());

        $catOptArr = $_POST['category_options'];
        $del_opts = "DELETE FROM " . $tableprefix . "category_options WHERE category_id = '" . $catid . "'";
        mysql_query($del_opts);
        if (count($catOptArr)) {
            foreach ($catOptArr as $opt) {
                $sqlinsertcat = "INSERT INTO " . $tableprefix . "category_options(category_id,option_id)
								 VALUES ('" . addslashes($catid) . "', '" . addslashes($opt) . "') ";
                mysql_query($sqlinsertcat);
            }
        }
        $update_message = CAT_UPDATED;

        header("Location:catalog.php?catid=$parentcatid&message=$update_message");
        exit;
    } else {
        $message = "<br>" . MSG_CORRECT_THE_ERRORS . "<br>" . $message;
    }
} else if ($_POST["btnDelete"] == DELETE) {
    if (categoryHasChildren($catid)) {
        $message .= CAT_IN_USE . "<br>";
    }

    if (categoryHasProducts($catid)) {
        $message .= DELETE_CATEGORY . "<br>";
    }

    if ($message == "") {
        $sql = "DELETE FROM  " . $tableprefix . "categories 
		WHERE 	category_id = '" . addslashes($catid) . "'
		";
        $res = mysql_query($sql);
        if (intval($parentcatid) == 0) {
            header("Location:catalog.php");
            exit;
        } else {
            header("Location:catalog.php?catid=$parentcatid");
            exit;
        }
    } else {
        $message = "<br>" . MSG_CORRECT_THE_ERRORS . "<br>" . $message;
    }
}

$avatarImage = '../categories/avatar/noimage.jpg';

$sql4 = " SELECT * FROM " . $tableprefix . "categories WHERE category_id = '" . addslashes($catid) . "' ";
$res = mysql_query($sql4);
if (mysql_num_rows($res) != 0) {
    $rw = mysql_fetch_array($res);
    $txtCategoryName = $rw["category_name"];
    $parentcatid = $rw["parent_id"];
    if (is_file('../categories/avatar/' . $rw["avatar"]) && file_exists('../categories/avatar/' . $rw["avatar"])) {
        $avatarImage = '../categories/avatar/' . $rw["avatar"];
    }
}
if (intval($parentcatid) == 0) {
    $cancellink = "catalog.php";
} else {
    $cancellink = "catalog.php?catid=$parentcatid";
}

include "../includes/htmltop.php";
?>
<SCRIPT>
    function confirmDelete(){
        if(confirm("<?php echo ARE_YOU_SURE_DELETE_RECORD; ?>") ){
            return true;
        }
        return false;
    }
</SCRIPT>

<body>
<center>

    <div align="left" id="layout">




        <!--header area start -->
        <?php
        include_once("../includes/topheader_admin.php")
        ?>

        <!--header area end -->




        <div align="left" class="main_body">
            <!--main body start -->



            <?php
            include_once("../includes/admintopmenu.php")
            ?>
            <form name="frmCategory" action="<?php echo $_SERVER["PHP_SELF"] ?>" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="catid" value="<?php echo htmlentities($catid); ?>">
                <input type="hidden" name="parentcatid" value="<?php echo htmlentities($parentcatid); ?>">

                <div align="left" class="content_area">
                    <!--content area start -->




                    <div align="left" class="page_title"><?php echo EDIT_CATEGORY; ?></div>
                    <div align="center" class="text_information grey_tr"><?php echo $message ?></div>
                    <br>

                    <div align="left">

                        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="manage_table">
                            <tr>
                                <td colspan="3" align="right"><span class="required">*</span><?php echo MANDATORY_FIELDS; ?></td>
                            </tr>
                            <tr><td colspan="3">&nbsp;</td></tr>
                            <tr><td width="39%" align="right" ><?php echo CATEGORY_NAME; ?>&nbsp;<span class="required">*</span></td>
                                <td width="3%" >&nbsp;</td><td width="58%" align="left"><input type="text" class="textarea" value="<?php echo (stripslashes($txtCategoryName)); ?>" name="txtCategoryName" size="30" maxlength="50"></td></tr>
                            <tr>
                                <td colspan="2"></td>
                                <td align="left">
                                    <?php
                                    if ($leafCat === true) {
                                        $queryOptions = "SELECT * FROM " . $tableprefix . "options";
                                        $queryOptionsR = mysql_query($queryOptions);
                                        if (mysql_num_rows($queryOptionsR)) {
                                            $queryAlreadyAvailableOptions = "SELECT option_id FROM " . $tableprefix . "category_options WHERE category_id = '" . $catid . "'";
                                            $alreadyAvailableOptionsQ = mysql_query($queryAlreadyAvailableOptions);
                                            $alreadyAvailableOptionsArr = array();
                                            while ($alreadyAvailableOptionsObj = mysql_fetch_object($alreadyAvailableOptionsQ)) {
                                                $alreadyAvailableOptionsArr[] = $alreadyAvailableOptionsObj->option_id;
                                            }
                                            while ($optionsObj = mysql_fetch_object($queryOptionsR)) {
                                                $checked = "";
                                                if (in_array($optionsObj->option_id, $alreadyAvailableOptionsArr)) {
                                                    $checked = "checked";
                                                }
                                                ?>
                                                <input type="checkbox" name="category_options[]" value="<?php echo $optionsObj->option_id ?>" <?php echo $checked ?>>&nbsp;<?php echo $optionsObj->option_name; ?>
                                                <?php
                                            }
                                        }
                                        echo "<br>";
                                    }
                                    ?>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" ><?php echo IMAGE; ?>&nbsp;:&nbsp;(281px X 260px)</td>
                                <td >&nbsp;</td>
                                <td><input type="file" name="image" id="image" /></td>

                                </td>
                            </tr>
                            <tr>
                                <td align="right" >&nbsp;</td>
                                <td >&nbsp;</td>
                                <td><img src="<?php echo $avatarImage; ?>" alt="" width="150"/></td>

                                </td>
                            </tr>

                            <tr><td colspan="3">&nbsp;</td></tr>
                            <tr><td colspan="3" align="center">
                                    <input type="hidden" name="product_name_old" value="<?php echo (stripslashes($txtCategoryName)); ?>">
                                    <input type="submit" value="<?php echo BTN_SAVE_CHANGES; ?>" class="button" name="btnSaveChanges">&nbsp;&nbsp;
                                    <input class="button" type="submit" value="<?php echo DELETE; ?>" name="btnDelete" onClick="return confirmDelete();" >&nbsp;&nbsp;<input type="button" class="button" value="<?php echo CANCEL; ?>" name="btnCancel" onClick="window.location.href='<?php echo $cancellink; ?>';" ></td></tr>
                        </table>






                    </div>


                    <!--content area end-->

                </div>

            </form>

            <div align="left" class="clear_float"><img src="../images/clear.gif" alt="" width="1" height="1" /></div>
            <!--main body end -->
        </div>


        <?php
        include "../includes/footer.php";
        ?>