<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: 			*/
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004-2010 ARMIA INC                                    |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts VistaCart                     |
// +----------------------------------------------------------------------+
// | Authors: Jipson<jipson.thomas@armiasystems.com>                      |
// +----------------------------------------------------------------------+


App::import('Sanitize');
class ProductsController extends AppController {
    var $name = "Product";
    var $helpers = array('Html', 'Form','Pagination','Javascript','Ajax','Csv','xls','Tree');
    var $components = array ('Pagination','Catmenu','Pclzip'); // Added
    var $uses = array('Product', 'Category','Rating','Currency','Customfield','Customfieldvalue','Customcombination','Productcustomfield','Productdetail','Productimages','Setting','Cmspage','Cart');
    var $paginate = array('limit' => 25,'order' => array('Product.pname' => 'asc'));


function index()
    {
       
		$this->__validateLoginStatus();
                $cnfg 				=	Configure::read('Neutrino');


        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
		$admsess	=	$this->Session->read('Admin');
		if($admsess["products"] <> 1){
		 	$this->redirect(array('controller' => 'admins', 'action' => 'index'));
			exit();
		}

		global $currency;
		$curr		=	$this->Currency->findByCode($currency);

		$this->set('curlogo',$curr["Currency"]["logo"]);
		$criteria="Product.status = 'A'";
		$cmbSearchType	=	"";
		$txtSearch		=	"";

                $this->paginate["order"] = "Product.id DESC"; // Order list in descending order

		if(isset($_GET["cmbSearchType"]) && isset($_GET["txtSearch"])){
			$cmbSearchType	=	$_GET["cmbSearchType"];
			$txtSearch		=	$_GET["txtSearch"];
                        
			if($cmbSearchType == "name"){
				$data = $this->paginate('Product', array('Product.pname  LIKE ' => "%".addslashes($txtSearch)."%",'Product.status  = ' => "A"));
			}elseif($cmbSearchType == "category"){
				$data = $this->paginate('Product', array('Category.cname  LIKE ' => "%".addslashes($txtSearch)."%",'Product.status  = ' => "A"));
			}else{
				$data = $this->paginate('Product', array('Product.status  = ' => "A"));
			}
		}
		else if(isset($this->passedArgs["cmbSearchType"]) && isset($this->passedArgs["txtSearch"]) &&
		 $this->passedArgs["txtSearch"] <> '')
		{
		    $cmbSearchType	=	$this->passedArgs["cmbSearchType"];
			$txtSearch		=	$this->passedArgs["txtSearch"];
                       
			if($cmbSearchType == "name"){
				$data = $this->paginate('Product', array('Product.pname  LIKE ' => "%".addslashes($txtSearch)."%",'Product.status  = ' => "A"));
			}elseif($cmbSearchType == "category"){
				$data = $this->paginate('Product', array('Category.cname  LIKE ' => "%".addslashes($txtSearch)."%",'Product.status  = ' => "A"));
			}else{
				$data = $this->paginate('Product', array('Product.status  = ' => "A"));
			}
		}
		else{

			$data = $this->paginate('Product', array('Product.status  = ' => "A"));
		}

                //$data = $this->paginate('Product', array('Product.status  = ' => "A"));

		for($c=0; $c < sizeof($data); $c++)
		{
			if(isset($data[$c]["Productimages"][0]["imagename"]))
				{
					$defimg	=	$data[$c]["Productimages"][0]["imagename"];
					for($m=0; $m < sizeof($data[$c]["Productimages"]); $m++)
					{
						if($data[$c]["Productimages"][$m]["default_img"] == "Y")
						{
							$defimg	=	$data[$c]["Productimages"][$m]["imagename"];
						}
					}
					$data[$c]["Productimages"]	=	$defimg;
				}
				else
				{
					$data[$c]["Productimages"]	= '';
				}
		}
		$this->set('cmbSearchType', $cmbSearchType);
		$this->set('txtSearch', $txtSearch);
                $this->passedArgs['limit']=$this->paginate["limit"];
                $this->set('passedarg',$this->passedArgs);
		$this->set('product', $data);
		$this->layout = 'adm';
    }

