<?php

/**
 * This is the model class for table "{{_product}}".
 *
 * The followings are the available columns in table '{{_product}}':
 * @property string $id
 * @property string $product_name
 * @property string $product_image
 * @property string $user_group_id
 * @property string $product_category_id
 * @property string $product_group_id
 * @property string $isIntoPromotion
 * @property string $rewardPoints
 * @property string $promotionFrom
 * @property string $isFeaturedItem
 * @property string $specifications
 * @property string $overview
 * @property string $description
 * @property string $created
 * @property string $isActive
 * @property string $isDelete
 *
 * The followings are the available model relations:
 * @property ProductGroup $productGroup
 * @property UserGroup $userGroup
 * @property ProductCategory $productCategory
 * @property ProductDownloadableRealation[] $productDownloadableRealations
 * @property ProductFeatureRelation[] $productFeatureRelations
 * @property Resource[] $resources
 */
class Product extends CActiveRecord {

    public $category_search_groupname;
    public $productCategory_search_categoryname;
    public $productGroup_search_groupname;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{_product}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
      /*   return array(
            array('product_name, product_generic_name, product_image, user_group_id, product_category_id, product_group_id, specifications, overview, description', 'required'),
            array('product_image', 'file', 'types' => 'jpg, jpeg, gif, png', 'allowEmpty' => true,),
            array('product_image', 'file', 'types' => 'jpg, jpeg, gif, png', 'allowEmpty' => true, 'on' => 'update'), // this will allow empty field when page is update (remember here i create scenario update)
            array('product_name, product_image, rewardPoints', 'length', 'max' => 255),
            array('user_group_id, product_category_id, product_group_id, type_id, promotionFrom, promotionTo', 'length', 'max' => 20),
            array('isIntoPromotion, isFeaturedItem, isActive, isDelete', 'length', 'max' => 1),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, product_name, product_generic_name, product_image, user_group_id, 
                product_category_id, product_group_id, isIntoPromotion, rewardPoints, 
                promotionFrom, promotionTo, isFeaturedItem, specifications, overview,
                description, created, isActive, isDelete, userGroup_search_groupname, 
                productCategory_search_categoryname, productGroup_search_groupname, type_id', 'safe', 'on' => 'search'),
        ); */
    	
    	return array(
    			array('product_generic_name, product_name, main_category_id, category_id, sub_category_id, specifications, overview, description,product_image', 'required'),
    			array('main_category_id, category_id, sub_category_id, product_category_id, product_sub_category_id', 'numerical', 'integerOnly' => true),
    			array('product_generic_name, product_name, product_image, rewardPoints', 'length', 'max' => 100),
    			array('isIntoPromotion, isActive, isDelete', 'length', 'max' => 1),
    			// The following rule is used by search().
    			// @todo Please remove those attributes that should not be searched.
    			array('id, product_generic_name, product_name, product_image, main_category_id, category_id, sub_category_id, product_category_id, product_sub_category_id, isIntoPromotion, rewardPoints, promotionFrom, promotionTo, specifications, overview, description, created, isActive, isDelete', 'safe', 'on' => 'search'),
    	);
    	
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        
    	return array(
    			'maincategory' => array(self::BELONGS_TO, 'MainCategory', 'main_category_id'),
    			'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
    			'subcategory' => array(self::BELONGS_TO, 'Subcategory', 'sub_category_id'),
    			'productcategory' => array(self::BELONGS_TO, 'ProductCategory', 'product_category_id'),
    			'productsubcategory' => array(self::BELONGS_TO, 'ProductSubCategory', 'product_sub_category_id'),
    			'productfeaturerelation' => array(self::HAS_MANY, 'ProductFeatureRelation', 'product_id'),
    			'productdownloadrelation' => array(self::HAS_MANY, 'ProductDownloadableRelation', 'product_id'),
    			'productimages' => array(self::HAS_MANY, 'ProductImages', 'product_id'),
    			'productMapping' => array(self::HAS_MANY, 'ProductMapping', 'product_id'),
    	);
    	
