<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ModProduct extends Module {
    protected $_filters = array(
        'check_login' => '{newprd}{prdlist}{view}{recmndprd}'
    );
    
    private $stack = array();
    private $findout = array();
    
    public function newprd() {
        $list_size = trim(ParamHolder::get('prd_newlst_size'));
        $show_price = trim(ParamHolder::get('prd_newlst_price'),'0');
        if (!is_numeric($list_size) || strlen($list_size) == 0) {
            $list_size = '5';
        }
        $cap_id = trim(ParamHolder::get('prd_newlst_cap_id', '0'));
        $p_cols = trim(ParamHolder::get('prd_newlst_d', '1'));
        $this->assign('p_cols', $p_cols);
        $this->assign('show_price', $show_price);

        $ret = $this->_getNewPrds($list_size, $cap_id);
        if ($ret) {
            return $ret;
        }

        return 'newprd';
    }

    public function recmndprd() {
        $list_size = trim(ParamHolder::get('prd_recmndlst_size'));
        $show_price = trim(ParamHolder::get('prd_recmndlst_price'));
        if (!is_numeric($list_size) || strlen($list_size) == 0) {
            $list_size = '5';
        }
        $cap_id = trim(ParamHolder::get('prd_recmndlst_cap_id', '0'));
        $p_cols = trim(ParamHolder::get('prd_recmndlst_d', '1'));
        $this->assign('p_cols', $p_cols);
        $this->assign('show_price', $show_price);

        $ret = $this->_getRecmndPrds($list_size, $cap_id);
        if ($ret) {
            return $ret;
        }

        return 'newprd';
    }

    public function prdlist() {
    	$this->_layout = 'frontpage';

        // The default product category
        $curr_product_category = new ProductCategory();
        $curr_product_category->name = __('All Products');

        $cap_id = trim(ParamHolder::get('cap_id', '0'));
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        $curr_locale = trim(SessionHolder::get('_LOCALE'));

        $search_where = '';
        $search_params = array();
        $prd_keyword = trim(ParamHolder::get('prd_keyword', ''));
        if (strlen($prd_keyword) > 0) {
            $search_where .= ' AND (name LIKE ? OR description LIKE ?)';
            $search_params = array_merge($search_params,
            	array('%'.$prd_keyword.'%', '%'.$prd_keyword.'%'));
            $this->assign('prd_keyword', $prd_keyword);
        }// 02/06/2010 Edit >>
        else if (intval($cap_id) > 1) {
        //if (intval($cap_id) > 1) {
        // 02/06/2010 Edit <<
        	$product_category = new ProductCategory();
    		$product_categories = $product_category->findAll();
    		if(empty($product_categories)) $product_categories = array();
    		foreach($product_categories as $k => $v)
    		{
    			$this->stack[$v->id] = $v->product_category_id;
    		}
    		$this->findout[] = $cap_id;
    		$this->getCategoryList();
    		$search_where = " AND product_category_id IN (''";
    		foreach($this->findout as $k => $v)
    		{
    			$search_where .= ",$v";
    		}
    		$search_where .= ') AND product_category_id <> 0';
            $curr_product_category = new ProductCategory($cap_id);
        }

        try {
            $now = time();
            /**
             * Add 02/08/2010
             */
            include_once(P_LIB.'/pager.php');
            
            if ($user_role == '{admin}') {
	            $product_data =&
	                Pager::pageByObject('Product',
	                    "((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND s_locale=?".$search_where,
	                    array_merge(
	                    	array($now, $now, $now, $now, $curr_locale),
	                    	$search_params),
	                    "ORDER BY `i_order` DESC, `create_time` DESC");
            } else {
	            $product_data =&
	                Pager::pageByObject('Product',
	                    "((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND for_roles LIKE ? AND s_locale=?".$search_where,
	                    array_merge(
	                    	array($now, $now, $now, $now, '%'.$user_role.'%', $curr_locale),
	                    	$search_params),
	                    "ORDER BY `i_order` DESC, `create_time` DESC");
            }

            $this->assign('page_title', $curr_product_category->name);

            $this->assign('category', $curr_product_category);
            $this->assign('products', $product_data['data']);
            $this->assign('pager', $product_data['pager']);
            $this->assign('prd_keyword', $prd_keyword);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }
    }

    /** temporarily disabled **/
    /*
    public function newshow() {
        $list_size = trim(ParamHolder::get('prd_newshow_size', '3'));
        $cap_id = trim(ParamHolder::get('prd_newshow_cap_id', '0'));

        return $this->_getNewPrds($list_size, $cap_id);
    }

    public function recmndshow() {
        $list_size = trim(ParamHolder::get('prd_recmndshow_size', '3'));
        $cap_id = trim(ParamHolder::get('prd_recmndshow_cap_id', '0'));

        return $this->_getRecmndPrds($list_size, $cap_id);
    }
    */

    public function view() {
    	$this->_layout = 'frontpage';

        $p_id = ParamHolder::get('p_id', '0');
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        // bugfree 379
        if ((intval($p_id) == 0) || !preg_match("/^\d+$/i", $p_id)) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        try {
            $now = time();
            $o_product = new Product();
            if ($user_role == '{admin}') {
	            $curr_product =& $o_product->find("`id`=? AND "
	                        ."((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND s_locale=?",
	                    array($p_id, $now, $now, $now, $now, $curr_locale));
            } else {
	            $curr_product =& $o_product->find("`id`=? AND "
	                        ."((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND for_roles LIKE ? AND s_locale=?",
	                    array($p_id, $now, $now, $now, $now, '%'.$user_role.'%', $curr_locale));
            }
            $curr_product->loadRelatedObjects(REL_PARENT, array('ProductCategory'));
            $this->assign('page_title', $curr_product->name);
            $this->assign('curr_product', $curr_product);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }
    }


    private function _getNewPrds($list_size, $cap_id) {
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        $curr_locale = trim(SessionHolder::get('_LOCALE'));

        $where = '';
        $params = array();
        if (intval($cap_id) > 1) {
        	// 02/06/2010 Edit >>
        	$childids = $this->getCategoryChildIds($cap_id, $curr_locale);
        	$cap_id = !empty($childids) ? $childids.$cap_id : $cap_id;
        	//$where = " AND product_category_id=?";
        	$where = " AND product_category_id IN(".$cap_id.")";
        	//$params = array($cap_id);
        	$params = array();
        	// 02/06/2010 Edit <<
        }
        try {
            $o_product = new Product();
            $now = time();
            if ($user_role == '{admin}') {
	            $products =&
	                $o_product->findAll("((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND s_locale=?".$where,
	                    array_merge(
	                    	array($now, $now, $now, $now, $curr_locale),
	                    	$params),
	                    "ORDER BY `i_order` DESC,`create_time` DESC LIMIT ".$list_size);
            } else {
	            $products =&
	                $o_product->findAll("((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND for_roles LIKE ? AND s_locale=?".$where,
	                    array_merge(
	                    	array($now, $now, $now, $now, '%'.$user_role.'%', $curr_locale),
	                    	$params),
	                    "ORDER BY `i_order` DESC,`create_time` DESC LIMIT ".$list_size);
            }
            $this->assign('products', $products);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

        return false;
    }

    private function _getRecmndPrds($list_size, $cap_id) {
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        $curr_locale = trim(SessionHolder::get('_LOCALE'));

        $where = '';
        $params = array();
        if (intval($cap_id) > 1) {
            // 02/06/2010 Edit >>
        	$childids = $this->getCategoryChildIds($cap_id, $curr_locale);
        	$cap_id = !empty($childids) ? $childids.$cap_id : $cap_id;
        	//$where = " AND product_category_id=?";
        	$where = " AND product_category_id IN(".$cap_id.")";
        	//$params = array($cap_id);
        	$params = array();
        	// 02/06/2010 Edit <<
        }
        try {
            $o_product = new Product();
            $now = time();
            if ($user_role == '{admin}') {
	            $products =&
	                $o_product->findAll("((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND s_locale=? AND "
	                        ."recommended='1'".$where,
	                    array_merge(
	                    	array($now, $now, $now, $now, $curr_locale),
	                    	$params),
	                    "ORDER BY `i_order` DESC,`create_time` DESC LIMIT ".$list_size);
            } else {
	            $products =&
	                $o_product->findAll("((`pub_start_time`<? AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
	                        ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
	                        ."published='1' AND for_roles LIKE ? AND s_locale=? AND "
	                        ."recommended='1'".$where,
	                    array_merge(
	                    	array($now, $now, $now, $now, '%'.$user_role.'%', $curr_locale),
	                    	$params),
	                    "ORDER BY `i_order` DESC,`create_time` DESC LIMIT ".$list_size);
            }
            $this->assign('products', $products);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

        return false;
    }
    
    public function getCategoryList()
    {
    	$i = $j = count($this->stack);
    	$flag = true;
    	while(($j < $i) || $flag)
    	{
	    	$i = $j;
    		foreach($this->stack as $k => $v)
	    	{
	    		if(in_array($v,$this->findout))
	    		{
	    			$this->findout[] = $k;
	    			unset($this->stack[$k]);
	    		}
	    	}
	    	$j = count($this->stack);
	    	$flag = false;
    	}
    }
    
    // 02/06/2010 Add >>
    private function getCategoryChildIds( $parentid, $curr_locale )
    {
    	$product_childcategories = array();
    	$product_category = new ProductCategory();
    	$product_childcategories = $product_category->findAll("product_category_id = '{$parentid}' AND s_locale = '{$curr_locale}'");
    	
    	$childids = '';
    	if ( count($product_childcategories) ) {
    		foreach( $product_childcategories as $val )
    		{
				$childids .= $val->id.',';
				$childids .= $this->getCategoryChildIds($val->id, $curr_locale);
    		}
    	}
    	
    	return $childids;
    }
    // 02/06/2010 Add <<
}
?>
