<?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>                      |

// +----------------------------------------------------------------------+

class Product extends AppModel {



    var $name = 'Product';



    var $belongsTo = 'Category';



    var $hasMany = array('Productcustomfields','Productimages');


    var $validateFile = array(
            //'size' => 204800,
            'size' => 204800,
            'type' => 'jpg,pjpeg,jpeg,png,gif,zip,pdf,rar,psd,opf,azw,lit,pdb,pkg,mp3,mpeg,mp4,avi,octet-stream'
    );







    function generateUniqueFilename($fileName, $path='') {
        $fileExt = explode('.', $fileName);
        $fcount = count($fileExt);
        if($fcount > 1) {
            $fileExtention = $fileExt[$fcount -1];
            $fileName = "VC".time().".".$fileExtention;
        }

        $path = empty($path) ? WWW_ROOT.IMAGES_URL.'products/' : $path;



        $no = 1;



        $newFileName = $fileName;



        while (file_exists("$path/".$newFileName)) {



            $no++;



            $newFileName = substr_replace($fileName, "_$no.", strrpos($fileName, "."), 1);



        }



        return $newFileName;



    }



    function handleFileUpload($fileData, $fileName) {



        $error = false;



        //Get file type



        $typeArr = explode('/', $fileData['type']);



        //If size is provided for validation check with that size. Else compare the size with INI file



        if (($this->validateFile['size'] && $fileData['size'] > $this->validateFile['size']) || $fileData['error'] == UPLOAD_ERR_INI_SIZE) {



            $error = 'The Image File "'.$fileName.'" is too large to upload';



        }



        elseif ($this->validateFile['type'] && (strpos($this->validateFile['type'], strtolower($typeArr[1])) === false)) {



            //File type is not the one we are going to accept. Error!!



            $error = 'Invalid file type';



        }



        else {



            //Data looks OK at this stage. Let's proceed.



            if ($fileData['error'] == UPLOAD_ERR_OK) {



                //Oops!! File size is zero. Error!



                if ($fileData['size'] == 0) {



                    $error = 'Zero size file found.';



                }



                else {



                    if (is_uploaded_file($fileData['tmp_name'])) {



                        //Finally we can upload file now. Let's do it and return without errors if success in moving.



                        if (!move_uploaded_file($fileData['tmp_name'], WWW_ROOT.IMAGES_URL.'products/'."$fileName")) {



                            $error = true;



                        }



                        $this->resizeImg(WWW_ROOT.IMAGES_URL.'products/'."$fileName", 125 ,125, false, 100, 0,"_thumb");



                        //$this->resizeImg(WWW_ROOT.IMAGES_URL.'products/'."$fileName", 245 ,175, false, 100, 0,"_thumb");



                        $this->resizeImg(WWW_ROOT.IMAGES_URL.'products/'."$fileName", 180 ,180, false, 100, 0,"_disp");


                        $this->resizeImg(WWW_ROOT.IMAGES_URL.'products/'."$fileName", 300 ,300, false, 100, 0,"_xtra");



                        //echo WWW_ROOT.IMAGES_URL.'products/'."$fileName"; exit;



                    }



                    else {



                        $error = true;



                    }



                }



            }



        }



        return $error;



    }







    function deleteMovedFile($fileName) {



        if (!$fileName || !is_file($fileName)) {



            return true;



        }



        if(unlink($fileName)) {



            return true;



        }



        return false;



    }