       /*  return array(
            'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
        	'subcategory' => array(self::BELONGS_TO, 'SubCategory', 'sub_category_id'),
            'productCategory' => array(self::BELONGS_TO, 'ProductCategory', 'product_category_id'),
            'productType' => array(self::BELONGS_TO, 'ProductType', 'type_id'),
            'productMap' => array(self::HAS_MANY, 'ProductMapping', 'product_id'),
            'ProductDownloadableRelation' => array(self::HAS_MANY, 'ProductDownloadableRelation', 'product_id'),
            'productFeatureRelations' => array(self::HAS_MANY, 'ProductFeatureRelation', 'product_id'),
            'productMapping' => array(self::HAS_MANY, 'ProductMapping', 'product_id'),
            'resources' => array(self::HAS_MANY, 'Resource', 'product_id'),
        ); */
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'product_generic_name' => 'Product Generic Name',
            'product_name' => 'Product Name',
            'product_image' => 'Product Image',
            'user_group_id' => 'User Group',
            'product_category_id' => 'Product Category',
            'product_group_id' => 'Product Group',
            'type_id' => 'Product Type',
            'isIntoPromotion' => 'Add to Promotion',
            'rewardPoints' => 'Reward Points',
            'promotionFrom' => 'Promotion From',
            'promotionTo' => 'Promotion To',
            'isFeaturedItem' => 'Add to Featured Item',
            'specifications' => 'Specifications',
            'overview' => 'Overview',
            'description' => 'Description',
            'created' => 'Created',
            'isActive' => 'Is Active',
            'isDelete' => 'Is Delete',
            'userGroup_search_groupname' => 'User Group',
            'productCategory_search_categoryname' => 'category',
            'productGroup_search_groupname' => 'Product Group',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
   /*  public function search() {
        //die('here'.$this->productCategory_search_categoryname);
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->with = array('productGroup', 'userGroup', 'productCategory', 'productMap' => array('select' => 'productMap.product_group_id', 'together' => true));

        /* $criteria->compare('id',$this->id,true);

          $criteria->compare('product_name',$this->product_name,true);
          $criteria->compare('product_generic_name',$this->product_generic_name,true);
          $criteria->compare('product_image',$this->product_image,true);
          $criteria->compare('type_id',$this->type_id,true);
          $criteria->compare('isIntoPromotion',$this->isIntoPromotion,true);
          $criteria->compare('rewardPoints',$this->rewardPoints,true);
          $criteria->compare('promotionFrom',$this->promotionFrom,true);
          $criteria->compare('promotionTo',$this->promotionTo,true);
          $criteria->compare('isFeaturedItem',$this->isFeaturedItem,true);
          $criteria->compare('specifications',$this->specifications,true);
          $criteria->compare('overview',$this->overview,true);
          $criteria->compare('description',$this->description,true);
          $criteria->compare('created',$this->created,true);
          $criteria->compare('isActive',$this->isActive,true);
          $criteria->compare('isDelete',$this->isDelete,true); */
        //$criteria->compare('userGroup.id',$this->userGroup_search_groupname);
        //$criteria->compare('t.product_category_id',$this->productCategory_search_categoryname);
        //$criteria->compare('productGroup.id',$this->productGroup_search_groupname);
        //$criteria->compare('productMap.product_group_id',$this->productGroup_search_groupname,'OR');
        /*$criteria->condition = '';
        if($this->isIntoPromotion!='')
        {
            $criteria->condition != '' ? $criteria->condition .=' AND ' : '';
            $criteria->condition .= ' t.isIntoPromotion ="' . $this->isIntoPromotion . '"';
        }
        if($this->isFeaturedItem!='')
        {
            $criteria->condition != '' ? $criteria->condition .=' AND ' : '';
            $criteria->condition .= ' t.isFeaturedItem ="' . $this->isFeaturedItem . '"';
        }
        if ($this->product_name != '') {
            $criteria->condition != '' ? $criteria->condition .=' AND ' : '';
            $criteria->condition .= ' t.product_name LIKE "%' . $this->product_name . '%"';
        }
        if ($this->userGroup_search_groupname != '') {
            $criteria->condition != '' ? $criteria->condition .=' AND ' : '';
            $criteria->condition .= '( userGroup.id=' . $this->userGroup_search_groupname . ' OR productMap.user_group_id=' . $this->userGroup_search_groupname . ')';
        }
        if ($this->productGroup_search_groupname != '') {
            $criteria->condition != '' ? $criteria->condition .=' AND ' : '';
            $criteria->condition .= '( productGroup.id=' . $this->productGroup_search_groupname . ' OR productMap.product_group_id=' . $this->productGroup_search_groupname . ')';
        }
        if ($this->productCategory_search_categoryname != '') {
            $criteria->condition != '' ? $criteria->condition .=' AND ' : '';
            $criteria->condition .= '( t.product_category_id=' . $this->productCategory_search_categoryname . ' OR ((productMap.user_group_id <> 0) AND productMap.category_id=' . $this->productCategory_search_categoryname . '))';
        }
        //die($criteria->condition);


        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array('pageSize' => Yii::app()->params['defaultPageSize']),
            'sort' => array(
                'defaultOrder' => 't.id DESC',
                'attributes' => array(
                    'userGroup_search_groupname' => array(
                        'asc' => 'userGroup.id',
                        'desc' => 'userGroup.id DESC',
                    ),
                    'productCategory_search_categoryname' => array(
                        'asc' => 'productCategory.id',
                        'desc' => 'productCategory.id DESC',
                    ),
                    'productGroup_search_groupname' => array(
                        'asc' => 'productGroup.id',
                        'desc' => 'productGroup.id DESC',
                    ),
                    '*',
                ),
            ),
        ));
    }*/
    