    function getcsv() {
        $this->__validateLoginStatus();
        $admsess	=	$this->Session->read('Admin');
        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }
        $data	=	$this->Product->findAllByStatus('A');
        $this->set('data',$data);
        $this->layout	=	'csvexp';
    }


    function beforeFilter() {
        if (isset($this->Setting) && !empty($this->Setting->table)) {
            $this->Setting->load();
        }
        global $sitefolder;
        global $meta_description;
        global $meta_keywords;
        global $page_title;
        global $currency;
        $cnfg 				=	Configure::read('Neutrino');
        $currency			=	$cnfg["currency"];
        $sitefolder			=	$cnfg["sitebasefolder"];
        $meta_description	=	$cnfg["meta_description"];
        $meta_keywords		=	$cnfg["meta_keywords"];
        $page_title			=	$cnfg["page_title"];
        global $style;
        $style				=	$cnfg["style"];
        $this->set('style', $style);
        $this->set('meta_description', $meta_description);
        $this->set('meta_keywords', $meta_keywords);
        $this->pageTitle = $page_title	;
        $this->set('cnfg',$cnfg);
        $this->paginate["limit"]=$cnfg["items_perpage"]; //Setting pagination limit per page.
        $this->set('sitefolder', $sitefolder);
        $httpHost	=	$_SERVER['HTTP_HOST'];
        $this->set('sitebase','http://'.$httpHost);
        //get cart count
        $sus	=	$this->Session->read();
        if ($this->Session->check('Userlog') === true) {
            $userid = $sus["Userlog"]["id"];
            $cartCount = $this->Cart->getCartCount($userid,'user');
        }else {
            $sessid = $this->Session->id();
            $cartCount = $this->Cart->getCartCount($sessid,'G');
        }
        $this->set('cartcount',$cartCount);
        /*  $socialmedia = array(
                   'enable_facebook'=>"N",
                   'facebook_url'=>"",
                   'enable_twitter'=>"N",
                   'twitter_url'=>""
               );

               if(isset ($cnfg['enable_facebook'])){
                    $socialmedia['enable_facebook'] = $cnfg['enable_facebook'];
                    $socialmedia['facebook_url'] = $cnfg['facebook_url'];
               }
               if(isset ($cnfg['enable_twitter'])){
                    $socialmedia['enable_twitter'] = $cnfg['enable_twitter'];
                    $socialmedia['twitter_url'] = $cnfg['twitter_url'];
               }
               $this->set('socialmedia',$socialmedia);*/


    }

    function beforeRender() {
        // $lst	=	$this->Category->findAll();
        $lst	=	$this->Category->findAll(null, NULL, 'Category.cname ASC', null, null);
        if(empty($lst)===false) {
            foreach($lst as $det)
                $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"],'parent' => $det["Category"]["parent_id"]);
            $this->set('menu_array', $menu_array);
        }
        $footer_links = $this->Cmspage->find('list',array('conditions' => array('Cmspage.type' => 'content','Cmspage.status' => 'Y')));
        $this->set('footerlinks', $footer_links);

    }

    function __validateLoginStatus() {
        if($this->Session->check('Admin') == false) {
            $this->redirect(array('controller' => 'admins', 'action' => 'login'));
            $this->Session->setFlash(__('The URL you\'ve followed requires you login.'));
        }
    }


    function add() {

        $this->__validateLoginStatus();
        $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
        $admsess	=	$this->Session->read('Admin');

        $max_upload = (int)(ini_get('upload_max_filesize'));
        $max_post = (int)(ini_get('post_max_size'));
        $memory_limit = (int)(ini_get('memory_limit'));
        $upload_mb = min($max_upload, $max_post, $memory_limit);

        $this->set('max_upload', $upload_mb);

        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }

        $cat_cnt = $this->Category->find('count', array('fields' => 'COUNT(Category.id) as count','conditions' => array('Category.id !=' => 1)));
        if($cat_cnt == 0) {
            $this->Session->setFlash(__('Please add any product category.', true));
            $this->redirect(array('controller' => 'categories','action'=>'index'));
            exit();
        }


        //$xfile  = "../webroot/configxml.xml";

        global $currency;
        $curr		=	$this->Currency->findByCode($currency);
        $this->set('curlogo',$curr["Currency"]["logo"]);


        
        App::import('Xml');
        
        // your XML file's location
        $file = "configxml.xml";
        // now parse it
        
        $parsed_xml = new XML($file);
        $parsed_xml = Set::reverse($parsed_xml); // this is what i call magic
        $maxnum = $parsed_xml["Configuration"] ["pno"];
       // $maxnum = 20;

        $maxnum = (int)$maxnum ;
        $curnum	=	$this->Product->getCntPdct();
        if($curnum >= $maxnum) {
            $this->Session->setFlash(__('The Maximum Product limit exceeded', true));
            $this->redirect(array('action'=>'index'));
            exit;
        }

        if (!empty($this->data)) {
            //Setting 0.0 as prices if the whole sale or retail prices are not entered
            if(isset($this->data["Product"]["Set as Featured Item"]))
                $this->data["Product"]["featured"] = $this->data["Product"]["Set as Featured Item"];
            if(isset($this->data["Product"]["wholesale_price"]) && $this->data["Product"]["wholesale_price"] == '')
                $this->data["Product"]["wholesale_price"] = $this->data["Product"]["price"];
            if(isset($this->data["Product"]["price"]) && $this->data["Product"]["price"] == '')
                $this->data["Product"]["price"] = 0.0;
            if(isset($this->data["Product"]["discount_type"]) && $this->data["Product"]["discount_type"] == '')
                $this->data["Product"]["discount"] = 0.0;
            if(isset($this->data["Product"]["weight"]) && $this->data["Product"]["weight"] == '')
                $this->data["Product"]["weight"] = 0.0;
            $check_combn		=	$this->Category->findById($this->data["Product"]["category_id"]);
            if($check_combn["Category"]["custom_combination"]=='') {
                //Uplaoding image for digital product
                $err = false;
                if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {

                    $pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name']);
                    $error = $this->Product->handleFileUpload($this->data['Product']['pdctfile'], $pdctfile1);
                }
                

                if(empty($error)) {
                 
                   
                    if(!empty($pdctfile1))
                        $this->data['Product']['pdctfile'] = $pdctfile1;
                    else
                        unset($this->data['Product']['pdctfile']);
                }

                
               

                //Uplaoding image for digital product

                if ($this->Product->save($this->data)) {
                    $productid = $this->Product->id;
                    $this->_uploadProductImages($productid);
                }

                $this->Session->setFlash(__('The Product has been saved', true));
                $this->redirect(array('controller' => 'products','action'=>'index'));
            }

            else if($check_combn["Category"]["custom_combination"]<>'') {

                //Uploading image for digital product
                $err = false;
                if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {


                    $pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name']);
                    $error = $this->Product->handleFileUpload($this->data['Product']['pdctfile'], $pdctfile1);
                }
                if(empty($error)) {
                    if(!empty($pdctfile1))
                        $this->data['Product']['pdctfile'] = $pdctfile1;
                    else
                        unset($this->data['Product']['pdctfile']);
                }

                //Uploading image for digital product
                if ($this->Product->save($this->data)) {
                    $productid = $this->Product->id;
                    global $size_err;
                    $this->_uploadProductImages($productid);
                    #################  Function to Add product details starts here(Added by Shyam)	#################
                    if(isset($this->data['Product']['combn_cnt'])) {
                        //getting the last insert id.
                        $categoryid=$this->data['Product']['category_id'];
                        $pdctimage='';
                        $c=0;
                        foreach($this->data['Product']['combn_cnt'] as $k => $v) {
                            $c++;
                            foreach($this->data["Product"]["attributes$v"] as $attribval) {
                                if($attribval!='') $attrib_array[]=$attribval;
                            }
                            if(isset($attrib_array))   $attributes=implode(',',$attrib_array); else  $attributes='';
                            $stock=$this->data["Product"]["stock$v"];

                            if(!is_numeric($stock))
                            {
                                $stock = 0;
                            }

                            $reorderlevel=$this->data["Product"]["reorderlevel$v"];

                            if(!is_numeric($reorderlevel))
                            {
                                $reorderlevel = 0;
                            }
                            $skuno=$this->data["Product"]["skuno$v"];
                            $extraprice=$this->data["Product"]["extraprice$v"];

                             if(!is_numeric($extraprice))
                            {
                                $extraprice = 0;
                            }

                            //Uploading Image Starts here .
                            if(!empty($this->data["Product"]["pdctfile$v"]["tmp_name"])) {
                                list($width,$height,$type) = @getimagesize($this->data["Product"]["pdctfile$v"]["tmp_name"]);
                                if($width >= 25 && $height >= 25) {

                                    $pdctfile = $this->Product->generateUniqueFilename($this->data["Product"]["pdctfile$v"]["name"]);
                                    $error = $this->Product->handleFileUpload($this->data["Product"]["pdctfile$v"], $pdctfile);
                                    if(empty($error)) {
                                        if(!empty($pdctfile))
                                            $pdctimage = $pdctfile;
                                    }
                                    else
                                        $size_err.="<br />".$error;
                                }
                                else {
                                    $size_err.="<br />Please Upload Image of size greater than 25x25 pixels for product combination".$c.".";
                                }
                            }
                            //Uploading Image Ends here ..

                            $this->Product->addProductCombinations($categoryid,$productid,$attributes,$stock,$reorderlevel,$skuno,$extraprice,$pdctimage);
                            if(isset($attrib_array)) unset($attrib_array);
                            $pdctimage='';
                            $pdctfile='';
                            $error=false;
                        }
                        $this->Product->updateTotalStock($productid);
                    }

                    ################# Function to Add product details Ends here(Added by Shyam)	#################

                    if(isset($size_err) && !empty($size_err))
                        $this->Session->setFlash(__('The Product details has been saved.'.$size_err, true));
                    else
                        $this->Session->setFlash(__('The Product has been saved', true));
                    //$this->redirect(array('controller' => 'products','action'=>'edit/'.$productid.'/'.$categoryid));


                    $this->redirect(array('controller' => 'products','action'=>'index'));
                    //$this->redirect(array('controller' => 'products'));
                    exit();
                }
            }
            //newly added for category tree listing
            $ppcat = $this->Category->find('threaded', array('order' => array('Category.cname' => 'ASC')));
            $this->set('categoriesList', $ppcat);
            $this->layout = 'adm';
            $this->render();
        }
        else {
            $ppcat = $this->Category->find('threaded', array('order' => array('Category.cname' => 'ASC')));
            $this->set('categoriesList', $ppcat);
            $this->layout = 'adm';
        }
    }





    #################  Function to Add product Images starts here(Added by Shyam)	#################

    function _uploadProductImages($productid) {

        global $size_err;

        for($i=0;$i<=$this->data["Product"]["totalimg"];$i++) {

            if($i==$this->data["Product"]["defaultimg"])  $dfltimg='Y'; else  $dfltimg='N';

            $pdctimage='';

            if(!empty($this->data["Product"]["pdctimg$i"]["tmp_name"])) {

                list($width,$height,$type) = @getimagesize($this->data["Product"]["pdctimg$i"]["tmp_name"]);

                if($width >= 25 && $height >= 25) {

                    $pdctimgfile = $this->Product->generateUniqueFilename($this->data["Product"]["pdctimg$i"]["name"]);

                    $error = $this->Product->handleFileUpload($this->data["Product"]["pdctimg$i"], $pdctimgfile);

                    if(empty($error)) {

                        if(!empty($pdctimgfile))

                            $pdctimage = $pdctimgfile;

                        $this->Product->addProductImages($productid,$pdctimage,$dfltimg);

                        $pdctimgfile='';
                        $error=false;

                    }

                    else

                        $size_err.="<br />".$error;

                }

                else {

                    $size_err="<br />Please Upload Images of size greater than 25x25 pixels for product images.";

                }

            }

        }

    }

    #################  Function to Add product Images ends here(Added by Shyam)	#################



    ################# Ajax Function to show Custom fields starts here(Added by Shyam)	#################

    function showcustomfields($catid,$index) {

        $this->layout = null;

        $combinations=$this->Category->findById($catid);

        if($combinations['Category']['custom_combination']!='') {

            $combination=$combinations['Category']['custom_combination'];

            $split_combination=explode(',',$combination);

            foreach($split_combination as $combn) {

                $cparent=$this->Customfieldvalue->findById($combn);

                $cparents[$combn]=$cparent['Customfieldvalue']['customfield_id'];

            }

            $selected_cfields=array_unique(array_values($cparents));

            $selected_cvalues=array_keys($cparents);

            $sel_cids=array();
            $sel_cids=implode(',',$selected_cvalues);


            foreach($selected_cfields as $fieldid) {

                $temp_array= $this->Customfield->findById($fieldid);

                $selected_cfieldnames[]=$temp_array['Customfield']['custom_name'];

            }

            unset($temp_array);
            unset($fieldid);

            foreach($selected_cfields as $fieldid) {

                // $temp_array= $this->Customfieldvalue->find('list',array('fields'=>array('Customfieldvalue.id', 'Customfieldvalue.custom_value'),'conditions' =>'Customfieldvalue.customfield_id  IN ('.$fieldid.')'));

                $temp_array= $this->Customfieldvalue->find('list',array('fields'=>array('Customfieldvalue.id', 'Customfieldvalue.custom_value'),'conditions' =>'Customfieldvalue.customfield_id  IN ('.$fieldid.') AND Customfieldvalue.id IN ('.$sel_cids.')'));

                $selected_cfieldvalues[$fieldid]=$temp_array;

            }



            $this->set('index', $index);

            $this->set('selected_cfieldvalues', $selected_cfieldvalues);

            $this->set('selected_cfieldnames', $selected_cfieldnames);

        }

        else {

            echo '';

            exit();

        }

    }

    ################# Ajax Function to show Custom fields ends here(Added by Shyam)	#################





################# Ajax Function to show product combination image and skuno starts here(Added by Shyam)	#################

    function showcombnimage($cmbnid='',$price='',$distype='',$discnt='') {



        $this->layout = null;

        $sus	=	$this->Session->read('Userlog');

        if(isset($sus) && empty($sus)===false) {

            $this->set('sus', $sus);

        }

        global $currency;

        $curr		=	$this->Currency->findByCode($currency);

        $this->set('curlogo',$curr["Currency"]["logo"]);

        $cmbn_det=$this->Productdetail->findById($cmbnid);


        $this->set('cmbn_det', $cmbn_det);

        if(isset($cmbn_det["Productdetail"]["product_id"]) && $cmbn_det["Productdetail"]["product_id"] <> '') {

            $pid=$cmbn_det["Productdetail"]["product_id"];

            $prod_det=$this->Product->findById($pid);

            $this->set('prod_det', $prod_det);

        }

        $this->set('prod_price', $price);
        
        

        $this->set('prod_distype', $distype);

        $this->set('prod_discnt', $discnt);
        $this->set('prod_stock', $cmbn_det["Productdetail"]["stock"]);

    }

