<?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;
}
if (isset($_GET["parent"]) and $_GET["parent"] != "") {
    $parent = $_GET["parent"];
} else if (isset($_POST["parent"]) and $_POST["parent"] != "") {
    $parent = $_POST["parent"];
}

if (intval($parent) == 0) {
    $cancellink = "catalog.php?catid=0";
} else {
    $cancellink = "catalog.php?catid=$parent";
}
$txtCategoryName = $_POST["txtCategoryName"];
if ($_POST["btnAddNewCategory"] == ADD_CATEGORY && !isNotNull($txtSearchcat)) {
    $message = "";


    //Avatar Start
    $timeNow = time();
    $avatarError = '';
    $catfilename = '';
    $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 for upload<br />";
            }

            //check if the file size is above the allowed limit
            if ($userfile_size > ($max_file * 1048576)) {
                $avatarError = "Images must be under " . $max_file . "MB in size";
            }
        } else {
            $avatarError = SELECT_IMG;
        }
        //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;
                $sttaus = 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 (!isset($catid) || $catid == "") {//at the top level
        $parentcatid = "0";
    } else {
        $parentcatid = $catid;
    }
    if (!isNotNull($txtCategoryName)) {
        $message .= CAT_NAME_REQD . "<br>";
    } else if (categoryExists($txtCategoryName, $catid)) {
        $message .= CAT_EXIST;
    }
    if ($message != "") { // error
        $message = "<br>" . MSG_CORRECT_THE_ERRORS . "<br>" . $message;
    } else { // no error so insert category details
            //Generate Alias name for product
            $aliasname = Utils::generateAlias($tableprefix . "categories", $txtCategoryName);
        if ($parentcatid == "0") {//top level category  
            
            $sqlinsertcat = "INSERT INTO " . $tableprefix . "categories(category_name,parent_id,route,avatar,alias)
							   					 VALUES ('" . addslashes($txtCategoryName) . "', '" . addslashes($parentcatid) . "','0','" . addslashes($catfilename) . "','" . addslashes($aliasname) . "') ";
            $resultinsertcat = mysql_query($sqlinsertcat);
            $route_pr = mysql_insert_id();
            $category_id = $route_pr;
            $catOptArr = $_POST['category_options'];


            

            if (count($catOptArr)) {
                foreach ($catOptArr as $opt) {
                    $sqlinsertcat = "INSERT INTO " . $tableprefix . "category_options(category_id,option_id)
														 VALUES ('" . addslashes($category_id) . "', '" . addslashes($opt) . "') ";
                    mysql_query($sqlinsertcat);
                }
            }

            $sqlupdaterouteparent = "UPDATE " . $tableprefix . "categories SET route= '" . $route_pr . "' WHERE category_id = '" . $route_pr . "'";
            $resultupdatecat_parent = mysql_query($sqlupdaterouteparent);
            $message.=CAT_ADDED_SUCC;
            header('Location:' . $cancellink . '&message=' . $message);
        } else {
            $sqlcatdetails = "SELECT route,count,parent_id  FROM " . $tableprefix . "categories  
												  WHERE category_id = '$parentcatid' ";

            //echo "<br>".$sqlcatdetails;
            $resultcatdetails = mysql_query($sqlcatdetails);
            $rowcatdetails = mysql_fetch_array($resultcatdetails);
            $route = $rowcatdetails["route"];

            $exp = explode(",", $route);

            if ($route == "0") {
                $route = $parentcatid;
            }
            $qry = "SELECT product_category FROM " . $tableprefix . "products WHERE product_category in($route)";

            $qryexc = mysql_query($qry);
            if (mysql_num_rows($qryexc) == 0) {                
                
                $sqlinsertcat = "INSERT INTO " . $tableprefix . "categories(category_name,parent_id,route,avatar,alias)
										  				   VALUES ('" . addslashes($txtCategoryName) . "', '" . addslashes($parentcatid) . "','" . $route . "','" . addslashes($catfilename) ."','" . addslashes($aliasname) . "') ";
                $resultinsertcat = mysql_query($sqlinsertcat);
                $sqlcatid = mysql_insert_id();

                $category_id = $sqlcatid;
                $catOptArr = $_POST['category_options'];

                if (count($catOptArr)) {
                    foreach ($catOptArr as $opt) {
                        $sqlinsertcat = "INSERT INTO " . $tableprefix . "category_options(category_id,option_id)
																	 VALUES ('" . addslashes($category_id) . "', '" . addslashes($opt) . "') ";
                        mysql_query($sqlinsertcat);
                    }
                }

                if ($route != "") {
                    $route .= "," . $sqlcatid;
                    $sqlupdatecat = "UPDATE " . $tableprefix . "categories SET route= '" . $route . "' WHERE category_id = '" . $sqlcatid . "'";
                    $resultupdatecat = mysql_query($sqlupdatecat);
                }
                $message.=CAT_ADDED_SUCC;
                header('Location:' . $cancellink . '&message=' . $message);
            } else {
                $message = "<br>" . MSG_CORRECT_THE_ERRORS . "<br>" . MSG_CAT_DISABLED;
            }
        }
    }
}
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 ADD_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 htmlentities($txtCategoryName); ?>" name="txtCategoryName" size="30" maxlength="50"></td></tr>
                            <tr>
                                <td colspan="2"></td>
                                <td align="left">
                                    <?php
                                    $queryOptions = "SELECT * FROM " . $tableprefix . "options";
                                    $queryOptionsR = mysql_query($queryOptions);
                                    if (mysql_num_rows($queryOptionsR)) {
                                        while ($optionsObj = mysql_fetch_object($queryOptionsR)) {
                                            $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;(191px X 183px)</td>
                                <td >&nbsp;</td>
                                <td><input type="file" name="image" id="image" /></td>

                                </td>
                            </tr>
                            <tr><td colspan="3">&nbsp;</td></tr>
                            <tr><td colspan="3" align="center"><input type="button" class="button" value="<?php echo CANCEL; ?>" name="btnCancel" onClick="window.location.href='<?php echo $cancellink; ?>';" >&nbsp;&nbsp;<input type="submit" value="<?php echo ADD_CATEGORY; ?>" class="button" name="btnAddNewCategory"></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";
        ?>