    public function search() {
    	// @todo Please modify the following code to remove attributes that should not be searched.
    
    	$search = trim(Yii::app()->request->getParam('searchterm'));
    	 
    	$criteria = new CDbCriteria;
    
    	$criteria->with = array('maincategory', 'category','productcategory');
    
    	$criteria->compare('id', $this->id);
    	$criteria->compare('product_generic_name', $this->product_generic_name, true);
    	$criteria->compare('product_name', $this->product_name, true);
    	$criteria->compare('product_image', $this->product_image, true);
    	$criteria->compare('main_category_id', $this->main_category_id);
    	$criteria->compare('category_id', $this->category_id);
    	$criteria->compare('sub_category_id', $this->sub_category_id);
    	$criteria->compare('product_category_id', $this->product_category_id);
    	$criteria->compare('product_sub_category_id', $this->product_sub_category_id);
    	$criteria->compare('isIntoPromotion', $this->isIntoPromotion, true);
    	$criteria->compare('rewardPoints', $this->rewardPoints, true);
    	$criteria->compare('promotionFrom', $this->promotionFrom, true);
    	$criteria->compare('promotionTo', $this->promotionTo, true);
    	$criteria->compare('specifications', $this->specifications);
    	$criteria->compare('overview', $this->overview, true);
    	$criteria->compare('description', $this->description, true);
    	$criteria->compare('created', $this->created, true);
    	$criteria->compare('isActive', $this->isActive, true);
    	$criteria->compare('isDelete', $this->isDelete, true);
    
    	if (!empty($search)) {
    		$criteria->addCondition('t.product_name like "%' . $search . '%" OR t.product_generic_name like "%' . $search . '%" OR productsubcategory.product_sub_category like "%' . $search . '%" OR maincategory.main_category like "%' . $search . '%" OR category.category like "%' . $search . '%" OR subcategory.sub_category like "%' . $search . '%" OR productcategory.product_category like "%' . $search . '%"', 'AND');
    	}
    	
    	/* $data = new CActiveDataProvider($this, array(
    			'criteria' => $criteria,
    			'pagination'=>array(
    					'pageSize'=>10,
    					'pageVar'=>'custom-page-selector', //page selector
    			),
    	));
    	
    	 echo '<pre>';
    	print_r($data->data);
    	exit;  */
    
    	return new CActiveDataProvider($this, array(
    			'criteria' => $criteria,
    			'pagination'=>array(
    					'pageSize'=>10,
    					'pageVar'=>'custom-page-selector', //page selector
    			),
    	));
    }

    public function getPromotioanlProducts() {
        $condition = 'isActive =  "Y"';
        $condition .= ' AND isIntoPromotion =  "Y"';
        $model = self::model()->findAll(array('condition' => $condition, 'order' => 'id'));
        return CHtml::listData($model, 'id', 'product_name');
    }

    //Get Category(s)
    //param group id, returning model
    public function getProduct($category_id = 0, $sub_category_id = 0, $product_category_id = 0, $getAll = false, $type = null) {
        $condition = 'isActive =  "Y"';
        if ($type != null) {
            switch ($type) {
                case 'isIntoPromotion':
                    $condition .= ' AND isIntoPromotion =  "Y"';
                    break;
                case 'isFeaturedItem':
                    $condition .= ' AND isFeaturedItem =  "Y"';
                    break;
            }
        }
        if ((int) $category_id > 0 || (int) $sub_category_id > 0 || (int) $product_category_id > 0) {
            if ((int) $category_id > 0)
                $condition .= ' AND category_id =  ' . (int) $category_id;
            if ((int) $product_group_id > 0)
                $condition .= ' AND sub_category_id =  ' . (int) $sub_category_id;
            if ((int) $product_category_id > 0)
                $condition .= ' AND product_category_id =  ' . (int) $product_category_id;
            $model = Product::model()->findAll(array('condition' => $condition, 'order' => 'id'));
            return CHtml::listData($model, 'id', 'product_name');
        }
        if ($getAll) {
            $model = Product::model()->findAll(array('condition' => $condition, 'order' => 'id'));
            return CHtml::listData($model, 'id', 'product_name');
        }
        return array();
    }

}