    function resizeImg($imgPath, $maxWidth, $maxHeight, $directOutput = true, $quality = 90, $verbose,$imageType) {



        $size = getimagesize($imgPath);



        //print_r($size);exit;



        // break and return false if failed to read image infos



        if(!$size) {



            if($verbose && !$directOutput)echo "<br />Not able to read image infos.<br />";







            return false;



        }



        // relation: width/height



        $relation = $size[0]/$size[1];



        // maximal size (if parameter == false, no resizing will be made)



        $maxSize = array($maxWidth?$maxWidth:$size[0],$maxHeight?$maxHeight:$size[1]);



        // declaring array for new size (initial value = original size)



        $newSize = $size;



        // width/height relation



        $relation = array($size[1]/$size[0], $size[0]/$size[1]);



        //print_r($size);



        //echo "<br>";



        //print_r($relation);exit;



        if(($newSize[0] > $maxWidth)) {



            $newSize[0]=$maxSize[0];



            $newSize[1]=$newSize[0]*$relation[0];



        }



        if(($newSize[1] > $maxHeight)) {



            $newSize[1]=$maxSize[1];



            $newSize[0]=$newSize[1]*$relation[1];



        }
$newSize[0]=$maxSize[0];$newSize[1]=$maxSize[1];


        // create image



        $img_ext='';



        switch($size[2]) {



            case 1:



                if(function_exists("imagecreatefromgif")) {



                    $originalImage = imagecreatefromgif($imgPath);



                    $img_ext='.'.end(explode('.',$imgPath));



                }



                else {



                    if($verbose && !$directOutput)echo "<br />No GIF support in this php installation, sorry.<br />";



                    return false;



                }



                break;



            case 2:



                $originalImage = imagecreatefromjpeg($imgPath);



                $img_ext='.'.end(explode('.',$imgPath));



                break;



            case 3:



                $originalImage = imagecreatefrompng($imgPath);



                $img_ext='.'.end(explode('.',$imgPath));



                break;



            default:



                if($verbose && !$directOutput)echo "<br />No valid image type.<br />";



                return false;



        }







        // create new image



        $resizedImage = imagecreatetruecolor($newSize[0], $newSize[1]);



        imagecopyresampled($resizedImage, $originalImage,0, 0, 0, 0,$newSize[0], $newSize[1], $size[0], $size[1]);



        $rz=$imgPath;



        // output or save



        if($directOutput) {



            imagejpeg($resizedImage);



        }



        else {



            $rz=preg_replace("/\.([a-zA-Z]{3,4})$/","".$imageType.$img_ext,$imgPath);



            imagejpeg($resizedImage, $rz, $quality);



        }



        // return true if successfull



        return $rz;



    }







    #################  Function to Update Stock After Checkout Starts here(Added by Shyam) #################



    function updatecombnstock($pid,$optid,$qty) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdetailstbl = $Db->fullTableName('productdetails');



        $this->query("UPDATE $pdetailstbl SET stock = stock - ".$qty." WHERE id = ".$optid);



