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

class ModMenuItem extends Module {
	
	protected $_filters = array(
        'check_admin' => '{getId}'
    );
	
    public function admin_add() {
        $this->_layout = 'content';

        $menu_id = ParamHolder::get('menu_id', 0);
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $this->assign('content_title', __('New Menu Item'));
        $this->assign('next_action', 'admin_create');

//        $all_mis =& MenuItem::listMenuItems(0, "menu_id=? AND s_locale=? AND menu_item_id=?",
//            array($menu_id, $mod_locale, 0));
		$all_mis = & MenuItem::listMenuItems(0, "menu_id=? AND s_locale=?",
                array($menu_id,$mod_locale));
        $select_mis = array();
        MenuItem::toSelectArray($all_mis, $select_mis,
                0, array(), array('0' => __('Top Level')));

        $this->assign('menu_id', $menu_id);
        $this->assign('select_mis', $select_mis);
        $this->assign('mod_locale', $mod_locale);
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());
        include_once(P_INC.'/menus.php');
        $menuitems = MenuItem::toSectionArray($menus);
        $this->assign('menus', $menuitems);

        //return '_form';
    }

    public function admin_create() {
        $tmp_id = trim(ParamHolder::get('tmp_id', ''));
        $mi_info =& ParamHolder::get('mi', array());
        if (sizeof($mi_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing menu item information!')));
            return '_result';
        }
        $is_member_only = ParamHolder::get('ismemonly', '0');
        try {
            include_once(P_INC.'/menus.php');
            $tmplink == '';
            $link_type_parts = explode('|', $mi_info['link_type']);
            $mi_info['mi_category'] = $link_type_parts[0];
            if($mi_info['mi_category'] == 'outer_url') {
                $tmplink = $tmp_id;
            } else if(empty($tmp_id)) {
                $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'];
                // Hard code for "Company Introduction" and "Contact Us"
                if ($mi_info['mi_category'] == 'company_info') {
                    if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                        $sc_id = '2';
                    else
                        $sc_id = '4';
                    $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                } else if ($mi_info['mi_category'] == 'contact_info') {
                    if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                        $sc_id = '1';
                    else
                        $sc_id = '3';
                    $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                } // End : Hard code
            } else {
                $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'].'&'.$menus[$mi_info['mi_category']]['id_category'].'='.$tmp_id;
            }
			$mi_info['link'] = $tmplink;
            // Re-arrange publish status
            /*
            if ($mi_info['published'] == '1') {
                $mi_info['published'] = '1';
            } else {
                $mi_info['published'] = '0';
            }
            */
            $mi_info['published'] = '1';
            $mi_info['for_roles'] = ACL::explainAccess(intval($is_member_only));
            // Calculate order
            $mi_info['i_order'] =
                MenuItem::getMaxOrder($mi_info['menu_item_id']) + 1;

            // Data operation
            $o_mi = new MenuItem();
            $o_mi->set($mi_info);
            $o_mi->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }

        $this->assign('json', Toolkit::jsonOK(array('forward' => Html::uriquery('mod_menu_item', 'admin_list', array("menu_id" => $mi_info['menu_id'])))));
        return '_result';
    }

    public function admin_edit() {
        $this->_layout = 'content';

        $mi_id = ParamHolder::get('mi_id', '0');
        if (intval($mi_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }

        try {
            $curr_mi = new MenuItem($mi_id);
            $this->assign('curr_mi', $curr_mi);

//            $all_mis =& MenuItem::listMenuItems(0, "menu_id=? AND s_locale=? AND menu_item_id=? ",
//                array($curr_mi->menu_id, $curr_mi->s_locale, 0));
			$all_mis = & MenuItem::listMenuItems(0, "menu_id=? AND s_locale=?",
                array($curr_mi->menu_id,$curr_mi->s_locale));
            $this->assign('menu_id', $curr_mi->menu_id);
            $select_mis = array();
            MenuItem::toSelectArray($all_mis, $select_mis,
                0, array($curr_mi->id), array('0' => __('Top Level')));

            $this->assign('select_mis', $select_mis);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }


        $this->assign('content_title', __('Edit Menu Item'));
        $this->assign('next_action', 'admin_update');

        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());
        include_once(P_INC.'/menus.php');
        $menuitems = MenuItem::toSectionArray($menus);
        $this->assign('menus', $menuitems);
        return '_form';
    }
    public function admin_addsub() {
        $this->_layout = 'content';

        $menu_id = ParamHolder::get('menu_id', 0);
		$mi_id = ParamHolder::get('mi_id', '0');
        if (intval($mi_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }
		$curr_mi = new MenuItem($mi_id);
        $this->assign('curr_mi', $curr_mi);

        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $this->assign('content_title', __('New Menu Item'));
        $this->assign('next_action', 'admin_sub_create');

//        $all_mis =& MenuItem::listMenuItems(0, "menu_id=? AND s_locale=? AND menu_item_id=?",
//            array($menu_id, $mod_locale, 0));
		$all_mis = & MenuItem::listMenuItems(0, "menu_id=? AND s_locale=?",
                array($menu_id,$mod_locale));
        $select_mis = array();
        MenuItem::toSelectArray($all_mis, $select_mis,
                0, array(), array('0' => __('Top Level')));

        $this->assign('menu_id', $menu_id);
        $this->assign('select_mis', $select_mis);
        $this->assign('mod_locale', $mod_locale);
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());
        include_once(P_INC.'/menus.php');
        $menuitems = MenuItem::toSectionArray($menus);
        $this->assign('menus', $menuitems);
    }

	public function admin_sub_create() {
        $tmp_id = trim(ParamHolder::get('tmp_id', ''));
        $mi_info =& ParamHolder::get('mi', array());
        if (sizeof($mi_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing menu item information!')));
            return '_result';
        }
        $is_member_only = ParamHolder::get('ismemonly', '0');
        try {
            include_once(P_INC.'/menus.php');
            $tmplink == '';
            $link_type_parts = explode('|', $mi_info['link_type']);
            $mi_info['mi_category'] = $link_type_parts[0];
            if($mi_info['mi_category'] == 'outer_url') {
                $tmplink = $tmp_id;
            } else if(empty($tmp_id)) {
                $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'];
                // Hard code for "Company Introduction" and "Contact Us"
                if ($mi_info['mi_category'] == 'company_info') {
                    if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                        $sc_id = '2';
                    else
                        $sc_id = '4';
                    $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                } else if ($mi_info['mi_category'] == 'contact_info') {
                    if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                        $sc_id = '1';
                    else
                        $sc_id = '3';
                    $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                } // End : Hard code
            } else {
                $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'].'&'.$menus[$mi_info['mi_category']]['id_category'].'='.$tmp_id;
            }
			$mi_info['link'] = $tmplink;
            // Re-arrange publish status
            /*
            if ($mi_info['published'] == '1') {
                $mi_info['published'] = '1';
            } else {
                $mi_info['published'] = '0';
            }
            */
            $mi_info['published'] = '1';
            $mi_info['for_roles'] = ACL::explainAccess(intval($is_member_only));
            // Calculate order
            $mi_info['i_order'] =
                MenuItem::getMaxOrder($mi_info['menu_item_id']) + 1;

            // Data operation
            $o_mi = new MenuItem();
            $o_mi->set($mi_info);
            $o_mi->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }

        $this->assign('json', Toolkit::jsonOK(array('forward' => Html::uriquery('mod_menu_item', 'admin_list', array("menu_id" => $mi_info['menu_id'])))));
        return '_result';
    }
    public function admin_update() {
        $mi_info =& ParamHolder::get('mi', array());
		$tmp_id = trim(ParamHolder::get('tmp_id', ''));
        if (sizeof($mi_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing menu item information!')));
            return '_result';
        }
        $is_member_only = ParamHolder::get('ismemonly', '0');
        try {
            $link_type_parts = explode('|', $mi_info['link_type']);
            $mi_info['mi_category'] = $link_type_parts[0];

			include_once(P_INC.'/menus.php');
            // Re-arrange publish status
            /*
            if ($mi_info['published'] == '1') {
                $mi_info['published'] = '1';
            } else {
                $mi_info['published'] = '0';
            }
            */
            $mi_info['for_roles'] = ACL::explainAccess(intval($is_member_only));

            // Data operation
            $o_mi = new MenuItem($mi_info['id']);
            if ($mi_info['mi_category'] != $o_mi->mi_category) {
                if($mi_info['mi_category'] == 'outer_url') {
                    $tmplink = $tmp_id;
                } else if(empty($tmp_id)) {
                    $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'];
                    // Hard code for "Company Introduction" and "Contact Us"
                    if ($mi_info['mi_category'] == 'company_info') {
                        if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                            $sc_id = '2';
                        else
                            $sc_id = '4';
                        $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                    } else if ($mi_info['mi_category'] == 'contact_info') {
                        if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                            $sc_id = '1';
                        else
                            $sc_id = '3';
                        $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                    } // End : Hard code
                } else {
                    $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'].'&'.$menus[$mi_info['mi_category']]['id_category'].'='.$tmp_id;
                }
                $mi_info['link'] = $tmplink;
            } else {
                if ($menus[$mi_info['mi_category']]['is_id'] && empty($tmp_id)) {
                    // Do nothing
					$mi_info['link'] = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'];
                } else {
                    if($mi_info['mi_category'] == 'outer_url') {
                        $tmplink = $tmp_id;
                    } else if(empty($tmp_id)) {
                        $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'];
                        // Hard code for "Company Introduction" and "Contact Us"
                        if ($mi_info['mi_category'] == 'company_info') {
                            if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                                $sc_id = '2';
                            else
                                $sc_id = '4';
                            $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                        } else if ($mi_info['mi_category'] == 'contact_info') {
                            if (trim(SessionHolder::get('_LOCALE')) == 'zh_CN')
                                $sc_id = '1';
                            else
                                $sc_id = '3';
                            $tmplink .= '&'.$menus[$mi_info['mi_category']]['id_category'].'='.$sc_id;
                        } // End : Hard code
                    } else {
                        $tmplink = '_m='.$menus[$mi_info['mi_category']]['mod_addr']['mod_name'].'&_a='.$menus[$mi_info['mi_category']]['mod_addr']['addr'].'&'.$menus[$mi_info['mi_category']]['id_category'].'='.$tmp_id;
                    }
                    $mi_info['link'] = $tmplink;
                }
            }
            $o_mi->set($mi_info);
            $o_mi->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_result';
        }

        $this->assign('json', Toolkit::jsonOK(array('forward' => Html::uriquery('mod_menu_item', 'admin_list', array("menu_id" => $mi_info['menu_id'])))));
        return '_result';
    }

    public function admin_list() {
        $this->_layout = 'content';

        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));
        $lang_sw = trim(ParamHolder::get('lang_sw', $mod_locale));
        SessionHolder::set('mod_menu_item/_LOCALE', $lang_sw);
        $menu_id = ParamHolder::get('menu_id', 0);

        $all_menuitems =& MenuItem::listMenuItems(0, "s_locale=? and menu_id=?", array($lang_sw, $menu_id));

        $this->assign('menuitems', $all_menuitems);

        $this->assign('lang_sw', $lang_sw);
        $this->assign('langs', Toolkit::loadAllLangs());
    }

    public function admin_delete() {

        $mi_id = trim(ParamHolder::get('mi_id', '0'));
        if (intval($mi_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }
        try {
            $curr_mi = new MenuItem($mi_id);
            MenuItem::delete_r($curr_mi->id);
            $curr_mi->delete();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }

        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }

    /** useless now
 	public function subcategory() {
        include_once(P_INC.'/menus.php');
		$curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $flag = ParamHolder::get('flag');
        $_menus = MenuItem::toSelectLink($menus, $flag);
        if($flag == 'outer_url') {
            $_menus['link'] ='';
        }
        $_menus['flag'] = $flag;
		//2009-10-12 update zhangjc
		if($_menus[$flag]['is_id']) {
			$_obj = new $_menus[$flag]['obj_name']();
			$sub_items = $_obj->findAll("s_locale =? and published=?",array($mod_locale, 1));
			$arr = array();
			$j=0;
			for($i=0;$i<sizeof($sub_items);$i++) {
				$arr[$j++] = $sub_items[$i]->id;
				$arr[$j++] = $sub_items[$i]->$_menus[$flag]['obj_field'];
			}
			$_menus['zhangjc'] = $arr;
		}
        $this->assign('json', Toolkit::jsonOK($_menus));
        return '_result';
    }
    */

    public function getid() {
        $this->_layout = 'content';
        $obj_name = ParamHolder::get('_c');
        $obj_field = ParamHolder::get('_field');
        $id_c = ParamHolder::get('id_c');

        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_article/_LOCALE', $curr_locale));
        $lang_sw = trim(ParamHolder::get('lang_sw', $mod_locale));
        SessionHolder::set('mod_article/_LOCALE', $lang_sw);
        $_data =&
            Pager::pageByObject($obj_name, "s_locale=?", array($lang_sw),
                "ORDER BY `id` DESC");
        $this->assign('_field', trim($obj_field));
        $this->assign('id_c', $id_c);
        $this->assign('datas', $_data['data']);
        $this->assign('pager', $_data['pager']);

    }
    
    public function admin_move() {

        $mi_id = trim(ParamHolder::get('mi_id', '0'));
        $sib_mi_id = trim(ParamHolder::get('sib_mi_id', '0'));
        if (intval($mi_id) == 0 || intval($sib_mi_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }

        try {
            $curr_mi = new MenuItem($mi_id);
            $sib_mi = new MenuItem($sib_mi_id);

            $tmp_order = $curr_mi->i_order;
            $curr_mi->i_order = $sib_mi->i_order;
            $sib_mi->i_order = $tmp_order;

            $curr_mi->save();
            $sib_mi->save();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }

        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }
    
    public function admin_link_content_select() {
        $this->_layout = 'clean';
        $link_type = trim(ParamHolder::get('pt'));
        
        $link_type_text = trim(ParamHolder::get('txt'));
        $this->assign('type_text', $link_type_text);
        
        switch ($link_type) {
            case 'article_list':
                return $this->_load_article_categories();
                break;
            case 'product_list':
                return $this->_load_product_categories();
                break;
            case 'article':
                return $this->_load_articles();
                break;
            case 'product':
                return $this->_load_products();
                break;
            case 'static':
                return $this->_load_static_contents();
                break;
            case 'outer_url':
                return $this->_load_external_url_input();
                break;
            default:
                $this->assign('json', Toolkit::jsonERR(__('Link Type Error!')));
                return ('_error');
        }
    }
    
    private function _load_article_categories() {
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));
        
        $all_categories =& ArticleCategory::listCategories(0, "s_locale=? AND published='1'", array($mod_locale));
        
        $this->assign('categories', $all_categories);
        
        // Prepare article category for select list view
        $all_categories =& ArticleCategory::listCategories(0, "s_locale=? AND published='1'", array($mod_locale));
        $select_categories = array();
        ArticleCategory::toSelectArray($all_categories, $select_categories,
                0, array(), array('0' => __('Top Level')));

        $this->assign('select_categories', $select_categories);

        $this->assign('mod_locale', $mod_locale);
        
        return '_select_article_category';
    }
    
    private function _load_product_categories() {
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));
        
        $all_categories =& ProductCategory::listCategories(0, "s_locale=? AND published='1'", array($mod_locale));
        
        $this->assign('categories', $all_categories);
        
		// Prepare Product category for select list view
        $all_categories =& ProductCategory::listCategories(0, "s_locale=? AND published='1'", array($mod_locale));
        $select_categories = array();
        ProductCategory::toSelectArray($all_categories, $select_categories,
                0, array(), array('0' => __('Top Level')));

        $this->assign('select_categories', $select_categories);

        $this->assign('mod_locale', $mod_locale);
        
        return '_select_product_category';
    }
    
    private function _load_articles() {
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $where = "s_locale=?";
        $params = array($mod_locale);

		$where .=  " AND article_category_id <> 2 AND published='1'";//article can't see News'infomation.
        
        $article_data =&
            Pager::pageByObject('Article', $where, $params,
                "ORDER BY `i_order` DESC");

        $this->assign('articles', $article_data['data']);
        $this->assign('pager', $article_data['pager']);

        return '_select_article';
    }
    
    private function _load_products() {
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $where = "s_locale=? AND published='1'";
        $params = array($mod_locale);

        $product_data =&
            Pager::pageByObject('Product', $where, $params,
                "ORDER BY `i_order` DESC");

        $this->assign('products', $product_data['data']);
        $this->assign('pager', $product_data['pager']);

        return '_select_product';
    }
    
    private function _load_static_contents() {
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $scontent_data =& 
            Pager::pageByObject('StaticContent', "s_locale=? AND id>? AND published='1'", array($mod_locale,4), 
                "ORDER BY `create_time` DESC");
        
        $this->assign('scontents', $scontent_data['data']);
        $this->assign('pager', $scontent_data['pager']);

        return '_select_static_content';
    }
    
    private function _load_external_url_input() {
        return '_input_external_url';
    }
    
	public function admin_pic()
    {
    	$menu_item_info = array();
    	$mi_id = trim(ParamHolder::get('_id', ''));
    	if(!empty($mi_id))
    	{
    		$o_mi = new MenuItem($mi_id);
            if($o_mi->published == 1)
            {
            	$menu_item_info['published'] = '0';
            	$o_mi->set($menu_item_info);
            	$o_mi->save();
				die('0');
            }
            elseif($o_mi->published == 0)
            {
            	$menu_item_info['published'] = '1';
            	$o_mi->set($menu_item_info);
            	$o_mi->save();
				die('1');
            }
    	}
    }
    
    public function admin_dashboard() {
    	$this->_layout = 'default';
    }
}
?>