################# Ajax Function to show product combination image and skuno ends here(Added by Shyam)	#################





    function edit($id=0,$catid=0,$tab='') {

        if($id == 0) {

            $this->redirect(array('controller' => 'products','action'=>'index'));

            exit();

        }

        $this->__validateLoginStatus();
$cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
        $admsess	=	$this->Session->read('Admin');

        $max_upload = (int)(ini_get('upload_max_filesize'));
        $max_post = (int)(ini_get('post_max_size'));
        $memory_limit = (int)(ini_get('memory_limit'));
        $upload_mb = min($max_upload, $max_post, $memory_limit);

        $this->set('max_upload', $upload_mb);

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        $this->Product->id = $id;

        global $currency;

        //$this->set('tab', $tab);

        $curr		=	$this->Currency->findByCode($currency);

        $this->set('curlogo',$curr["Currency"]["logo"]);

        $this->set('catid',$catid);

        if (!empty($this->data)) {
            //Setting 0.0 as prices if the whole sale or retail prices are not entered
            if(isset($this->data["Product"]["Set as Featured Item"]))
                $this->data["Product"]["featured"] = $this->data["Product"]["Set as Featured Item"];
            if(isset($this->data["Product"]["wholesale_price"]) && $this->data["Product"]["wholesale_price"] == '')
                $this->data["Product"]["wholesale_price"] = 0.0;
            if(isset($this->data["Product"]["price"]) && $this->data["Product"]["price"] == '')
                $this->data["Product"]["price"] = 0.0;
            if(isset($this->data["Product"]["discount_type"]) && $this->data["Product"]["discount_type"] == '')
                $this->data["Product"]["discount"] = 0.0;
            if(isset($this->data["Product"]["weight"]) && $this->data["Product"]["weight"] == '')
                $this->data["Product"]["weight"] = 0.0;

            $productid=$id;
            //Code to change category of the product if a new category is selected starts here...

            if($this->data["Product"]["hidcatid"] <> $this->data["Product"]["category_id"]) {

                $new_comb_det		=	$this->Category->findById($this->data["Product"]["category_id"]);

                $old_comb_det		=	$this->Category->findById($this->data["Product"]["hidcatid"]);

                if($new_comb_det["Category"]["custom_combination"] <> $old_comb_det["Category"]["custom_combination"]) {

                    $this->Session->setFlash(__('Product Attributes doesn\'t match for the selected category.', '/products'));

                    $this->redirect(array('controller' => 'products','action'=>'index/'));

                    exit();

                }

                else {

                    $this->Product->updateCategory($productid,$this->data["Product"]["category_id"]);

                    $categoryid=$this->data["Product"]["category_id"];
                }

            }

            else {

                $categoryid=$this->data["Product"]["hidcatid"];

            }

            //Uplaoding image for digital product

            $err = false;

            if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {

                $pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name']);

                $error = $this->Product->handleFileUpload($this->data['Product']['pdctfile'], $pdctfile1);

            }

            if(empty($error)) {



                if(!empty($pdctfile1))

                    $this->data['Product']['pdctfile'] = $pdctfile1;

                else

                    unset($this->data['Product']['pdctfile']);

            }

            //Uplaoding image for digital product

            $this->Product->save($this->data);


            //Code to change category of the product if a new category is selected ends here...





            #################  Function to Add product Images starts here(Added by Shyam)	#################

            $size_err='';
            
            for($i=0;$i<=$this->data["Product"]["totalimg"];$i++) {

                if($i==$this->data["Product"]["defaultimg"])

                    $dfltimg='Y'; else  $dfltimg='N';

                $pdctimage='';

                if(!empty($this->data["Product"]["pdctimg$i"]["tmp_name"])) {

                    list($width, $height,$type) = @getimagesize($this->data["Product"]["pdctimg$i"]["tmp_name"]);

                }

                if(!empty($this->data["Product"]["pdctimg$i"]["tmp_name"]) && isset($this->data["Product"]["imageid"][$i]) ) {

                    if($width >=25 && $height >=25) {

                        $pdctimgfile = $this->Product->generateUniqueFilename($this->data["Product"]["pdctimg$i"]["name"]);

                        $error = $this->Product->handleFileUpload($this->data["Product"]["pdctimg$i"], $pdctimgfile);

                        if(empty($error)) {
                            if(!empty($pdctimgfile))   $pdctimage = $pdctimgfile;
                        } else   $size_err.="<br />".$error;

                        $this->Product->updateProductImages($productid,$pdctimage,$dfltimg,$this->data["Product"]["imageid"][$i]);

                        $pdctimgfile='';
                        $error=false;

                    }

                    else {

                        $size_err="<br />Please Upload Images of size greater than 25x25 pixels for product images.";

                    }

                }

                else  if(!empty($this->data["Product"]["pdctimg$i"]["tmp_name"]) && !isset($this->data["Product"]["imageid"][$i]) ) {

                    if($width >=25 && $height >=25) {

                        $pdctimgfile = $this->Product->generateUniqueFilename($this->data["Product"]["pdctimg$i"]["name"]);

                        $error = $this->Product->handleFileUpload($this->data["Product"]["pdctimg$i"], $pdctimgfile);

                        if(empty($error)) {
                            if(!empty($pdctimgfile))   $pdctimage = $pdctimgfile;
                        } else   $size_err.="<br />".$error;

                        $this->Product->addProductImages($productid,$pdctimage,$dfltimg);

                        $pdctimgfile='';
                        $error=false;

                    }

                    else {

                        $size_err="<br />Please Upload Images of size greater than 25x25 pixels for product images.";

                    }

                }

                else  if(empty($this->data["Product"]["pdctimg$i"]["tmp_name"]) && isset($this->data["Product"]["imageid"][$i]) ) {

                    $this->Product->updateDefaultImage($productid,$dfltimg,$this->data["Product"]["imageid"][$i]);

                }

            }

            #################  Function to Add product Images ends here(Added by Shyam)	#################



            if(isset($this->data['Product']['combn_cnt'])) {

                $pdctimage='';

                foreach($this->data['Product']['combn_cnt'] as $k => $v) {

                    $editid=explode('->',$v);

                    $indx=$editid[0];

                    foreach($this->data["Product"]["attributes$indx"] as $attribval) {

                        if($attribval!='') $attrib_array[]=$attribval;

                    }

                    if(isset($attrib_array))  $attributes=implode(',',$attrib_array); else  $attributes='';

                    $stock=$this->data["Product"]["stock$indx"];

                    $reorderlevel=$this->data["Product"]["reorderlevel$indx"];

                    $skuno=$this->data["Product"]["skuno$indx"];

                    $extraprice=$this->data["Product"]["extraprice$indx"];

                    $pdctfile=$this->data["Product"]["pdctfile$indx"];

                    if(!is_numeric($extraprice))
                    {
                        $extraprice = 0;
                    }

                    if(!is_numeric($reorderlevel))
                    {
                        $reorderlevel = 0;
                    }



                    //Uploading Image Starts here ..

                    if(!empty($this->data["Product"]["pdctfile$indx"]["tmp_name"])) {

                        list($width, $height,$type) = @getimagesize($this->data["Product"]["pdctfile$indx"]["tmp_name"]);

                    }



                    if(isset($editid[1]) && !empty($this->data["Product"]["pdctfile$indx"]["tmp_name"])) {

                        if($width >=25 && $height >=25) {

                            $pdet=$this->Productdetail->findById($editid[1]);

                            //Removing old images starts here..

                            $old_img=$pdet["Productdetail"]["pdctfile"];

                            $image	= explode(".",$old_img);

                            $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$old_img);

                            $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$image[0]."_thumb.jpg");

                            $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$image[0]."_disp.jpg");

                            $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$image[0]."_xtra.jpg");

                            //Removing old images ends here..

                            $pdctfile1 = $this->Product->generateUniqueFilename($this->data["Product"]["pdctfile$indx"]["name"]);
                            $error = $this->Product->handleFileUpload($this->data["Product"]["pdctfile$indx"], $pdctfile1);

                            if(empty($error)) {
                                if(!empty($pdctfile1))  $pdctimage1 = $pdctfile1;
                            }	else  $size_err.="<br />".$error;

                            $this->Product->updateProductCombinations($categoryid,$productid,$attributes,$stock,$reorderlevel,$skuno,$extraprice,$pdctimage1,$editid[1]);

                            if(isset($attrib_array))  unset($attrib_array);

                            if(isset($pdctfile1))  unset($pdctfile1);

                            if(isset($pdctimage1))  unset($pdctimage1);

                        }

                        else {

                            $size_err.="<br />Please Upload Image of size greater than 25x25 pixels for product combination.";

                        }

                    }

                    else if(isset($editid[1]) && empty($this->data["Product"]["pdctfile$indx"]["tmp_name"])) {

                        $pdet=$this->Productdetail->findById($editid[1]);

                        $pdctimage2 =$pdet["Productdetail"]["pdctfile"];

                        $this->Product->updateProductCombinations($categoryid,$productid,$attributes,$stock,$reorderlevel,$skuno,$extraprice,$pdctimage2,$editid[1]);

                        if(isset($attrib_array)) unset($attrib_array);

                        if(isset($pdctimage2)) unset($pdctimage2);

                    }

                    else if( isset($editid[0]) && !isset($editid[1]) && $attributes!='' && $stock!='') {

                        $pdctimage3='';

                        if(isset($this->data["Product"]["pdctfile$indx"]["name"]) && !empty($this->data["Product"]["pdctfile$indx"]["name"])) {

                            if($width >=25 && $height >=25) {

                                $pdctfile3 = $this->Product->generateUniqueFilename($this->data["Product"]["pdctfile$indx"]["name"]);

                                $error = $this->Product->handleFileUpload($this->data["Product"]["pdctfile$indx"], $pdctfile3);

                                if(empty($error)) {
                                    if(!empty($pdctfile3))  $pdctimage3 = $pdctfile3;
                                }	else  $size_err.="<br />".$error;

                            }

                            else {

                                $size_err.="<br />Please Upload Image of size greater than 25x25 pixels for product combination.";

                            }

                        }

                        $this->Product->addProductCombinations($categoryid,$productid,$attributes,$stock,$reorderlevel,$skuno,$extraprice,$pdctimage3);

                        if(isset($attrib_array)) unset($attrib_array);

                        if(isset($pdctfile3)) unset($pdctfile3);

                        if(isset($pdctimage3)) unset($pdctimage3);

                    }



                } // end of For loop


            } // end of second if stmt

            if(isset($size_err) && !empty($size_err))

                $this->Session->setFlash(__('The Product details has been Updated.'.$size_err, true));

            else

                $this->Session->setFlash(__('Product has been Updated Successfully.', true));

            // $this->redirect(array('controller' => 'products','action'=>'edit/'.$productid.'/'.$categoryid));

            $this->redirect(array('controller' => 'products','action'=>'index'));

        } // end of first if stmt

        else {

            //$ppcat	=	$this->Category->findleaf();

            //$this->set('pcat', $ppcat);
            //newly added for category tree listing
            $ppcat = $this->Category->find('threaded', array('order' => array('Category.cname' => 'ASC')));
            $this->set('categoriesList', $ppcat);


            $this->data = $this->Product->read();

            //$pimg	=	$this->Productimages->findAllByProductId($id);

            $pimg	= $this->Productimages->find('all', array('conditions' => array('Productimages.product_id  IN ('.$id.') order by id ASC')));



            if(isset($pimg) && !empty($pimg) && sizeof($pimg) > 0) {

                $this->set('primcnt', sizeof($pimg));

                $this->set('imgarr', $pimg);

            }

            /* code for array empty */

            else {

                $this->set('primcnt', 0);

                $this->set('imgarr', 0);

            }

            $this->set('productdet', $this->data);



            ############## Code to Fetch the Attributes for editing  Starts here (Added by Shyam) ##############

            $combinations=$this->Category->findById($catid);

            if($combinations['Category']['custom_combination']!='') {

                $combination=$combinations['Category']['custom_combination'];

                $split_combination=explode(',',$combination);

                foreach($split_combination as $combn) {

                    $cparent=$this->Customfieldvalue->findById($combn);

                    $cparents[$combn]=$cparent['Customfieldvalue']['customfield_id'];

                }

                $selected_cfields=array_unique(array_values($cparents));

                $selected_cvalues=array_keys($cparents);





                foreach($selected_cfields as $fieldid) {

                    $temp_array= $this->Customfield->findById($fieldid);

                    $selected_cfieldnames[]=$temp_array['Customfield']['custom_name'];

                }

                unset($temp_array);
                unset($fieldid);

                foreach($selected_cfields as $fieldid) {

                    $temp_array= $this->Customfieldvalue->find('list',array('fields'=>array('Customfieldvalue.id', 'Customfieldvalue.custom_value'),'conditions' =>'Customfieldvalue.customfield_id  IN ('.$fieldid.')'));

                    $selected_cfieldvalues[$fieldid]=$temp_array;

                }



                $this->set('selected_cfieldvalues', $selected_cfieldvalues);

                $this->set('selected_cfieldnames', $selected_cfieldnames);

            }



            $totcnt = $this->Productdetail->find('count', array('conditions' => array('Productdetail.product_id' => $id)));

            if($totcnt>0) {

                $prod_details	=	$this->Productdetail->findAllByProductId($id);
                
                foreach($prod_details as $key => $val) {

                    $edit_id[]=$val['Productdetail']['id'];

                    $custom_combn[]=$val['Productdetail']['customvalue_id'];

                    $edit_stock[]=$val['Productdetail']['stock'];

                    $edit_reorderlevel[]=$val['Productdetail']['reorderlevel'];

                    $edit_skuno[]=$val['Productdetail']['skuno'];

                    $edit_extraprice[]=$val['Productdetail']['extraprice'];

                    $edit_pdctfile[]=$val['Productdetail']['id'].'='.$val['Productdetail']['pdctfile'];

                }
                

                $j=0;

                foreach($custom_combn as $key => $val) {



                    $edit_combn["Combndetail$j"]=explode(',',$val);

                    $j++;

                }



                $this->set('prodid',$id);

                $this->set('edit_id', $edit_id);

                $this->set('edit_stock', $edit_stock);

                $this->set('edit_reorderlevel', $edit_reorderlevel);

                $this->set('edit_skuno', $edit_skuno);

                $this->set('edit_extraprice', $edit_extraprice);

                $this->set('edit_pdctfile', $edit_pdctfile);

                $this->set('edit_combn', $edit_combn);

            }

            // End of totcnt if statement

            ############## Code to Fetch the Attributes for editing  Starts here (Added by Shyam) ##############

            $this->set('totcnt',$totcnt);

            $this->layout = 'adm';

        }

    }





    function delProdcombn($catid,$prodid,$delid) {

        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        $this->Product->delpdctcmbn($catid,$delid);

        $this->Session->setFlash(__('Product with the selected Combination has been  Deleted.', '/products'));

        $this->redirect(array('controller' => 'products','action'=>'edit/'.$prodid.'/'.$catid));

    }



    function delete($id) {

        $this->__validateLoginStatus();

        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        $del_prod=$this->Product->findById($id);

        $this->Product->delpdct($id,$del_prod["Product"]["combination"]);

        $this->Session->setFlash(__('Product has been deleted Successfully.', '/products'));

        $this->redirect('index');

    }







    #### Function to show product details on User side........

    function show($name,$id=0) {

        ini_set("allow_url_fopen", 1);
       

        global $currency;
        $curr       =   $this->Currency->findByCode($currency);
        $this->set('curlogo',$curr["Currency"]["logo"]);

        if (isset($this->Setting) && !empty($this->Setting->table)) {
            $this->Setting->load();
        }
        global $page_title;

        global $sitefolder;

        $cnfg 				=	Configure::read('Neutrino');
        $page_title			=	$name;
        if($cnfg["page_title"] <> '')
            $page_title.=' - '.$cnfg["page_title"];

        $this->set('sitefolder', $sitefolder);

        $this->pageTitle = $page_title	;

        $sus			=	$this->Session->read('Userlog');

        $this->set('sus', $sus);

        if($id == 0||$id=='') {
            //if(isset($name) && $name!='')
            //$pdet = $this->Product->find('first', array('conditions' => array('Product.pname' => $name)));
            $this->redirect(array('controller' => 'pages','action'=>'display'));
            exit();
        }
        else
            $pdet = $this->Product->find('first', array('conditions' => array('Product.id' => $id)));

        if(isset($pdet["Product"]["id"])) {

            $id		=	$pdet["Product"]["id"];

            //Code Added By shyam for Category Menu Listing starts here..

            $lst	=	$this->Category->findAll();

            foreach($lst as $det)

                $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"],'parent' => $det["Category"]["parent_id"]);

            $this->set('menu_array', $menu_array);

            //Code Added By shyam for Category Menu Listing ends here..





            $this->Product->id = $id;

            $this->data = $this->Product->read();

            #################  Fetching the Product combination(Added by Shyam)	#################



            //Fetching Images starts here

            if(isset($this->data["Productimages"]) && !empty($this->data["Productimages"])) {

                foreach($this->data["Productimages"] as $key => $val)

                    $imgarr[]=$val["imagename"];
                //echopre($imgarr);

                $this->set('imgarr', $imgarr);

            }

            //Fetching Images ends here





            if($this->data["Product"]["combination"]=='Y') {

                $pcombndet	=	$this->Productdetail->findAllByProductId($id);

                for($i=0;$i<count($pcombndet);$i++) {

                    $pcmbnids=$pcombndet[$i]["Productdetail"]["customvalue_id"];

                    $pcmbnid=explode(',',$pcmbnids);

                    foreach($pcmbnid as $key => $val) {

                        if($val!='') {

                            $combnstr[]=$this->Product->getpdctcmbn($val);

                            $combinations=implode(" ,",$combnstr);

                            $pcombndet[$i]["Productdetail"]["combinations"]= $combinations;

                        }

                    }

                    unset($combnstr);
                    unset($combinations);

                }

                $this->set('pcombndet', $pcombndet);

            }





            #################  Fetching the Product combination(Added by Shyam)	################

            if(isset($this->data["Productimages"][0]["imagename"])) {

                $defimg	=	$this->data["Productimages"][0]["imagename"];

                for($m=0; $m < sizeof($this->data["Productimages"]); $m++) {

                    if($this->data["Productimages"][$m]["default_img"] == "Y") {

                        $defimg	=	$this->data["Productimages"][$m]["imagename"];

                    }

                }

                $this->data["Productimages"]	=	$defimg;

            }else {

                $this->data["Productimages"]	= '';

            }

            $rate	=	$this->Rating->avgrate($id);

            $this->set('avgrate', $rate);

            $this->set('productdet', $this->data);

            global $currency;

            $curr		=	$this->Currency->findByCode($currency);

            $this->set('curlogo',$curr["Currency"]["logo"]);

        }

        else {

            $this->redirect(array('controller' => 'pages','action'=>'display'));

        }



    }



    ########## Function to show reorder alert....................

    function reorder() {

        $criteria='Product.stock <= Product.reorderlevel AND status ="A"';

        list($order,$limit,$page) = $this->Pagination->init($criteria); // Added

        $data = $this->Product->findAll($criteria, NULL, 'Product.id DESC', $limit, $page); // Extra parameters added

        $this->set('product', $data);

        $this->layout = 'adm';

    }

    ########## Function to show search result###############################

    function search() {

        $sus			=	$this->Session->read('Userlog');

        $this->set('sus', $sus);

        global $currency;

        $curr		=	$this->Currency->findByCode($currency);

        $this->set('curlogo',$curr["Currency"]["logo"]);

        //Code Added By shyam for Category Menu Listing starts here..

        $lst	=	$this->Category->findAll();

        foreach($lst as $det)

            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"],'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        $key	=	$_GET["srchProduct"];

        $this->pageTitle = 'Search Results';

        $criteria="Product.stock > 0 AND Product.status = 'A' AND (Product.pname  LIKE '%".addslashes($key)."%' OR Product.descr  LIKE '%".addslashes($key)."%') ";

        list($order,$limit,$page) = $this->Pagination->init($criteria); // Added



        $data = $this->Product->findAll($criteria, NULL, 'Product.id DESC', $limit, $page); // Extra parameters added

        for($c=0; $c < sizeof($data); $c++) {

            if(isset($data[$c]["Productimages"][0]["imagename"])) {

                $defimg	=	$data[$c]["Productimages"][0]["imagename"];

                for($m=0; $m < sizeof($data[$c]["Productimages"]); $m++) {

                    if($data[$c]["Productimages"][$m]["default_img"] == "Y") {

                        $defimg	=	$data[$c]["Productimages"][$m]["imagename"];

                    }

                }

                $data[$c]["Productimages"]	=	$defimg;

            }

            else {

                $data[$c]["Productimages"]	= '';

            }

        }

        $this->set('product', $data);

    }

    ######## Ajax Fuction To rate a product.........................................
    function rate($pid,$rt) {
        global $sitefolder;
        $this->layout = null;
        $this->set('rated', $rt);
        $sus	=	$this->Session->read('Userlog');
        if(!empty($sus)===true) {
            $chk	=	$this->Rating->findCount('Rating.user_id = '.$sus["id"].' AND Rating.product_id = '.$pid);
            if($chk > 0) {
                echo "err1";
                exit;
            }
            else {
                $dat["user_id"]		=	$sus["id"];
                $dat["product_id"]	=	$pid;
                $dat["rate"]		=	$rt;
                if($this->Rating->save($dat)) {
                    echo "yes";
                    exit;
                }
            }
        }else {
            echo "err2";
            //echo $sitefolder.'/users/login/';
            exit;
        }
    }







    ################### Function to show the Products details at adminside.............................

    function details($id) {

        $this->Product->id = $id;

        $this->data = $this->Product->read();

        $rate	=	$this->Rating->avgrate($id);

        $this->set('avgrate', $rate);

        $sus			=	$this->Session->read('Userlog');

        $this->set('sus', $sus);

        $k=0;

        $i = 0;

        $optname	=	'';

        $optionarr	=	array();

        $optionarnm	=	array();

        $inarr		=	false;

        if(isset($this->data["Productimages"][0]["imagename"])) {

            $defimg	=	$this->data["Productimages"][0]["imagename"];

            for($m=0; $m < sizeof($this->data["Productimages"]); $m++) {

                if($this->data["Productimages"][$m]["default"] == "Y") {

                    $defimg	=	$this->data["Productimages"][$m]["imagename"];

                }

            }

            $this->data["Productimages"]	=	$defimg;

        }else {

            $this->data["Productimages"]	= '';

        }

        for($m=0; $m < sizeof($this->data["Productcustomfields"]); $m++) {



            $copt	=	$this->Customfield->findById($this->data["Productcustomfields"][$m]["customfield_id"]);



            if (in_array($copt["Customfield"]["custom_name"], $optionarnm)) {

                $inarr	=	false;

            }else {

                $inarr	=	true;

            }

            if($optname <> $copt["Customfield"]["custom_name"] ) {

                $i 				=	0;

                $optname		=	$copt["Customfield"]["custom_name"];

                ///$optionarr[$k]	=	$optname."#$@^".$copt["Customfield"]["custom_value"];

                $k++;

            }

            $optionarr[$k]["name"]	=	$optname;

            $optionarr[$k]["value"][$i]	=	$copt["Customfield"]["custom_value"];

            $optionarnm[$k]	=	$copt["Customfield"]["custom_name"];

            $i++;

        }

        $this->data["Productcustomfields"]	=	$optionarr;

        $this->set('productdet', $this->data);

        global $currency;

        $curr		=	$this->Currency->findByCode($currency);

        $this->set('curlogo',$curr["Currency"]["logo"]);

        $this->layout = 'adm';

    }

    function addcrt() {

        if($_SERVER['REQUEST_METHOD'] == "POST") {

            $cid	=	$_POST["cid"];

            $pid	=	$_POST["pid"];

            $optar	=	implode("$!&*",$_POST["opt"]);

            $optar	=	base64_encode($optar);

            $this->redirect(array('controller' => 'carts','action'=>'add/'.$pid.'/'.$cid.'/'.$optar));

            exit;

        }

    }

    function addimage() {

        if($_SERVER['REQUEST_METHOD'] == "POST") {

            $pid	=	$_POST["pid"];

            $err = false;

            $i = 0;

            $ims	=	array();

            if(isset($_FILES)) {

                foreach($_FILES as $fl) {

                    if(!empty($fl['tmp_name'])) {

                        $fileName = $this->Product->generateUniqueFilename($fl['name']);

                        $error = $this->Product->handleFileUpload($fl, $fileName);

                        if(!isset($error) || $error == '') {

                            $ims[$i]	=	$fileName;

                            $i++;

                        }

                    }

                }



            }

            if(!empty($ims)) {

                foreach($ims as $img) {

                    $this->Productimages->create($csf = array());

                    $csf	=	array("product_id" => $pid, "imagename" =>$img);

                    $this->Productimages->save($csf);

                }

            }



            $this->redirect(array('controller' => 'products','action'=>'edit/'.$pid.'/img'));

            exit;

        }

    }

    function defaultimage($id,$pid) {

        if($this->Product->defaultimage($id,$pid)) {

            $this->Session->setFlash(__('Your default image selection have been saved.', true));

            $this->redirect(array('controller' => 'products','action'=>'edit/'.$pid.'/img'));

            exit;

        }

    }

    function deleteimage($pid='',$cid='',$delid='',$type='') {

        if($type=='pdct') {

            $det	=	$this->Productimages->findById($delid);

            if(!empty($det["Productimages"])) {

                $imde	=	explode(".",$det["Productimages"]["imagename"]);

                $imgext  =  end(explode(".",$det["Productimages"]["imagename"]));

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$det["Productimages"]["imagename"]);

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$imde[0]."_thumb".$imgext);

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$imde[0]."_disp".$imgext);

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$imde[0]."_xtra".$imgext);

            }

            if($this->Productimages->del($delid)) {

                $this->Session->setFlash(__('Product Image has been deleted Successfully.', true));

                $this->redirect(array('controller' => 'products','action'=>'edit/'.$pid.'/'.$cid));

                exit;

            }

        }

        if($type=='cmbn') {

            $det	=	$this->Productdetail->findById($delid);

            if(!empty($det["Productdetail"])) {

                $imde	=	explode(".",$det["Productdetail"]["pdctfile"]);

                $imgext  =  end(explode(".",$det["Productdetail"]["pdctfile"]));

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$det["Productdetail"]["pdctfile"]);

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$imde[0]."_thumb".$imgext);

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$imde[0]."_disp".$imgext);

                $this->Product->deleteMovedFile(WWW_ROOT.IMAGES_URL."products/".$imde[0]."_xtra".$imgext);

            }

            $this->Productdetail->id = $delid;

            $this->Productdetail->saveField('pdctfile','');

            $this->Session->setFlash(__('Product Image has been deleted Successfully.', true));

            $this->redirect(array('controller' => 'products','action'=>'edit/'.$pid.'/'.$cid));

            exit;

        }

    }

    ######## Ajax Fuction To show image of a product.........................................

    function shwajximg($img,$imarr,$j) {



        $this->set("img",$img);

        $this->set("imarr",$imarr);

        $this->set("j",$j);

        $this->layout = 'ajax';

    }

    ##################### Section for bulk upload and deletion of products.........................

    function bulkupload() {

        $this->__validateLoginStatus();
        $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);

        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        if (!empty($this->data)) {

            if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {

                $pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name'],WWW_ROOT.IMAGES_URL.'csv/');

                $error = $this->Product->csvUpload($this->data['Product']['pdctfile'], $pdctfile1,WWW_ROOT.IMAGES_URL.'csv/');
               
            }

            if(empty($error) && !empty($this->data['Product']['pdctfile']['tmp_name'])) {
                $this->Session->setFlash(__('Please save your data to continue upload.', true));
 
                $this->redirect(array('controller' => 'products','action'=>'checkbulkupload/'.$pdctfile1));

                exit;

            }else {

                if(isset($error)) {

                    $this->Session->setFlash(__($error, true));

                }

            }

        }

        $this->layout = 'adm';

    }

    function checkbulkupload($filename) {

        $this->__validateLoginStatus();

        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);
        $admsess	=	$this->Session->read('Admin');


        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        $dat	=	file_get_contents(WWW_ROOT.IMAGES_URL.'csv/'.$filename);

        $line	=	explode("\n",$dat);

        $this->set("header",explode(',',$line[0]));

        $this->set("filename",$filename);

        $this->layout = 'adm';

        if($_SERVER['REQUEST_METHOD'] == "POST") {



            $category		=	$_POST["category"];

            $pname			=	$_POST["pname"];

            $description	=	$_POST["pdescr"];

            $wholesale_price =	$_POST["wholesale_price"];

            $retail_price    =	$_POST["retail_price"];

            $weight			=	$_POST["weight"];

            $reorder		=	$_POST["reorder"];

            $stock			=	$_POST["stock"];

            unset($line[0]);

            $rows	=	array();

            $flag	=	true;

            foreach($line as $rows) {

                $row	=	array();

                $row	=	explode(",",$rows);

                $categ	=	array();

                $carray	=	array();

                if(sizeof($row) > 1) {

                    if(isset($row[$category])) {

                        if($row[$category] == " ") {

                            $row[$category]	=	"No Category";

                        }

                        $categ	=	$this->Category->findByCname($row[$category]);

                        if(!empty($categ)) {

                            $row[$category]	=	$categ["Category"]["id"];

                        }else {



                            $carray["Category"]	=	array("cname" => $row[$category], "parent_id" => 1);

                            $this->Category->create();

                            $this->Category->save($carray);

                            $categ	=	$this->Category->findByCname($row[$category]);

                            if(!empty($categ)) {

                                $row[$category]	=	$categ["Category"]["id"];

                            }

                        }

                    }

                    $parray	=	array();

                    $parray["Product"]["category_id"]	=	$row[$category];

                    $parray["Product"]["pname"]			=	$row[$pname];

                    $parray["Product"]["wholesale_price"]	=	$row[$wholesale_price];


                    if(!is_numeric($parray["Product"]["wholesale_price"]))
                    {
                        $parray["Product"]["wholesale_price"] = 0;
                    }

                    $parray["Product"]["price"]			=	$row[$retail_price];


                    if(!is_numeric($parray["Product"]["price"]))
                    {
                        $parray["Product"]["price"] = 0;
                    }


                    if($description == ' ') {

                        $parray["Product"]["descr"]		=	'';

                    }else {

                        $parray["Product"]["descr"]		=	$row[$description];

                    }

                    if($weight == ' ') {

                        $parray["Product"]["weight"]		=	0;

                    }elseif(isset($row[$weight])) {

                        $parray["Product"]["weight"]		=	$row[$weight];

                    }else {
                        $parray["Product"]["weight"] = 0;
                    }


                    if($parray["Product"]["weight"] == NULL) {
                        $parray["Product"]["weight"] = 0;
                    }


                     if(!is_numeric($parray["Product"]["weight"]))
                    {
                        $parray["Product"]["weight"] = 0;
                    }



                    if($reorder == ' ') {

                        $parray["Product"]["reorderlevel"]		=	0;

                    }elseif(isset ($row[$reorder])) {

                        $parray["Product"]["reorderlevel"]		=	$row[$reorder];

                    }else {
                        $parray["Product"]["reorderlevel"]		=	0;
                    }

                     if(!is_numeric($parray["Product"]["reorderlevel"]))
                    {
                        $parray["Product"]["reorderlevel"] = 0;
                    }     


                    if($stock == ' ') {

                        $parray["Product"]["stock"]		=	0;

                    }elseif(isset ($row[$stock])) {

                        $parray["Product"]["stock"]		=	$row[$stock];

                    }else {
                        $parray["Product"]["stock"]		=	0;
                    }

                     if(!is_numeric($parray["Product"]["stock"]))
                    {
                        $parray["Product"]["stock"] = 0;
                    }     


                    ######################Section to check maximum number of products limit****************************************

                    App::import('Xml');



                    // your XML file's location

                    $file = "configxml.xml";



                    // now parse it

                    $parsed_xml = new XML($file);

                    $parsed_xml = Set::reverse($parsed_xml); // this is what i call magic

                    $maxnum = $parsed_xml["Configuration"] ["pno"];

                    //$curnum	=	$this->Product->getCntPdct();
                    $curnum = $this->Product->find('count', array('conditions' => array('Product.status' => 'A')));

                    if(trim($curnum) >= trim($maxnum)) {

                        unlink(WWW_ROOT.IMAGES_URL.'csv/'.$filename);
                         $this->Session->setFlash(__('The Maximum Product limit '.$maxnum.' can not exceed', true));

                        //$this->Session->setFlash(__('You package limit '.$maxnum.' can not exceed', true));

                        $this->redirect(array('action'=>'index'));

                        exit;

                    }else {

                        #$dupl	=	$this->Product->findByPname($row[$pname]);

                        $dupl	=	$this->Product->findAll('Product.pname = "'.$row[$pname].'" AND Product.status = "A"');

                        if(empty($dupl)) {

                            $this->Product->create();

                            $this->Product->save($parray);

                        }

                    }

                }

            }

            unlink(WWW_ROOT.IMAGES_URL.'csv/'.$filename);

            $this->Session->setFlash(__('Products have been added.', true));

            $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));

            exit;

        }



    }


    //****************
    ##################### Section for bulk upload digital prouct and deletion of products.........................

    function bulkuploaddigitalproduct() {

        $this->__validateLoginStatus();
        $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        if (!empty($this->data)) {

            if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {

                $pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name'],WWW_ROOT.IMAGES_URL.'csv/');

                $error = $this->Product->csvUpload($this->data['Product']['pdctfile'], $pdctfile1,WWW_ROOT.IMAGES_URL.'csv/');

            }

            if(empty($error) && !empty($this->data['Product']['pdctfile']['tmp_name'])) {
                $this->Session->setFlash(__('Please save your data to continue upload.', true));
                $this->redirect(array('controller' => 'products','action'=>'checkbulkuploaddigitalproduct/'.$pdctfile1));

                exit;

            }else {

                if(isset($error)) {

                    $this->Session->setFlash(__($error, true));

                }

            }

        }

        $this->layout = 'adm';

    }

    function checkbulkuploaddigitalproduct($filename) {

        $this->__validateLoginStatus();

        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);


        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        $dat	=	file_get_contents(WWW_ROOT.IMAGES_URL.'csv/'.$filename);

        $line	=	explode("\n",$dat);

        $this->set("header",explode(',',$line[0]));

        $this->set("filename",$filename);

        $this->layout = 'adm';

        if($_SERVER['REQUEST_METHOD'] == "POST") {



            $category		=	$_POST["category"];

            $pname			=	$_POST["pname"];

            $description	=	$_POST["pdescr"];

            $wholesale_price =	$_POST["wholesale_price"];

            $retail_price    =	$_POST["retail_price"];

            $pdctfile			=	$_POST["pdctfile"];

            /*$reorder		=	$_POST["reorder"];

			$stock			=	$_POST["stock"];*/

            unset($line[0]);

            $rows	=	array();

            $flag	=	true;

            foreach($line as $rows) {

                $row	=	array();

                $row	=	explode(",",$rows);

                $categ	=	array();

                $carray	=	array();

                if(sizeof($row) > 1) {

                    if(isset($row[$category])) {

                        if($row[$category] == " ") {

                            $row[$category]	=	"No Category";

                        }

                        $categ	=	$this->Category->findByCname($row[$category]);

                        if(!empty($categ)) {

                            $row[$category]	=	$categ["Category"]["id"];

                        }else {



                            $carray["Category"]	=	array("cname" => $row[$category], "parent_id" => 1);

                            $this->Category->create();

                            $this->Category->save($carray);

                            $categ	=	$this->Category->findByCname($row[$category]);

                            if(!empty($categ)) {

                                $row[$category]	=	$categ["Category"]["id"];

                            }

                        }

                    }

                    $parray	=	array();

                    $parray["Product"]["category_id"]	=	$row[$category];

                    $parray["Product"]["pname"]			=	$row[$pname];

                    $parray["Product"]["wholesale_price"]	=	$row[$wholesale_price];

                    $parray["Product"]["price"]			=	$row[$retail_price];


                     if(!is_numeric($parray["Product"]["wholesale_price"]))
                    {
                             $parray["Product"]["wholesale_price"] = 0;
                     }

                      if(!is_numeric($parray["Product"]["price"]))
                    {
                             $parray["Product"]["price"] = 0;
                     }


                    if($description == ' ') {

                        $parray["Product"]["descr"]		=	'';

                    }else {

                        $parray["Product"]["descr"]		=	$row[$description];

                    }

                    if($pdctfile == ' ') {

                        $parray["Product"]["pdctfile"]		=	"";

                    }elseif(isset($row[$pdctfile])) {

                        $parray["Product"]["pdctfile"]		=	$row[$pdctfile];

                    }else {
                        $parray["Product"]["pdctfile"] = "";
                    }
                    if($parray["Product"]["pdctfile"] == NULL) {
                        $parray["Product"]["pdctfile"] = "";
                    }

                    $parray["Product"]["prodtype"] = 'Digital';
                    $parray["Product"]["stock"] = 990000;

                    $parray["Product"]["status"] = "A";
                    /*if($reorder == ' '){

						$parray["Product"]["reorderlevel"]		=	0;

					}elseif(isset ($row[$reorder])) {

						$parray["Product"]["reorderlevel"]		=	$row[$reorder];

					}else{
                                            $parray["Product"]["reorderlevel"]		=	0;
                                        }

					if($stock == ' '){

						$parray["Product"]["stock"]		=	0;

					}elseif(isset ($row[$stock])) {

						$parray["Product"]["stock"]		=	$row[$stock];

					}else{
                                            $parray["Product"]["stock"]		=	0;
                                        }*/


                    ######################Section to check maximum number of products limit****************************************

                    App::import('Xml');



                    // your XML file's location

                    $file = "configxml.xml";



                    // now parse it

                    $parsed_xml =  new XML($file);

                    $parsed_xml = Set::reverse($parsed_xml); // this is what i call magic

                    $maxnum = $parsed_xml["Configuration"] ["pno"];

                    //$curnum	=	$this->Product->getCntPdct();
                    $curnum = $this->Product->find('count', array('conditions' => array('Product.status' => 'A')));

                    if(trim($curnum) >= trim($maxnum)) {

                        unlink(WWW_ROOT.IMAGES_URL.'csv/'.$filename);
                        $this->Session->setFlash(__('The Maximum Product limit '.$maxnum.' can not exceed', true));
                        //$this->Session->setFlash(__('You package limit '.$maxnum.' can not exceed', true));

                        $this->redirect(array('action'=>'index'));

                        exit;

                    }else {

                        #$dupl	=	$this->Product->findByPname($row[$pname]);

                        $dupl	=	$this->Product->findAll('Product.pname = "'.$row[$pname].'" AND Product.status = "A"');
                        



                        if(empty($dupl)) {

                            $this->Product->create();

                            $this->Product->save($parray);

                        }

                    }

                }

            }

            unlink(WWW_ROOT.IMAGES_URL.'csv/'.$filename);

            $this->Session->setFlash(__('Products have been added.', true));

            $this->redirect(array('controller' => 'products','action'=>'bulkuploaddigitalproductfiles'));

            exit;

        }



    }
    //************************digital prd ends********

    function bulkuploadimage() {

        $this->__validateLoginStatus();
        $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
        $error = "";
        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        if (!empty($this->data)) {



            if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {

                //$pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name'],WWW_ROOT.IMAGES_URL.'csv/');
                //************useing zip file name to get product name  *****************
                $pdctfile1 = $this->data['Product']['pdctfile']['name'];
                $error = $this->Product->csvUpload($this->data['Product']['pdctfile'], $pdctfile1,WWW_ROOT.IMAGES_URL.'csv/');

            }

            if(empty($error)) {
                $this->redirect(array('controller' => 'products','action'=>'checkimageupload/'.$pdctfile1));
                exit;

            }else {

                $this->Session->setFlash(__($error, true));

            }

        }

        $this->layout = 'adm';

    }

    function checkimageupload($filename) {
        $this->__validateLoginStatus();

        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);

        $admsess	=	$this->Session->read('Admin');
        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }

        ########### Constatnts for pclZip class.........................

        // ----- Constants

        define( 'PCLZIP_READ_BLOCK_SIZE', 2048 );



        // ----- File list separator

        // In version 1.x of PclZip, the separator for file list is a space

        // (which is not a very smart choice, specifically for windows paths !).

        // A better separator should be a comma (,). This constant gives you the

        // abilty to change that.

        // However notice that changing this value, may have impact on existing

        // scripts, using space separated filenames.

        // Recommanded values for compatibility with older versions :

        //define( 'PCLZIP_SEPARATOR', ' ' );

        // Recommanded values for smart separation of filenames.

        define( 'PCLZIP_SEPARATOR', ',' );



        // ----- Error configuration

        // 0 : PclZip Class integrated error handling

        // 1 : PclError external library error handling. By enabling this

        //     you must ensure that you have included PclError library.

        // [2,...] : reserved for futur use

        define( 'PCLZIP_ERROR_EXTERNAL', 0 );



        // ----- Optional static temporary directory

        //       By default temporary files are generated in the script current

        //       path.

        //       If defined :

        //       - MUST BE terminated by a '/'.

        //       - MUST be a valid, already created directory

        //       Samples :

        // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' );

        // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' );

        define( 'PCLZIP_TEMPORARY_DIR', '' );



        // --------------------------------------------------------------------------------

        // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****

        // --------------------------------------------------------------------------------



        // ----- Global variables

        $g_pclzip_version = "2.3";



        // ----- Error codes

        //   -1 : Unable to open file in binary write mode

        //   -2 : Unable to open file in binary read mode

        //   -3 : Invalid parameters

        //   -4 : File does not exist

        //   -5 : Filename is too long (max. 255)

        //   -6 : Not a valid zip file

        //   -7 : Invalid extracted file size

        //   -8 : Unable to create directory

        //   -9 : Invalid archive extension

        //  -10 : Invalid archive format

        //  -11 : Unable to delete file (unlink)

        //  -12 : Unable to rename file (rename)

        //  -13 : Invalid header checksum

        //  -14 : Invalid archive size

        define( 'PCLZIP_ERR_USER_ABORTED', 2 );
        define( 'PCLZIP_ERR_NO_ERROR', 0 );
        define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 );
        define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 );
        define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 );
        define( 'PCLZIP_ERR_MISSING_FILE', -4 );
        define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 );
        define( 'PCLZIP_ERR_INVALID_ZIP', -6 );
        define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 );
        define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 );
        define( 'PCLZIP_ERR_BAD_EXTENSION', -9 );
        define( 'PCLZIP_ERR_BAD_FORMAT', -10 );
        define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 );
        define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 );
        define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 );
        define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 );
        define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 );
        define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 );
        define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 );
        define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 );
        define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 );
        // ----- Options values

        define( 'PCLZIP_OPT_PATH', 77001 );
        define( 'PCLZIP_OPT_ADD_PATH', 77002 );
        define( 'PCLZIP_OPT_REMOVE_PATH', 77003 );
        define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 );
        define( 'PCLZIP_OPT_SET_CHMOD', 77005 );
        define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 );
        define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 );
        define( 'PCLZIP_OPT_BY_NAME', 77008 );
        define( 'PCLZIP_OPT_BY_INDEX', 77009 );
        define( 'PCLZIP_OPT_BY_EREG', 77010 );
        define( 'PCLZIP_OPT_BY_PREG', 77011 );
        define( 'PCLZIP_OPT_COMMENT', 77012 );
        define( 'PCLZIP_OPT_ADD_COMMENT', 77013 );
        define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 );
        define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 );
        define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 );
        define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 );
        // Having big trouble with crypt. Need to multiply 2 long int

        // which is not correctly supported by PHP ...

        //define( 'PCLZIP_OPT_CRYPT', 77018 );



        // ----- Call backs values

        define( 'PCLZIP_CB_PRE_EXTRACT', 78001 );
        define( 'PCLZIP_CB_POST_EXTRACT', 78002 );
        define( 'PCLZIP_CB_PRE_ADD', 78003 );
        define( 'PCLZIP_CB_POST_ADD', 78004 );
        ########### Constatnts for pclZip class.........................

        $this->Pclzip->PclZip(WWW_ROOT.IMAGES_URL.'csv/' . $filename);
        if ($this->Pclzip->extract(PCLZIP_OPT_PATH, WWW_ROOT.IMAGES_URL.'csv/' ) == 0) {
            // die("Error : " . $archive->errorInfo(true));

            // $message

            $error	= "Can not extract files.";
            $this->Session->setFlash(__($error, true));
            //$this->redirect(array('controller' => 'admins','action'=>'index'));
            $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
            exit;
        }

        $dirpath = WWW_ROOT.IMAGES_URL.'csv/'.$filename;
        if (file_exists($dirpath)) {

            unlink($dirpath);

        }

        $exp=explode(".",$filename);

        $zipfilename=$exp[0];


        $dirpaths= WWW_ROOT.IMAGES_URL.'csv/'.$zipfilename;



        if(is_dir($dirpaths) and file_exists($dirpaths)) {

            $image_file_path=$dirpaths;



        }else {

            $image_file_path=WWW_ROOT.IMAGES_URL.'csv/';

        }

        if(file_exists($image_file_path)) { // check file folder exists

            $d = dir($image_file_path) or die("Wrong path: $image_file_path");

            while (false !== ($entry = $d->read())) {

                if($entry != '.' && $entry != '..' && !is_dir($entry)) {

                    $Images[] = $entry;

                }



            } // end while


            $d->close();


            $cnfg 		= Configure::read('Neutrino');
            $imgcnt=0;
            $allowedExts = array("jpg", "jpeg", "gif", "png");

            $fileExt =  "";
            foreach($Images as $img) {
                /*if($img <> "Thumbs.db" && $img <> "Thumbs.ini") {
                    $imgcnt++;
                }*/

                 $fileExt = end(explode(".",$img));
                
                 if(in_array($fileExt, $allowedExts))
                 {
                    $imgcnt++;
                 }   

            }

              
            if($cnfg["product_images"] < $imgcnt) {
                foreach($Images as $img) {
                    if(file_exists($image_file_path."/".$img)) {
                        unlink($image_file_path."/".$img);
                    }
                }
                if(file_exists($image_file_path)) {
                    if($image_file_path <> WWW_ROOT.IMAGES_URL.'csv/') {
                        rmdir($image_file_path);
                    }
                }
                $this->Session->setFlash(__('The zip file should contain only '.$cnfg["product_images"].' Images.', true));
                $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
                exit();
            }


            $prod_array = $this->Product->find('first', array('conditions' => array('Product.pname  LIKE ' => "".addslashes($zipfilename)."%")));

            

            if(isset($prod_array["Product"]["id"]) && $prod_array["Product"]["id"] <> 0) {
                $curr_cnt = $this->Productimages->find('count', array('conditions' => array('Productimages.product_id' => $prod_array["Product"]["id"])));
                if($curr_cnt > 0) {
                    $this->Session->setFlash(__('The product already contains some Images.Please remove all the images before uploading the zip file.', true));
                    $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
                    exit();
                }
                /*
			   else
			   {
			     $split_cnt=$cnfg["product_images"] - $curr_cnt;
			   }
                */
            }else {
                $this->Session->setFlash(__('The product name matching file name does not exist!.', true));
                $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
                exit();
            }


            /*
			if($split_cnt > 0)
			$Images = array_slice($Images, $split_cnt);
            */

                

              $fileName = '';

              $allowedExts = array("jpg", "jpeg", "gif", "png");

              $img = '';

              $i =1;

            foreach($Images as $img) {

                if($img <> "Thumbs.db") {

                    $pimname	=	substr($img,0,mb_strrpos($img,"."));

                    $parray		=	array();

                    //$criteria ="Product.pname  LIKE '".addslashes($pimname)."%'";
                    //$parray = $this->Product->find($criteria);

                    //$parray = $this->Product->find('first', array('Product.pname  LIKE ' => "%".addslashes($pimname)."%"));


             $fileExt = end(explode(".",$img));
             $fcount = count($fileExt);

             if(in_array($fileExt, $allowedExts))
             {
                $fileName = "VC".$i.time().".".$fileExt;
             }   

           /* if($fcount > 1) {
                $fileExtention = $fileExt[$fcount -1];
                $fileName = "VC".time().".".$fileExtention;
            }*/



         


                    $parray = $this->Product->find('first', array('conditions' => array('Product.pname  LIKE ' => "".addslashes($zipfilename)."%")));

                    if(isset($parray["Product"]["id"]) && $parray["Product"]["id"] <> 0) {

                        $pro	=	array();

                        $pro["Productimages"]["product_id"]	=	$parray["Product"]["id"];

                        $pro["Productimages"]["imagename"]	=	$fileName;

                        $pro["Productimages"]["default"]		=	"A";

                        $this->Productimages->create();

                        

                        $this->Productimages->save($pro);

                        $path	=	WWW_ROOT.IMAGES_URL.'products/';

                        rename($image_file_path."/".$img, $path.$fileName);

                        $this->Product->resizeImg( $path."/".$fileName, 125 ,125, false, 100, 0,"_thumb");

                        $this->Product->resizeImg( $path."/".$fileName, 180 ,180, false, 100, 0,"_disp");

                        $this->Product->resizeImg( $path."/".$fileName, 300 ,300, false, 100, 0,"_xtra");

                       

                        $error	=	"Images uploaded successfully";


                    }

                    #mb_strrpos(".",$img)."<br>";

                        $i++;

                }

                if(file_exists($image_file_path."/".$fileName)) {

                    unlink($image_file_path."/".$fileName);

                }
            }
            //  echo '<br>'.$error;


            if(file_exists($image_file_path)) {

                if($image_file_path <> WWW_ROOT.IMAGES_URL.'csv/') {

                    rmdir($image_file_path);

                }

            }

        }


        if(isset($error)) {

            $this->Session->setFlash(__($error, true));

        }

        $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
        //$this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
        exit;



    }


    //************************digital prd ends********

    //************************digital prd file uplod********

    function bulkuploaddigitalproductfiles() {

        $this->__validateLoginStatus();
        $cnfg 				=	Configure::read('Neutrino');
        $style				=	$cnfg["style"];
        $this->set('style', "admin/".$style);
        $error = "";
        $admsess	=	$this->Session->read('Admin');

        if($admsess["products"] <> 1) {

            $this->redirect(array('controller' => 'admins', 'action' => 'index'));

            exit();

        }

        if (!empty($this->data)) {



            if(!empty($this->data['Product']['pdctfile']['tmp_name'])) {

                //$pdctfile1 = $this->Product->generateUniqueFilename($this->data['Product']['pdctfile']['name'],WWW_ROOT.IMAGES_URL.'csv/');
                //************useing zip file name to get product name  *****************
                $pdctfile1 = $this->data['Product']['pdctfile']['name'];
                $error = $this->Product->csvUpload($this->data['Product']['pdctfile'], $pdctfile1,WWW_ROOT.IMAGES_URL.'csv/');

            }

            if(empty($error)) {
                $this->redirect(array('controller' => 'products','action'=>'checkimageuploaddigitalproduct/'.$pdctfile1));
                exit;

            }else {

                $this->Session->setFlash(__($error, true));

            }

        }

        $this->layout = 'adm';

    }

    function checkimageuploaddigitalproduct($filename) {
        $this->__validateLoginStatus();

        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);

        $admsess	=	$this->Session->read('Admin');
        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }

        ########### Constatnts for pclZip class.........................

        // ----- Constants

        define( 'PCLZIP_READ_BLOCK_SIZE', 2048 );



        // ----- File list separator

        // In version 1.x of PclZip, the separator for file list is a space

        // (which is not a very smart choice, specifically for windows paths !).

        // A better separator should be a comma (,). This constant gives you the

        // abilty to change that.

        // However notice that changing this value, may have impact on existing

        // scripts, using space separated filenames.

        // Recommanded values for compatibility with older versions :

        //define( 'PCLZIP_SEPARATOR', ' ' );

        // Recommanded values for smart separation of filenames.

        define( 'PCLZIP_SEPARATOR', ',' );



        // ----- Error configuration

        // 0 : PclZip Class integrated error handling

        // 1 : PclError external library error handling. By enabling this

        //     you must ensure that you have included PclError library.

        // [2,...] : reserved for futur use

        define( 'PCLZIP_ERROR_EXTERNAL', 0 );



        // ----- Optional static temporary directory

        //       By default temporary files are generated in the script current

        //       path.

        //       If defined :

        //       - MUST BE terminated by a '/'.

        //       - MUST be a valid, already created directory

        //       Samples :

        // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' );

        // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' );

        define( 'PCLZIP_TEMPORARY_DIR', '' );



        // --------------------------------------------------------------------------------

        // ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****

        // --------------------------------------------------------------------------------



        // ----- Global variables

        $g_pclzip_version = "2.3";



        // ----- Error codes

        //   -1 : Unable to open file in binary write mode

        //   -2 : Unable to open file in binary read mode

        //   -3 : Invalid parameters

        //   -4 : File does not exist

        //   -5 : Filename is too long (max. 255)

        //   -6 : Not a valid zip file

        //   -7 : Invalid extracted file size

        //   -8 : Unable to create directory

        //   -9 : Invalid archive extension

        //  -10 : Invalid archive format

        //  -11 : Unable to delete file (unlink)

        //  -12 : Unable to rename file (rename)

        //  -13 : Invalid header checksum

        //  -14 : Invalid archive size

        define( 'PCLZIP_ERR_USER_ABORTED', 2 );
        define( 'PCLZIP_ERR_NO_ERROR', 0 );
        define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 );
        define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 );
        define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 );
        define( 'PCLZIP_ERR_MISSING_FILE', -4 );
        define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 );
        define( 'PCLZIP_ERR_INVALID_ZIP', -6 );
        define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 );
        define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 );
        define( 'PCLZIP_ERR_BAD_EXTENSION', -9 );
        define( 'PCLZIP_ERR_BAD_FORMAT', -10 );
        define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 );
        define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 );
        define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 );
        define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 );
        define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 );
        define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 );
        define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 );
        define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 );
        define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 );
        // ----- Options values

        define( 'PCLZIP_OPT_PATH', 77001 );
        define( 'PCLZIP_OPT_ADD_PATH', 77002 );
        define( 'PCLZIP_OPT_REMOVE_PATH', 77003 );
        define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 );
        define( 'PCLZIP_OPT_SET_CHMOD', 77005 );
        define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 );
        define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 );
        define( 'PCLZIP_OPT_BY_NAME', 77008 );
        define( 'PCLZIP_OPT_BY_INDEX', 77009 );
        define( 'PCLZIP_OPT_BY_EREG', 77010 );
        define( 'PCLZIP_OPT_BY_PREG', 77011 );
        define( 'PCLZIP_OPT_COMMENT', 77012 );
        define( 'PCLZIP_OPT_ADD_COMMENT', 77013 );
        define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 );
        define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 );
        define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 );
        define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 );
        // Having big trouble with crypt. Need to multiply 2 long int

        // which is not correctly supported by PHP ...

        //define( 'PCLZIP_OPT_CRYPT', 77018 );



        // ----- Call backs values

        define( 'PCLZIP_CB_PRE_EXTRACT', 78001 );
        define( 'PCLZIP_CB_POST_EXTRACT', 78002 );
        define( 'PCLZIP_CB_PRE_ADD', 78003 );
        define( 'PCLZIP_CB_POST_ADD', 78004 );
        ########### Constatnts for pclZip class.........................

        $this->Pclzip->PclZip(WWW_ROOT.IMAGES_URL.'csv/' . $filename);
        if ($this->Pclzip->extract(PCLZIP_OPT_PATH, WWW_ROOT.IMAGES_URL.'csv/' ) == 0) {
            // die("Error : " . $archive->errorInfo(true));

            // $message

            $error	= "Can not extract files.";
            $this->Session->setFlash(__($error, true));
            //$this->redirect(array('controller' => 'admins','action'=>'index'));
            $this->redirect(array('controller' => 'products','action'=>'bulkuploaddigitalproductfiles'));
            exit;
        }

        $dirpath = WWW_ROOT.IMAGES_URL.'csv/'.$filename;
        if (file_exists($dirpath)) {

            unlink($dirpath);

        }

        $exp=explode(".",$filename);

        $zipfilename=$exp[0];


        $dirpaths= WWW_ROOT.IMAGES_URL.'csv/'.$zipfilename;



        if(is_dir($dirpaths) and file_exists($dirpaths)) {

            $image_file_path=$dirpaths;



        }else {

            $image_file_path=WWW_ROOT.IMAGES_URL.'csv/';

        }

        if(file_exists($image_file_path)) { // check file folder exists

            $d = dir($image_file_path) or die("Wrong path: $image_file_path");

            while (false !== ($entry = $d->read())) {

                if($entry != '.' && $entry != '..' && !is_dir($entry)) {

                    $Images[] = $entry;

                }



            } // end while


            $d->close();


            $cnfg 		= Configure::read('Neutrino');
            $imgcnt=0;
            /*foreach($Images as $img)
			{
			  if($img <> "Thumbs.db" && $img <> "Thumbs.ini")
			  {	  $imgcnt++; }
		    }*/


            /*if($cnfg["product_images"] < $imgcnt)
			{
		         foreach($Images as $img)
				 {
				   if(file_exists($image_file_path."/".$img))
				   {
					 unlink($image_file_path."/".$img);
				   }
				 }
				 if(file_exists($image_file_path))
				 {
				     if($image_file_path <> WWW_ROOT.IMAGES_URL.'csv/')
					  {
					    rmdir($image_file_path);
					  }
				  }
				 $this->Session->setFlash(__('The zip file should contain only '.$cnfg["product_images"].' Images.', true));
				 $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
				 exit();
			}*/


            /*$prod_array = $this->Product->find('first', array('conditions' => array('Product.pname  LIKE ' => "".addslashes($zipfilename)."%")));


                        if(isset($prod_array["Product"]["id"]) && $prod_array["Product"]["id"] <> 0)
			{
			  $curr_cnt = $this->Productimages->find('count', array('conditions' => array('Productimages.product_id' => $prod_array["Product"]["id"])));
			  if($curr_cnt > 0)
			   {
		         $this->Session->setFlash(__('The product already contains some Images.Please remove all the images before uploading the zip file.', true));
				 $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
				 exit();
			   }
			   /*
			   else
			   {
			     $split_cnt=$cnfg["product_images"] - $curr_cnt;
			   }
            */
            /*}else{
                             $this->Session->setFlash(__('The product name matching file name does not exist!.', true));
				 $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
				 exit();
                        }*/


            /*
			if($split_cnt > 0)
			$Images = array_slice($Images, $split_cnt);
            */


            if(count($Images) == 0) {
                $this->Session->setFlash(__('Uploded zip file doesnot contain any digital product.', true));
                $this->redirect(array('controller' => 'products','action'=>'bulkuploadimage'));
                exit();
            }

            foreach($Images as $img) {

                if($img <> "Thumbs.db") {

                    $pimname	=	substr($img,0,mb_strrpos($img,"."));

                    $parray		=	array();

                    //$criteria ="Product.pname  LIKE '".addslashes($pimname)."%'";
                    //$parray = $this->Product->find($criteria);

                $parray = $this->Product->find('first', array('conditions' => array('Product.pname  LIKE ' => "%".addslashes($pimname)."%")));

                  //$parray = $this->Product->find('first', array('conditions' => array('Product.pdctfile  LIKE ' => "".mysql_real_escape_string($img)."%")));
                   
                    //print '<pre />';print_r($parray);
                  // echo $img;exit;
                    if(isset($parray["Product"]["id"]) && $parray["Product"]["id"] <> 0) {

                        $prd = array();
                        $prd["Product"]["id"]	=	$parray["Product"]["id"];
                        $prd["Product"]["status"]	=	'A';
                        
                         $prd["Product"]["pdctfile"]	=	$img;
                        
                        
                        if(trim($prd["Product"]["id"]) != "" &&trim($prd["Product"]["id"])!= "0") {
                            $this->Product->save($prd);
                        }

                        /*$pro	=	array();

						$pro["Productimages"]["product_id"]	=	$parray["Product"]["id"];

						$pro["Productimages"]["imagename"]	=	$img;

						$pro["Productimages"]["default"]		=	"N";

						$this->Productimages->create();

						$this->Productimages->save($pro);*/

                        /*$path	=	WWW_ROOT.IMAGES_URL.'products/';

						rename($image_file_path."/".$img, $path.$img);

						$this->Product->resizeImg( $path."/".$img, 125 ,125, false, 100, 0,"_thumb");

						$this->Product->resizeImg( $path."/".$img, 245 ,175, false, 100, 0,"_disp");*/
                        /*$updatedigitalfile = array("id"=>$parray["Product"]["id"],
                                                   "pdctfile" => "" );
                                               $this->Product->save();*/
                        $path	=	WWW_ROOT.IMAGES_URL.'products/';

                        rename($image_file_path."/".$img, $path.$img);

                        $error	=	"Digital product uploaded successfully";

                    }else {
                        
                         if(file_exists($image_file_path."/".$img)) {

                            unlink($image_file_path."/".$img);

                        }
                        if(file_exists($image_file_path)) {

                        if($image_file_path <> WWW_ROOT.IMAGES_URL.'csv/') {

                            rmdir($image_file_path);

                        }

                        }
                        $this->Session->setFlash(__('The product name matching file name does not exist!.', true));
                        
                        $this->redirect(array('controller' => 'products','action'=>'bulkuploaddigitalproductfiles'));
                        exit();
                    }

                    #mb_strrpos(".",$img)."<br>";



                }

                if(file_exists($image_file_path."/".$img)) {

                    unlink($image_file_path."/".$img);

                }
            }
            //  echo '<br>'.$error;

            if(file_exists($image_file_path)) {

                if($image_file_path <> WWW_ROOT.IMAGES_URL.'csv/') {

                    rmdir($image_file_path);

                }

            }

        }


        if(isset($error)) {

            $this->Session->setFlash(__($error, true));

        }

        //$this->redirect(array('controller' => 'admins','action'=>'index'));
        $this->redirect(array('controller' => 'products','action'=>'bulkuploaddigitalproductfiles'));
        exit;



    }