        return true;



    }



    function updatestock($pid,$qty) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdtbl = $Db->fullTableName('products');



        $this->query("UPDATE $pdtbl SET stock = stock - ".$qty." WHERE id = ".$pid);



        return true;



    }



    #################  Function to Update Stock After Checkout Ends here(Added by Shyam) #################







    function reorderalrt() {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdtbl = $Db->fullTableName('products');



        $cnt	=	$this->query("SELECT COUNT(*) AS cnt FROM $pdtbl WHERE stock <= reorderlevel AND status ='A'");



        return $cnt[0][0]["cnt"];



    }



    ########### Function to return maximum number of products present in the cart........................................



    function getCntPdct() {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdtbl = $Db->fullTableName('products');



        $cnt	=	$this->query("SELECT COUNT(*) AS cnt FROM $pdtbl WHERE status ='A'");



        return $cnt[0][0]["cnt"];



    }



    ############ Function to change the status of product as deleted D .............................



    function delpdct($id,$cmbn) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdtbl = $Db->fullTableName('products');



        $pdetailstbl = $Db->fullTableName('productdetails');



        $pdtimgsbl = $Db->fullTableName('productimages');



        $this->query("UPDATE $pdtbl SET status ='D', featured = '0' WHERE id= ".$id);







        //Deleting Details and Images from Product Details Tables



        if($cmbn=='Y') {



            $img_res=$this->query("SELECT pdctfile from $pdetailstbl WHERE product_id= ".$id);



            if(isset($img_res) && !empty($img_res)) {



                foreach($img_res as $img_val) {



                    $img_large='';
                    $img_thumb='';
                    $img_disp='';



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



                    $img_det=explode('.',$img_val["Vista_productdetails"]["pdctfile"]);



                    if(isset($img_det1) && !empty($img_det1)) {



                        $img_large=$img_delpath.$img_val["Vista_productdetails"]["pdctfile"];



                        $img_thumb=$img_delpath.$img_det[0].'_thumb.'.$img_det[1];



                        $img_disp=$img_delpath.$img_det[0].'_disp.'.$img_det[1];


                        $img_xtra=$img_delpath.$img_det[0].'_xtra.'.$img_det[1];



                        if(file_exists($img_large)) unlink($img_large);



                        if(file_exists($img_thumb)) unlink($img_thumb);



                        if(file_exists($img_disp)) unlink($img_disp);


                        if(file_exists($img_xtra)) unlink($img_xtra);



                    }



                }



            }



        }



        $this->query("DELETE from $pdetailstbl WHERE product_id= '".$id."'" );







        //Deleting Details and Images from Product Images Tables



        /*



            $img_res1=$this->query("SELECT imagename from $pdtimgsbl WHERE product_id= ".$id);



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



			{



			   foreach($img_res1 as $img_val1)



			   {



			     $img_large1='';$img_thumb1='';$img_disp1='';



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



			     $img_det1=explode('.',$img_val1["Vista_productimages"]["imagename"]);



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



				 {



					 $img_large1=$img_delpath1.$img_val1["Vista_productimages"]["imagename"];



					 $img_thumb1=$img_delpath1.$img_det1[0].'_thumb.'.$img_det1[1];



					 $img_disp1=$img_delpath1.$img_det1[0].'_disp.'.$img_det1[1];



					 if(file_exists($img_large1)) unlink($img_large1);



					 if(file_exists($img_thumb1)) unlink($img_thumb1);



					 if(file_exists($img_disp1)) unlink($img_disp1);



				 }



			   }



			}



        */



        $this->query("DELETE from $pdtimgsbl WHERE product_id= '".$id."'" );



        return true;



    }



    function defaultimage($id,$pid) {



        $Db 	=	ConnectionManager::getDataSource($this->useDbConfig);



        $pitbl 	= 	$Db->fullTableName('productimages');



        $this->query("UPDATE $pitbl SET `default` = 'N' WHERE `product_id` =".$pid);



        $this->query("UPDATE $pitbl SET `default` = 'Y' WHERE `id` =".$id);



        return true;



    }



    function csvUpload($fileData, $fileName,$path='') {



        $error = false;



        $path = empty($path) ? WWW_ROOT.IMAGES_URL.'products/' : $path;



        //Get file type



        $typeArr = explode('/', $fileData['type']);



        //If size is provided for validation check with that size. Else compare the size with INI file



        if (($this->validateFile['size'] && $fileData['size'] > $this->validateFile['size']) || $fileData['error'] == UPLOAD_ERR_INI_SIZE) {



            $error = 'File is too large to upload';



        }







        else {



            //Data looks OK at this stage. Let's proceed.



            if ($fileData['error'] == UPLOAD_ERR_OK) {



                //Oops!! File size is zero. Error!



                if ($fileData['size'] == 0) {



                    $error = 'Zero size file found.';



                }



                else {



                    if (is_uploaded_file($fileData['tmp_name'])) {



                        //Finally we can upload file now. Let's do it and return without errors if success in moving.



                        if (!move_uploaded_file($fileData['tmp_name'], $path."$fileName")) {



                           $error = 'Unable to move file';



                        }











                    }



                    else {



                        $error = true;



                    }



                }



            }



        }



        return $error;



    }



    function delpdctbulk() {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdtbl = $Db->fullTableName('products');



        $this->query("UPDATE $pdtbl SET status ='D', featured = 0 ");



        return true;



    }















    ###############  Function to Upload Product Images starts here(Added by Shyam)	#################



    function addProductImages($productid,$pdctimage,$default) {

        $pdctimage = addslashes($pdctimage);
        $default  = addslashes($default);

        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodimgstbl = $Db->fullTableName('productimages');



        $this->query("INSERT into $prodimgstbl(product_id,imagename,default_img) values('".$productid."','".$pdctimage."','".$default."')");



        return true;



    }



    #################  Function to  Upload Product Images  Ends here(Added by Shyam) #################







    function updateProductImages($productid,$pdctimage,$default,$updateid) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodimgstbl = $Db->fullTableName('productimages');



        $check = $this->query("SELECT * FROM $prodimgstbl  where product_id='".$productid."'");



        if(isset($check) && empty($check)===false)



            $this->query("UPDATE $prodimgstbl SET product_id='".$productid."',imagename='".$pdctimage."',default_img='".$default."' WHERE id='".$updateid."'");



        else



        //write your insert query here



            $this->query("INSERT INTO $prodimgstbl(product_id,imagename,default_img) values('".$productid."','".$pdctimage."','".$default."')");



        if($default=='Y')



            $this->query("UPDATE $prodimgstbl set default_img='N' WHERE id<>'".$updateid."' AND product_id='".$productid."'");



        return true;



    }







    ###############  Function to Upload Product Images starts here(Added by Shyam)	#################



    function updateDefaultImage($productid,$default,$updateid) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodimgstbl = $Db->fullTableName('productimages');



        $this->query("UPDATE $prodimgstbl SET default_img='".$default."' WHERE id='".$updateid."'");



        if($default=='Y')



            $this->query("UPDATE $prodimgstbl set default_img='N' WHERE id<>'".$updateid."' AND product_id='".$productid."'");



        return true;



    }



    #################  Function to  Upload Product Images  Ends here(Added by Shyam) #################







    ###############  Function to Update category starts here(Added by Shyam)	#################



    function updateCategory($productid,$categoryid) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodtbl = $Db->fullTableName('products');



        $this->query("UPDATE $prodtbl SET category_id='".$categoryid."' WHERE id='".$productid."'");



        return true;



    }



    #################  Function to Update category  Ends here(Added by Shyam) #################











    #################  Function to Add Product Combination details starts here(Added by Shyam)	#################



    function addProductCombinations($categoryid,$productid,$attributes,$stock,$reorderlevel,$skuno,$extraprice,$pdctimage) {

        $attributes = addslashes($attributes);
        $pdctimage = addslashes($pdctimage);
        $extraprice = addslashes($extraprice);
        $skuno = addslashes($skuno);
        $reorderlevel = addslashes($reorderlevel);
        $stock = addslashes($stock);


        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodetailstbl = $Db->fullTableName('productdetails');



        $this->query("INSERT into $prodetailstbl(category_id,product_id,customvalue_id,stock,reorderlevel,skuno,extraprice,pdctfile) values('".$categoryid."','".$productid."','".$attributes."','".$stock."','".$reorderlevel."','".$skuno."','".$extraprice."','".$pdctimage."')");



        return true;



    }



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







    #################  Function to Update Product Combination details starts here(Added by Shyam)	#################



    function updateProductCombinations($categoryid,$productid,$attributes,$stock,$reorderlevel,$skuno,$extraprice,$pdctimage,$updateid) {

        $categoryid = addslashes($categoryid);
        $productid = addslashes($productid);
        $attributes = addslashes($attributes);
        $stock = addslashes($stock);
        $reorderlevel = addslashes($reorderlevel);
        $skuno = addslashes($skuno);
        $extraprice = addslashes($extraprice);
        $pdctimage = addslashes($pdctimage);
        $updateid = addslashes($updateid);

        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodetailstbl = $Db->fullTableName('productdetails');



        $this->query("UPDATE $prodetailstbl set category_id='".$categoryid."',product_id='".$productid."',customvalue_id='".$attributes."',



			stock='".$stock."',reorderlevel='".$reorderlevel."',skuno='".$skuno."',extraprice='".$extraprice."',pdctfile='".$pdctimage."' WHERE id='".$updateid."'");



        return true;



    }



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











    #################  Function to Update Stock starts starts here(Added by Shyam)	#################



    function updateTotalStock($productid) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $prodetailstbl = $Db->fullTableName('productdetails');



        $pdtbl = $Db->fullTableName('products');



        $stk	=	$this->query("SELECT SUM(stock) AS stk FROM $prodetailstbl WHERE `product_id` =".$productid);



        $total_stock=$stk[0][0]["stk"];



        $this->query("UPDATE $pdtbl SET stock ='".$total_stock."', combination = 'Y' WHERE `id` =".$productid);



        return true;



    }



    #################  Function to Update Stock  Ends here(Added by Shyam) #################











    #################  Function to Delete a Combination of a product details starts here(Added by Shyam) #################



    function delpdctcmbn($catid,$delid) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdetailstbl = $Db->fullTableName('productdetails');



        $this->query("DELETE from $pdetailstbl  WHERE id= '".$delid."'  AND category_id='".$catid."'" );



        return true;



    }



    #################  Function to Delete a Combination of a product details starts here(Added by Shyam) #################







    #################  Function to get  product combination details on user side starts here(Added by Shyam) #################



    function getpdctcmbn($id) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $cstmfld = $Db->fullTableName('customfields');



        $cstmfldval = $Db->fullTableName('customfieldvalues');



        $res=$this->query("select $cstmfldval.id,$cstmfld.custom_name,$cstmfldval.custom_value



           FROM $cstmfldval INNER JOIN $cstmfld  ON $cstmfldval.customfield_id=$cstmfld.id



           WHERE $cstmfldval.id='".$id."'");



        $cstmfld=trim(str_replace('`','',$cstmfld));
        $cstmfldval=trim(str_replace('`','',$cstmfldval));



        // $attribute=ucwords($res[0]["$cstmfld"]["custom_name"])." : ".ucwords($res[0]["$cstmfldval"]["custom_value"]);



        $attribute=ucwords($res[0]["$cstmfldval"]["custom_value"]);



        return $attribute;



    }



    #################  Function to get  product combination details on user side ends here(Added by Shyam) #################







    #################  Function to Delete a All the Combination of a product starts here(Added by Shyam) #################



    /*



	    function delpdctcombinations($prodid){



			$Db = ConnectionManager::getDataSource($this->useDbConfig);



			$pdetailstbl = $Db->fullTableName('productdetails');



			$this->query("DELETE from $pdetailstbl  WHERE product_id= '".$prodid."'" );



			return true;



		}



    */



    #################  Function to Delete a Combination of a product details starts here(Added by Shyam) #################







    #################  Function to get combination product images starts here(Added by Shyam) #################



    function getcombnimages($cmbnid) {



        $Db = ConnectionManager::getDataSource($this->useDbConfig);



        $pdetailstbl = $Db->fullTableName('productdetails');



        $res=$this->query("SELECT extraprice,skuno,pdctfile from $pdetailstbl  WHERE id= '".$cmbnid."'" );



        $tblname=trim(str_replace('`','',$pdetailstbl));



        return $res[0][$tblname];



    }



    #################  Function to get combination product images ends here(Added by Shyam) #################

    function threshold_breached($prd_id) {

        $Db = ConnectionManager::getDataSource($this->useDbConfig);

        $pdtbl = $Db->fullTableName('products');

        $cnt	=	$this->query("SELECT COUNT(*) AS cnt FROM $pdtbl WHERE stock <= reorderlevel AND id = ".$prd_id);

        return $cnt[0][0]["cnt"];

    }

    /*
     * Function to Auto Load Field
     */
    function productDetails(){
     

        $Db = ConnectionManager::getDataSource($this->useDbConfig);

        $pTbl = $Db->fullTableName('products');
        $cTbl = $Db->fullTableName('categories');
        $piTbl = $Db->fullTableName('productimages');
        $pdTbl = $Db->fullTableName('productdetails');
        $cvTbl = $Db->fullTableName('customfieldvalues');
        $cfTbl = $Db->fullTableName('customfields');

        $selPd = "SELECT p.id, p.pname, p.category_id, p.descr, p.price, p.wholesale_price, p.discount_type, p.discount,
                    p.image1, p.image2, p.featured, p.stock, p.skuno, p.reorderlevel, p.weight, p.shipping_price,p.status,
                    p.pdctfile, p.prodtype, p.combination,
                    c.cname,
                    pi.imagename, pi.default_img,
                    pd.id, pd.stock, pd.reorderlevel, pd.skuno, pd.extraprice, pd.pdctfile,
                    cv.custom_value,
                    cf.custom_name FROM $pTbl as p LEFT JOIN $cTbl as c ON p.category_id = c.id
                    LEFT JOIN $piTbl pi ON (p.id = pi.product_id AND pi.default_img = 'Y')
                    LEFT JOIN $pdTbl pd ON p.id = pd.product_id
                    LEFT JOIN $cvTbl cv ON pd.customvalue_id = cv.id
                    LEFT JOIN $cfTbl cf ON cv.customfield_id = cf.id";
        
        $dataArr = $this->query($selPd);
               
        return $dataArr;
    } // End Function

    

    function formatToPrice($number){
        $formatedNumber  = NULL;
        $number = (!empty($number)) ? $number : 0;
        $formatedNumber  = number_format($number, 2, '.', '');
        
        return $formatedNumber;

    } //End Function

}



?>