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

// 06/08/2010 Add >>
include_once(P_LIB.'/image.class.php');
// 06/08/2010 Add <<

class ModProduct extends Module {

	protected $_filters = array(
        'check_admin' => ''
    );
	public function admin_batch_create() {
		$file_allow_ext_pat = '/\.(csv)$/i';
		$file_info =& ParamHolder::get('batch_file', array(), PS_FILES);
		if (empty($file_info)) {
            Notice::set('mod_product/msg', __('Invalid post file data!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_batch'));
        }
		if(!preg_match($file_allow_ext_pat, $file_info["name"])) {
			Notice::set('mod_product/msg', __('File type error!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_batch'));
		}

		$file_info["name"] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
		if (!$this->_savetplFile($file_info)) {
            Notice::set('mod_product/msg', __('Uploading file failed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_batch'));
        }
		//csv upload
		$curr_locale = trim(SessionHolder::get('_LOCALE'));
		$product_info = array();
		$product_info['pub_start_time'] = -1;//开始时间
		$product_info['pub_end_time'] = -1;//结束时间
		$product_info['published'] = '1';//是否发布
		$product_info['for_roles'] = '{member}{admin}{guest}';//是否发布
		//$product_info['create_time'] = time();//创建时间
		//$product_info['price'] = 0;//产品原价
		//$product_info['introduction'] = '';//产品简介
		//$product_info['discount_price'] = 0;//产品折扣价
		//$product_info['delivery_fee'] = 0;//邮寄费
		//$product_info['online_orderable'] = 0;//是否开放在线订购
		$product_info['s_locale'] = $curr_locale;//语言
		//$product_info['recommended'] = 0;//是否推荐
		//$product_info['product_category_id'] = 1;//默认未分类

		$handle = fopen(ROOT.'/upload/file/'.$file_info["name"],"r");
		$row = 1;
		while ($data = fgetcsv($handle)) {
			if($row == 1){
				$row++;
				continue;
			}
			$num = count($data);
			$row++;//行数
			//for ($c=0; $c < $num; $c++) {
			$o_prd = new Product();
			$product_info['i_order'] = Product::getMaxOrder(1) + 1;

			$prd_class = iconv('gb2312','utf-8//IGNORE',strip_tags($data[0]));//产品分类
			$o_prd_class = new ProductCategory();
			$prd_arr = $o_prd_class->findAll("name='".$prd_class."'");
			$product_info['product_category_id'] = intval($prd_arr[0]->id);

			$product_info['name'] = iconv('gb2312','utf-8//IGNORE',strip_tags($data[1]));//产品名称 
			$product_info['introduction'] = str_replace( array('\r', '\n', '"<"'), array("\r", "\n", "<"), iconv('gb2312','utf-8//IGNORE',$data[2]) );//产品简介
			$product_info['description'] = str_replace( array('\r', '\n', '"<"'), array("\r", "\n", "<"), iconv('gb2312','utf-8//IGNORE',$data[3]) );//产品描述
			$product_info['feature_img'] = 'upload/image/'.iconv('gb2312','utf-8//IGNORE',strip_tags($data[4]));//产品大图
			// 图片水印/缩略图
        	if( THUMB_STATUS ) {
        		/*$extend = array('_e' => 'mod_product/msg', 
	        			            '_a' => 'mod_product', 
	        						'_m' => 'admin_batch'
	        				  );
							  */
        		$resource = $this->image_mark_thumb( ROOT.'/'.$product_info['feature_img'], array() );
        	    $product_info["feature_smallimg"] = !empty($resource['thumb']) ? 'upload/image/'.$resource['thumb'] : 'upload/image/'.$file_info["name"];
        	} else {
				$product_info['feature_smallimg'] = $product_info['feature_img'];
			}
			$product_info['price'] = iconv('gb2312','utf-8//IGNORE',strip_tags($data[5]));//产品原价
			$product_info['discount_price'] = iconv('gb2312','utf-8//IGNORE',strip_tags($data[6]));//产品折扣价
			$product_info['delivery_fee'] = iconv('gb2312','utf-8//IGNORE',strip_tags($data[7]));//邮寄费
			$product_info['online_orderable'] = iconv('gb2312','utf-8//IGNORE',strip_tags($data[8]));//是否开放在线订购	
			$product_info['recommended'] = iconv('gb2312','utf-8//IGNORE',strip_tags($data[9]));//是否推荐
			$product_info['create_time'] = intval( strtotime($data[10]) );//创建时间
			
			$o_prd->set($product_info);
            $o_prd->save();
			//}
		}
		fclose($handle);
		/*
		//xls格式
		require_once P_LIB.'/Excel/reader.php';
		$data = new Spreadsheet_Excel_Reader();
		$data->setOutputEncoding('gb2312');
		$data->read(ROOT.'/upload/file/'.$file_info["name"]);
		
		$curr_locale = trim(SessionHolder::get('_LOCALE'));
		$product_info = array();
		$product_info['pub_start_time'] = -1;//开始时间
		$product_info['pub_end_time'] = -1;//结束时间
		$product_info['published'] = '1';//是否发布
		$product_info['for_roles'] = '{member}{admin}{guest}';//是否发布
		$product_info['create_time'] = time();//创建时间
		//$product_info['price'] = 0;//产品原价
		//$product_info['introduction'] = '';//产品简介
		//$product_info['discount_price'] = 0;//产品折扣价
		//$product_info['delivery_fee'] = 0;//邮寄费
		//$product_info['online_orderable'] = 0;//是否开放在线订购
		$product_info['s_locale'] = $curr_locale;//语言
		//$product_info['recommended'] = 0;//是否推荐
		//$product_info['product_category_id'] = 1;//默认未分类
		
		for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
			$o_prd = new Product();
			$product_info['i_order'] =
            	Product::getMaxOrder(1) + 1;

			$prd_class = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][1]));//产品分类
			$o_prd_class = new ProductCategory();
			$prd_arr = $o_prd_class->findAll("name='".$prd_class."'");
			$product_info['product_category_id'] = intval($prd_arr[0]->id);

			$product_info['name'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][2]));//产品名称
			$product_info['introduction'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][3]));//产品简介
			$product_info['description'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][4]));//产品描述
			$product_info['feature_img'] = 'upload/image/'.iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][5]));//产品大图
			// 图片水印/缩略图
        	if( THUMB_STATUS ) {
        		$extend = array('_e' => 'mod_product/msg', 
	        			            '_a' => 'mod_product', 
	        						'_m' => 'admin_batch'
	        				  );
        		$resource = $this->image_mark_thumb( ROOT.'/'.$product_info['feature_img'], $extend );
        	    $product_info["feature_smallimg"] = !empty($resource['thumb']) ? 'upload/image/'.$resource['thumb'] : 'upload/image/'.$file_info["name"];
        	} else {
				$product_info['feature_smallimg'] = $product_info['feature_img'];
			}
			$product_info['price'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][6]));//产品描述
			$product_info['discount_price'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][7]));//产品描述
			$product_info['delivery_fee'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][8]));//产品描述
			$product_info['online_orderable'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][9]));//产品描述
			$product_info['recommended'] = iconv('gb2312','utf-8',strip_tags($data->sheets[0]['cells'][$i][10]));//产品描述
			$o_prd->set($product_info);
            $o_prd->save();
		}
		*/
		@unlink(ROOT.'/upload/file/'.$file_info["name"]);
		Notice::set('mod_product/msg', __('Product added successfully!'));
		Content::redirect(Html::uriquery('mod_product', 'admin_list'));
	}
	public function admin_batch() {
		$this->_layout = 'content';
    	
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_product/_LOCALE', $curr_locale));
        
        $this->assign('content_title', __('Batch Import'));
        $this->assign('next_action', 'admin_batch_create');
        
        $this->assign('mod_locale', $mod_locale);
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());
        
	}
    public function admin_list() {
        $this->_layout = 'content';

        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_product/_LOCALE', $curr_locale));
        $lang_sw = trim(ParamHolder::get('lang_sw', $mod_locale));
        SessionHolder::set('mod_product/_LOCALE', $lang_sw);
        $keyword =& ParamHolder::get('hidkeyword', '');

        $where = "s_locale=?";
        $params = array($lang_sw);
        
        $cap_sw = trim(ParamHolder::get('cap_sw', '-'));
        // 02/06/2010 Edit >>
		$all_categories =& ProductCategory::listCategories(0, "s_locale=?", array($lang_sw));
        if (is_numeric($cap_sw)) {
        	$childids = '';

	        $childids = $this->getCategoryChildIds( $cap_sw, $curr_locale );
	        $catids = !empty($childids) ? $childids.$cap_sw : $cap_sw;
	        $where .= " AND product_category_id IN(".$catids.")";
            //$where .= " AND product_category_id =?";
            //$params[] = $cap_sw;
        }// 02/06/2010 Edit <<
        if( trim($keyword) ) $where .=  " AND name LIKE '%{$keyword}%'";

        $product_data =&
            Pager::pageByObject('Product', $where, $params,
                "ORDER BY `id` DESC");
        $this->assign('next_action', 'admin_order');
        $this->assign('products', $product_data['data']);
        $this->assign('pager', $product_data['pager']);
        $this->assign('cap_sw', $cap_sw);
        $this->assign('keyword', $keyword);
        $this->assign('lang_sw', $lang_sw);
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());

		// Prepare Product category for select list view
        //$all_categories =& ProductCategory::listCategories(0, "s_locale=?", array($lang_sw));
        $select_categories = array();
        ProductCategory::toSelectArray($all_categories, $select_categories,
                0, array(), array('-' => __('View All'), '0' => __('Uncategorised')));

		// 28/06/2010 excel export >>
		$act = trim(ParamHolder::get('act', ''));
		$pids = trim(ParamHolder::get('prd_ids', '0'));
		if( $act == '9999' ) {
			if( str_replace('M', '', ini_get('memory_limit')) <= 8 ) {ini_set("memory_limit", '64M');}
			$products = $rows = array();
			$obj = new Product();
			
			if ($pids) $where .=  " AND `id` IN({$pids})";
			$products =& $obj->findAll($where, $params, "ORDER BY `create_time` DESC");

			$rows[] = array(__('Category'), __('Name'), __('Introduction'), __('Product Description'), __('Full Image'), __('Price'),  
					        __('Discount Price'), __('Delivery Fee'), __('Online Orderable'), __('Recommend'), __('Publish Date'));

			// product list
			foreach ($products as $product) {
				$product->loadRelatedObjects(REL_PARENT, array('ProductCategory'));

				$rows[] = array($product->masters['ProductCategory']->name, $product->name, $product->introduction, 
								$product->description, str_replace('upload/image/', '', $product->feature_img), 
				             	$product->price, $product->discount_price, $product->delivery_fee, $product->online_orderable, 
								$product->recommended, date('Y-m-d H:i:s', $product->create_time));
			}

			include_once P_LIB."/Excel/export.class.php";
			$csv = new Export_CSV($rows, 'products.csv');
			$csv->Export();
			exit;
		}
		// 28/06/2010 excel export <<

        $this->assign('select_categories', $select_categories);
    }
	public function admin_order() {

		$order_info =& ParamHolder::get('i_order', array());
		if (!is_array($order_info)) {
            $this->assign('json', Toolkit::jsonERR(__('Missing product order information!')));
            return '_result';
        }
		try {
			foreach($order_info as $key => $val) {
				$product_info['i_order'] = $val;
				$o_product = new Product($key);
				$o_product->set($product_info);
				$o_product->save();
			}
		} catch (Exception $ex) {
			$this->assign('json', Toolkit::jsonERR($ex->getMessage()));
			return '_result';
		}
		Notice::set('mod_product/msg', __('Product order added successfully!'));
		Content::redirect(Html::uriquery('mod_product', 'admin_list'));
	}
    public function admin_add() {
        $this->_layout = 'content';

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

        $all_categories =& ProductCategory::listCategories(0, "s_locale=?", array($mod_locale));
        $select_categories = array();
        ProductCategory::toSelectArray($all_categories, $select_categories,
	        	0, array(), array('0' => __('Uncategorised')));

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

        $this->assign('mod_locale', $mod_locale);
        $this->assign('select_categories', $select_categories);
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());
		$this->assign('act', 'add');
        return '_form';
    }
    
    public function admin_mi_quick_add() {
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $mod_locale = trim(SessionHolder::get('mod_menu_item/_LOCALE', $curr_locale));

        $all_categories =& ProductCategory::listCategories(0, "s_locale=?", array($mod_locale));
        $select_categories = array();
        ProductCategory::toSelectArray($all_categories, $select_categories,
	        	0, array(), array('0' => __('Uncategorised')));

        $this->assign('content_title', __('New Product'));
        $this->assign('next_action', 'admin_mi_quick_create');

        $this->assign('mod_locale', $mod_locale);
        $this->assign('select_categories', $select_categories);
        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());
        
        $link_type_text = trim(ParamHolder::get('txt'));
        $this->assign('type_text', $link_type_text);

        $this->_layout = 'clean';
        return '_mi_quick_add_form';
    }

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

        $product_info =& ParamHolder::get('prd', array());
        if (sizeof($product_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing product information!')));
            return '_error';
        }
    	if($product_info['product_category_id'] == -1) {
        	$product_info['product_category_id'] == 0;
        }
		$file_info =& ParamHolder::get('prd_file', array(), PS_FILES);
		if (empty($file_info)) {
            Notice::set('mod_product/msg', __('Invalid post file data!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_add'));
        }
		if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $file_info["name"])) {
			Notice::set('mod_product/msg', __('Big image type error!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_add'));
		}
		
        //if(file_exists(ROOT.'/upload/image/'.$file_info["name"])) {
        $file_info["name"] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
        //}
        if (!$this->_savelinkimg($file_info)) {
            Notice::set('mod_product/msg', __('Product big image upload failed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_add'));
        } else {
		    // 图片水印/缩略图
        	if( THUMB_STATUS || WATERMARK_STATUS ) {
        		$extend = array('_e' => 'mod_product/msg', 
	        			            '_a' => 'mod_product', 
	        						'_m' => 'admin_add'
	        				  );
        		$resource = $this->image_mark_thumb( ROOT.'/upload/image/'.$file_info["name"], $extend );
        		$file_info["name"] = !empty($resource['watermark']) ? $resource['watermark'] : $file_info["name"];
        	    $file_small_info["name"] = !empty($resource['thumb']) ? $resource['thumb'] : $file_info["name"];
        	}
        }

		/*$file_small_info =& ParamHolder::get('prd_small_file', array(), PS_FILES);
		if (empty($file_small_info)) {
            Notice::set('mod_product/msg', __('Invalid post file data!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_add'));
        }
		if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $file_small_info["name"])) {
			Notice::set('mod_product/msg', __('Small image type not allowed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_add'));
		}
        if(file_exists(ROOT.'/upload/image/'.$file_small_info["name"])) {
            $file_small_info["name"] = Toolkit::randomStr(8).strrchr($file_small_info["name"],".");
        }
        if (!$this->_savelinkimg($file_small_info)) {
            Notice::set('mod_product/msg', __('Product small image upload failed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_add'));
        }*/

		$is_member_only = ParamHolder::get('ismemonly', '0');
        try {
			 $product_info['feature_img'] = "upload/image/".$file_info["name"];
			 if( !empty($file_small_info["name"]) ) {
			 	 $product_info['feature_smallimg'] = "upload/image/".$file_small_info["name"];
			 } else {
			 	 if (!empty($file_info["name"])) {
			 	 $product_info['feature_smallimg'] = "upload/image/".$file_info["name"];}
			 }
        	// Re-arrange publish time
        	//if (intval(ParamHolder::get('pub_start_time', '0')) == 0) {
        	    $product_info['pub_start_time'] = -1;
        	//} else {
        	//    $product_info['pub_start_time'] = strtotime($product_info['pub_start_time']);
        	//}
        	//if (intval(ParamHolder::get('pub_end_time', '0')) == 0) {
        	    $product_info['pub_end_time'] = -1;
        	//} else {
        	//    $product_info['pub_end_time'] = strtotime($product_info['pub_end_time']);
        	//}
        	// Re-arrange recommend status
            if ($product_info['recommended'] == '1') {
                $product_info['recommended'] = '1';
            } else {
                $product_info['recommended'] = '0';
            }
        	// Re-arrange publish status
//            if ($product_info['published'] == '1') {
//                $product_info['published'] = '1';
//            } else {
//                $product_info['published'] = '0';
//            }
				$product_info['published'] = '1';
        	// Re-arrange online orderable status
            if ($product_info['online_orderable'] == '1') {
                $product_info['online_orderable'] = '1';
            } else {
                $product_info['online_orderable'] = '0';
            }

			// Re-arrange prices for basic version
			if (!isset($product_info['price'])) {
				$product_info['price'] = '0.00';
			}
			if (!isset($product_info['discount_price'])) {
				$product_info['discount_price'] = '0.00';
			}
			if (!isset($product_info['delivery_fee'])) {
				$product_info['delivery_fee'] = '0.00';
			}
			
            // Re-arrange discount price
            if (number_format($product_info['discount_price'], 2) == '0.00') {
                $product_info['discount_price'] = $product_info['price'];
            }
            $product_info['for_roles'] = ACL::explainAccess(intval($is_member_only));
            // The create time
            $product_info['create_time'] = intval( strtotime($product_info['date']) );
            $product_info['i_order'] =
            	Product::getMaxOrder($product_info['product_category_id']) + 1;
            // Data operation
            $o_product = new Product();
            $o_product->set($product_info);
            $o_product->save();
            
            $this->_upload_gala_pics($o_product->id, ParamHolder::get('prd_extpic', array(), PS_FILES));
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

       Notice::set('mod_product/msg', __('Product added successfully!'));
       Content::redirect(Html::uriquery('mod_product', 'admin_list'));
    }
    
    public function admin_mi_quick_create() {
		$this->_layout = 'clean';

        $product_info =& ParamHolder::get('prd', array());
        if (sizeof($product_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing product information!')));
            return '_error';
        }
		$file_info =& ParamHolder::get('prd_file', array(), PS_FILES);
		if (empty($file_info)) {
            Notice::set('mod_product/msg', __('Invalid post file data!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_mi_quick_add'));
        }
		if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $file_info["name"])) {
			Notice::set('mod_product/msg', __('Big image type error!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_mi_quick_add'));
		}
        //if(file_exists(ROOT.'/upload/image/'.$file_info["name"])) {
        $file_info["name"] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
        //}
        if (!$this->_savelinkimg($file_info)) {
            Notice::set('mod_product/msg', __('Product big image upload failed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_mi_quick_add'));
        } else {
		    // 图片水印/缩略图
        	if( THUMB_STATUS || WATERMARK_STATUS ) {
        		$extend = array('_e' => 'mod_product/msg', 
	        			            '_a' => 'mod_product', 
	        						'_m' => 'admin_mi_quick_add'
	        				  );
        		$resource = $this->image_mark_thumb( ROOT.'/upload/image/'.$file_info["name"], $extend );
        		$file_info["name"] = !empty($resource['watermark']) ? $resource['watermark'] : $file_info["name"];
        	    $file_small_info["name"] = !empty($resource['thumb']) ? $resource['thumb'] : $file_info["name"];
        	}
        }

		/*$file_small_info =& ParamHolder::get('prd_small_file', array(), PS_FILES);
		if (empty($file_small_info)) {
            Notice::set('mod_product/msg', __('Invalid post file data!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_mi_quick_add'));
        }
		if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $file_small_info["name"])) {
			Notice::set('mod_product/msg', __('Small image type not allowed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_mi_quick_add'));
		}
        if(file_exists(ROOT.'/upload/image/'.$file_small_info["name"])) {
            $file_small_info["name"] = Toolkit::randomStr(8).strrchr($file_small_info["name"],".");
        }
        if (!$this->_savelinkimg($file_small_info)) {
            Notice::set('mod_product/msg', __('Product small image upload failed!'));
            Content::redirect(Html::uriquery('mod_product', 'admin_mi_quick_add'));
        }*/

		$is_member_only = ParamHolder::get('ismemonly', '0');
        try {
			 $product_info['feature_img'] = "upload/image/".$file_info["name"];
			 if( !empty($file_small_info["name"]) ) {
			 	$product_info['feature_smallimg'] = "upload/image/".$file_small_info["name"];
			 } else {
			 	 if (!empty($file_info["name"])) {
			 	$product_info['feature_smallimg'] = "upload/image/".$file_info["name"];}
			 }
        	// Re-arrange publish time
        	//if (intval(ParamHolder::get('pub_start_time', '0')) == 0) {
        	    $product_info['pub_start_time'] = -1;
        	//} else {
        	//    $product_info['pub_start_time'] = strtotime($product_info['pub_start_time']);
        	//}
        	//if (intval(ParamHolder::get('pub_end_time', '0')) == 0) {
        	    $product_info['pub_end_time'] = -1;
        	//} else {
        	//    $product_info['pub_end_time'] = strtotime($product_info['pub_end_time']);
        	//}
        	// Re-arrange recommend status
            if ($product_info['recommended'] == '1') {
                $product_info['recommended'] = '1';
            } else {
                $product_info['recommended'] = '0';
            }
        	// Re-arrange publish status
//            if ($product_info['published'] == '1') {
//                $product_info['published'] = '1';
//            } else {
//                $product_info['published'] = '0';
//            }
				$product_info['published'] = '1';
        	// Re-arrange online orderable status
            if ($product_info['online_orderable'] == '1') {
                $product_info['online_orderable'] = '1';
            } else {
                $product_info['online_orderable'] = '0';
            }

			// Re-arrange prices for basic version
			if (!isset($product_info['price'])) {
				$product_info['price'] = '0.00';
			}
			if (!isset($product_info['discount_price'])) {
				$product_info['discount_price'] = '0.00';
			}
			if (!isset($product_info['delivery_fee'])) {
				$product_info['delivery_fee'] = '0.00';
			}
			
            // Re-arrange discount price
            if (number_format($product_info['discount_price'], 2) == '0.00') {
                $product_info['discount_price'] = $product_info['price'];
            }
            $product_info['for_roles'] = ACL::explainAccess(intval($is_member_only));
            // The create time
            $product_info['create_time'] = intval( strtotime($product_info['date']) );
            $product_info['i_order'] =
            	Product::getMaxOrder($product_info['product_category_id']) + 1;
            // Data operation
            $o_product = new Product();
            $o_product->set($product_info);
            $o_product->save();
            
            $this->_upload_gala_pics($o_product->id, ParamHolder::get('prd_extpic', array(), PS_FILES));
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

        $link_type_text = trim(ParamHolder::get('txt'));
        $this->assign('type_text', $link_type_text);
        $this->assign('id', $o_product->id);
        $this->assign('name', $o_product->name);
        return '_mi_quick_add_success';
    }

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

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

        try {
            $curr_product = new Product($p_id);
            $this->assign('curr_product', $curr_product);

	        $all_categories =& ProductCategory::listCategories(0, "s_locale=?", array($curr_product->s_locale));
	        $select_categories = array();
	        ProductCategory::toSelectArray($all_categories, $select_categories,
		        	0, array(), array('0' => __('Uncategorised')));
	        $this->assign('select_categories', $select_categories);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

        $this->assign('content_title', __('Edit Product'));
        $this->assign('next_action', 'admin_update');
        $this->assign('p_id', $p_id);

        $this->assign('langs', Toolkit::loadAllLangs());
        $this->assign('roles', Toolkit::loadAllRoles());

        return '_form';
    }

    public function admin_update() {
        $product_info =& ParamHolder::get('prd', array());
        if (sizeof($product_info) <= 0) {
            $this->assign('json', Toolkit::jsonERR(__('Missing product information!')));
            return '_error';
        }
		$file_info =& ParamHolder::get('prd_file', array(), PS_FILES);
		if (!empty($file_info["name"])) {
			if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $file_info["name"])) {
				Notice::set('mod_product/msg', __('Big image type error!'));
				Content::redirect(Html::uriquery('mod_product', 'admin_edit', array('p_id' => $product_info['id'])));
			}
			//if(file_exists(ROOT.'/upload/image/'.$file_info["name"])) {
			$file_info["name"] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
			//}
			if (!$this->_savelinkimg($file_info)) {
				Notice::set('mod_product/msg', __('Product big image upload failed!'));
				Content::redirect(Html::uriquery('mod_product', 'admin_edit', array('p_id' => $product_info['id'])));
			} else {
				/**
				 * 编辑模式下删除编辑前的对应图片文件
				 */
				 $str_feature_img = ROOT.'/'.$product_info['feature_img']; // 全图
				 if (file_exists($str_feature_img)) {
				 	 $mix_paths = pathinfo($str_feature_img);
				 	 $str_ext = strtolower( $mix_paths["extension"] );
				 	 $str_small_img = str_replace( $str_ext, 'thumb.'.$str_ext, $str_feature_img );// 缩略图
				 	 if (file_exists($str_small_img)) {unlink($str_small_img);}
				 	 unlink($str_feature_img);
				 }
				 
	        	// 图片水印/缩略图
	        	if( THUMB_STATUS || WATERMARK_STATUS ) {
	        		$extend = array('_e' => 'mod_product/msg', 
	        			            '_a' => 'mod_product', 
	        						'_m' => 'admin_edit',
	        						'_p' => array('p_id' => $product_info['id'])
	        				  );
	        		$resource = $this->image_mark_thumb( ROOT.'/upload/image/'.$file_info["name"], $extend );
	        		$file_info["name"] = !empty($resource['watermark']) ? $resource['watermark'] : $file_info["name"];
	        	    $file_small_info["name"] = !empty($resource['thumb']) ? $resource['thumb'] : $file_info["name"];
	        	}
	        }
		}
		/*$file_small_info =& ParamHolder::get('prd_small_file', array(), PS_FILES);
		if (!empty($file_small_info["name"])) {
			if(!preg_match('/\.('.PIC_ALLOW_EXT.')$/i', $file_small_info["name"])) {
				Notice::set('mod_product/msg', __('Small image type error!'));
				Content::redirect(Html::uriquery('mod_product', 'admin_edit', array('p_id' => $product_info['id'])));
			}
			if(file_exists(ROOT.'/upload/image/'.$file_small_info["name"])) {
				$file_small_info["name"] = Toolkit::randomStr(8).strrchr($file_small_info["name"],".");
			}
			if (!$this->_savelinkimg($file_small_info)) {
				Notice::set('mod_product/msg', __('Product small image upload failed!'));
				Content::redirect(Html::uriquery('mod_product', 'admin_edit', array('p_id' => $product_info['id'])));
			}
		}*/

        $is_member_only = ParamHolder::get('ismemonly', '0');
        try {
			//add image
			if (!empty($file_info["name"])) {
				$product_info['feature_img'] = "upload/image/".$file_info["name"];
			}
			if (!empty($file_small_info["name"])) {
				$product_info['feature_smallimg'] = "upload/image/".$file_small_info["name"];
			} else {
				if (!empty($file_info["name"])) {
				$product_info['feature_smallimg'] = "upload/image/".$file_info["name"];}
			}
        	// Re-arrange publish time
        	//if (intval(ParamHolder::get('pub_start_time', '0')) == 0) {
        	    $product_info['pub_start_time'] = -1;
        	//} else {
        	//    $product_info['pub_start_time'] = strtotime($product_info['pub_start_time']);
        	//}
        	//if (intval(ParamHolder::get('pub_end_time', '0')) == 0) {
        	    $product_info['pub_end_time'] = -1;
        	//} else {
        	//    $product_info['pub_end_time'] = strtotime($product_info['pub_end_time']);
        	//}
        	// Re-arrange recommend status
            if ($product_info['recommended'] == '1') {
                $product_info['recommended'] = '1';
            } else {
                $product_info['recommended'] = '0';
            }
        	// Re-arrange publish status
//            if ($product_info['published'] == '1') {
//                $product_info['published'] = '1';
//            } else {
//                $product_info['published'] = '0';
//            }
        	// Re-arrange online orderable status
            if ($product_info['online_orderable'] == '1') {
                $product_info['online_orderable'] = '1';
            } else {
                $product_info['online_orderable'] = '0';
            }
            // Re-arrange discount price
            if (number_format($product_info['discount_price'], 2) == '0.00') {
                $product_info['discount_price'] = number_format($product_info['price'],2);
            }
            $product_info['for_roles'] = ACL::explainAccess(intval($is_member_only));
            $product_info['create_time'] = intval( strtotime($product_info['date']) );

            // Data operation
            $o_product = new Product($product_info['id']);
            $o_product->set($product_info);
            $o_product->save();
            
            $this->_upload_gala_pics($o_product->id, ParamHolder::get('prd_extpic', array(), PS_FILES));
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

       Notice::set('mod_product/msg', __('Product updated successfully!'));
       Content::redirect(Html::uriquery('mod_product', 'admin_list'));
    }

    public function admin_delete() {

        $p_id = trim(ParamHolder::get('p_id', '0'));
        if (intval($p_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }
        try {
			$tmp_arr = explode('_', $p_id);
			$len = sizeof($tmp_arr);
			for ($i = 0; $i< $len; $i++){
				$curr_product = new Product($tmp_arr[$i]);
				/**
				 * 删除模式下删除当前产品的对应图片文件
				 */
				 if (file_exists(ROOT.'/'.$curr_product->feature_img)) {
				 	@unlink(ROOT.'/'.$curr_product->feature_img);
				 }
				 if (file_exists(ROOT.'/'.$curr_product->feature_smallimg)) {
				 	@unlink(ROOT.'/'.$curr_product->feature_smallimg);
				 }
				$curr_product->delete();
			}
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }

        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }
    
    public function admin_delete_extpic() {
        $p_id = trim(ParamHolder::get('p_id', '0'));
        if (intval($p_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }
        try {
				$curr_pic = new ProductPic($p_id);
				@unlink(ROOT.'/'.$curr_pic->pic);
				$curr_pic->delete();
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }
        
        $this->assign('json', Toolkit::jsonOK(array('id' => $p_id)));
        return '_result';
    }

	private function _savelinkimg($struct_file) {
		//$struct_file['name'] = iconv("UTF-8", "GB2312//IGNORE", $struct_file['name']);
        return move_uploaded_file($struct_file['tmp_name'], ROOT.'/upload/image/'.$struct_file['name']);
    }
    
    private function _upload_gala_pics($product_id, $html_file) {
        if (sizeof($html_file) == 0) return;
        for ($i = 0; $i < sizeof($html_file['name']); $i++) {
            if ($html_file['error'][$i] > 0) continue;
            $rand_fname = Toolkit::randomStr(8).'_'.$html_file['name'][$i];
            if (move_uploaded_file($html_file['tmp_name'][$i], 
                    ROOT.'/upload/image/'.$rand_fname)) {
                $ext_prd_pic = new ProductPic();
                $ext_prd_pic->product_id = $product_id;
                
                $ext_prd_pic->pic = 'upload/image/'.$rand_fname;
                $ext_prd_pic->save();
            }
        }
    }
    
	public function admin_pic()
    {
    	$product_info = array();
    	$product_id = trim(ParamHolder::get('_id', ''));
    	if(!empty($product_id))
    	{
    		$o_product = new Product($product_id);
            if($o_product->published == 1)
            {
            	$product_info['published'] = '0';
            	$o_product->set($product_info);
            	$o_product->save();
				die('0');
            }
            elseif($o_product->published == 0)
            {
            	$product_info['published'] = '1';
            	$o_product->set($product_info);
            	$o_product->save();
				die('1');
            }
    	}
    }
    
    // 02/06/2010 Add >>
    private function getCategoryChildIds( $cur_classid, $curr_locale ) 
    {
    	$childids = '';
    	$product_childcategories = array();
    	$product_category = new ProductCategory();
    	$product_childcategories = $product_category->findAll("product_category_id = '{$cur_classid}' AND s_locale = '{$curr_locale}'");
    	
    	if ( count($product_childcategories) > 0 ) {
    		foreach( $product_childcategories as $val ) 
    		{
    			$childids .= $val->id.',';
    			$childids .= $this->getCategoryChildIds( $val->id, $curr_locale );
    		}
    	}
   
    	return $childids;
    }
    // 02/06/2010 Add <<
    
    // 08/06/2010 Add >>
    private function image_mark_thumb( $upload_file, $extend )
    {
    	$resource = array();
    	$image = new Image( $upload_file, $extend );

		if( WATERMARK_STATUS ) {
			// 水印位置
			$watermarkstatus = WATERMARK_STATUS;
			// 水印图片类型(1:PNG 类型水印 2:文本类型水印)
			$watermarktype = WATERMARK_TYPE;
			// 水印添加条件
			$watermarkminwidth = WATERMARK_MIN_WIDTH;
			$watermarkminheight = WATERMARK_MIN_HEIGHT;
			// JPEG 水印质量
			$watermarkquality = WATERMARK_QUALITY;
			
			if( $watermarktype == 2 ) {
				// 文本水印属性
				$watermarktext = array(
					'angle' => WATERMARK_TEXT_ANGLE, 
					'fontpath' => ROOT.'/locale/fangxue.ttf', 
					'color' => WATERMARK_TEXT_COLOR, 
					'shadowcolor' => WATERMARK_TEXT_SHADOW_COLOR, 
					'size' => WATERMARK_TEXT_SIZE, 
					'shadowx' => WATERMARK_TEXT_SHADOWX, 
					'shadowy' => WATERMARK_TEXT_SHADOWY, 
					'text' => WATERMARK_TEXT
				);
				
				$watermarktext['color'] = preg_replace('/#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/e', 
				                          "hexdec('\\1').','.hexdec('\\2').','.hexdec('\\3')", $watermarktext['color']);
				$watermarktext['shadowcolor'] = preg_replace('/#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/e', 
				                          "hexdec('\\1').','.hexdec('\\2').','.hexdec('\\3')", $watermarktext['shadowcolor']);
				                          
				$watermarkpng = '';
			} else {
				// 水印图片
				$watermarkpng = WATERMARK_PNG;
				
				$watermarktext = array();
			}
			
			$resource["watermark"] = $image->Watermark($watermarkstatus, $watermarktype, $watermarkquality, $watermarkminwidth, 
			                                           $watermarkminheight, $watermarkpng, $watermarktext);
		}
		
		if( THUMB_STATUS ) {
			// 缩略图(0:不启用 1:生成不超过指定大小的缩略图 2:转换图片附件为不超过指定大小的图片 3:生成固定大小的缩略图)
			$thumbstatus = THUMB_STATUS;
			// 缩略图质量
			$thumbquality = THUMB_QUALITY;
			// 缩略图大小
			$thumbwidth = THUMB_WIDTH;
			$thumbheight = THUMB_HEIGHT;
			
			$resource["thumb"] = $image->Thumb($thumbstatus, $thumbquality, $thumbwidth, $thumbheight, $watermarkstatus);
		}
		
		return $resource;
    }
    // 08/06/2010 Add <<

	private function _savetplFile($struct_file) {
    	//$struct_file['name'] = iconv("UTF-8", "GB2312//IGNORE", $struct_file['name']);
        return move_uploaded_file($struct_file['tmp_name'], ROOT.'/upload/file/'.$struct_file['name']);
    }
}
?>