//*************Digital file uplod ends******


    function bulkdelete() {
        $this->__validateLoginStatus();
        $admsess	=	$this->Session->read('Admin');
        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }
        $this->Product->delpdctbulk();
        $this->Session->setFlash(__('All Products Removed from Database.', '/products'));
        $this->redirect('index');
    }



    function samplecsv() {
        $this->__validateLoginStatus();
        $admsess	=	$this->Session->read('Admin');
        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }

        $csvdat	=	file_get_contents("test.csv");
        header("Content-type: application/octet-stream");
        header("Content-Transfer-Encoding: binary");
        header("Content-Disposition: attachment; filename=\"sample.csv\"");
        echo $csvdat;
        exit;
    }

    function digitalsamplecvs() {
        $this->__validateLoginStatus();
        $admsess	=	$this->Session->read('Admin');
        if($admsess["products"] <> 1) {
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }

        $csvdat	=	file_get_contents("digital_samplecvs.csv");
        header("Content-type: application/octet-stream");
        header("Content-Transfer-Encoding: binary");
        header("Content-Disposition: attachment; filename=\"sample.csv\"");
        echo $csvdat;
        exit;
    }



    function prodlist() {
        $sus	=	$this->Session->read('Userlog');
        if(isset($sus) && empty($sus)===false) {
            $this->set('sus', $sus);
        }
        global $currency;
        $curr		=	$this->Currency->findByCode($currency);
        $this->set('curlogo',$curr["Currency"]["logo"]);
        $data = $this->paginate('Product', array('Product.status  = ' => "A"));
        for($c=0; $c < sizeof($data); $c++) {
            if(isset($data[$c]["Productimages"][0]["imagename"])) {
                $defimg	=	$data[$c]["Productimages"][0]["imagename"];
                for($m=0; $m < sizeof($data[$c]["Productimages"]); $m++) {
                    if($data[$c]["Productimages"][$m]["default_img"] == "Y") {
                        $defimg	=	$data[$c]["Productimages"][$m]["imagename"];
                    }
                }
                $data[$c]["Productimages"]	=	$defimg;
            }
            else {
                $data[$c]["Productimages"]	= '';
            }

            $data[$c]["Product"]["sellprice"]=$data[$c]["Product"]["wholesale_price"];
        }
        $this->set('product', $data);
    }


    function checksubcat($id='') {
        Configure::write('debug', 0);
        $this->layout = null;
        $cval	=	$this->Category->find('all', array('conditions' => array('Category.parent_id ='.$id)));
        $this->set('cval', $cval);
    }
}
?>