<?php
/**
 * vi:set sw=4 ts=4 noexpandtab fileencoding=utf-8:
 * @class  ncartView
 * @author NURIGO(contact@nurigo.net)
 * @brief  ncartView
 */
class ncartView extends ncart
{
	function init()
	{
		if(!$this->module_info->skin) $this->module_info->skin = 'default';
		$skin = $this->module_info->skin;
		$oModuleModel = &getModel('module');
		// 템플릿 경로 설정
		$this->setTemplatePath(sprintf('%sskins/%s', $this->module_path, $skin));

		$logged_info = Context::get('logged_info');

		if($logged_info) Context::set('login_chk','Y');
		else if(!$logged_info) Context::set('login_chk','N');

		Context::set('hide_trolley', 'true');

		$oLicenseModel = &getModel('license');
		if(!$oLicenseModel || ($oLicenseModel && !$oLicenseModel->getLicenseConfirm()))
		{
			Context::addHtmlHeader("<script>jQuery(document).ready(function() { jQuery('<div style=\"background:#fff; padding:6px; position:fixed; right:6px; bottom:6px; z-index:999999; \">Powered by <a href=\"http://www.xeshoppingmall.com\">NURIGO</a></div>').appendTo('body'); });</script>");
		}
	}

	function keygen()
	{
		$randval = rand(100000, 999999);
		$usec = explode(" ", microtime());
		$str_usec = str_replace(".", "", strval($usec[0]));
		$str_usec = substr($str_usec, 0, 6);
		return date("YmdHis") . $str_usec . $randval;
	}

	function getCategoryTree($module_srl) 
	{
		$oNcartModel = &getModel('ncart');
		$category = Context::get('category');
		if ($category && $this->module_info->category_display=='2') {
			$category_info = $oNcartModel->getCategoryInfo($category);
			$top = preg_split('/\./', $category_info->node_route);
			if (count($top) >= 2) {
				$args->node_route = sprintf("%s.%s.", $top[0], $top[1]);
				Context::set('top_category_srl', $top[1]);
			}
			if ($category_info->node_route=='f.') $args->node_route = 'f.' . $category . '.';
		}

		// category tree
		$args->module_srl = $module_srl;
		$output = $this->executeQueryArray('getCategoryAllSubitems', $args);
		if (!$output->toBool()) return $output;
		$category_list = $output->data;
		$category_tree = array();
		$category_index = array();
		if ($category_list) {
			foreach ($category_list as $no => $cate) {
				$node_route = $cate->node_route.$cate->node_id;
				$stages = explode('.',$node_route);
				$code_str = '$category_tree["' . implode('"]["', $stages) . '"] = array();';
				eval($code_str);
				$category_index[$cate->node_id] = $cate;
			}
		}
		Context::set('category_tree', $category_tree);
		Context::set('category_index', $category_index);
	}


	function dispNcartFrontPage() 
	{
		$oNcartModel = &getModel('ncart');

		$display_categories = $oNcartModel->getFrontDisplayItems($this->module_info->module_srl);

		Context::set('display_categories', $display_categories);

		$this->setTemplateFile('frontpage');
	}

	function thumbnailExists($file_srl, $width = 80, $height = 0, $type = '') 
	{
		if(!$file_srl) return false;
		if(!$this->getThumbnail($file_srl, $width, $height, $type)) return false;
		return true;
	}

	function getThumbnail($file_srl, $width = 80, $height = 0, $thumbnail_type = 'crop') 
	{
		$oFileModel = &getModel('file');
		if(!$file_srl) return;
		if(!$height) $height = $width;
		// Define thumbnail information
		$thumbnail_path = sprintf('files/cache/thumbnails/%s',getNumberingPath($file_srl, 3));
		$thumbnail_file = sprintf('%s%dx%d.%s.jpg', $thumbnail_path, $width, $height, $thumbnail_type);
		$thumbnail_url  = Context::getRequestUri().$thumbnail_file;
		// Return false if thumbnail file exists and its size is 0. Otherwise, return its path
		if(file_exists($thumbnail_file)) {
			if(filesize($thumbnail_file)<1) return false;
			else return $thumbnail_url;
		}
		// Target File
		$source_file = null;
		$file = $oFileModel->getFile($file_srl);
		if($file) {
			$source_file = $file->uploaded_filename;
		}

		if($source_file){
			$output = FileHandler::createImageFile($source_file, $thumbnail_file, $width, $height, 'jpg', $thumbnail_type);
		}
		// Return its path if a thumbnail is successfully genetated
		if($output) return $thumbnail_url;
		// Create an empty file not to re-generate the thumbnail
		else FileHandler::writeFile($thumbnail_file, '','w');

		return;
	}



	function dispNcartCartItems() 
	{
		$oNcartModel = &getModel('ncart');

		$cart = $oNcartModel->getCartInfo(Context::get('cartnos'));

		/*
		if ($cart && $cart->item_list)
		{
			foreach ($cart->item_list as $key=>$item)
			{
				if ($item->option_srl)
				{
					$options = $oNcartModel->getOptions($item->item_srl);
					$option = $options[$item->option_srl];
					$cart->item_list[$key]->option = $option;
				}
			}
		}
		 */

		Context::set('list',$cart->item_list);
		Context::set('sum_price',$cart->sum_price);
		Context::set('total_price',$cart->total_price);
		Context::set('delivery_fee',$cart->delivery_fee);
		Context::set('total_discounted_price',$cart->total_discounted_price);
		Context::set('total_discount_amount',$cart->total_discount_amount);

		// get module config
		$config = $oNcartModel->getModuleConfig();
		Context::set('config',$config);

		$this->setTemplateFile('cartitems');


	}
	function dispNcartFavoriteItems() 
	{
		$oFileModel = &getModel('file');
		$oNcartModel = &getModel('ncart');

		$logged_info = Context::get('logged_info');
		if (!$logged_info) return new Object(-1, 'msg_login_required');

		// favorite items
		$favorite_items = $oNcartModel->getFavoriteItems($logged_info->member_srl);
		Context::set('favorite_items', $favorite_items);

		// get module config
		$config = $oNcartModel->getModuleConfig();
		Context::set('config',$config);

		$this->setTemplateFile('favoriteitems');
	}

	function dispNcartOrderItems() 
	{
		global $lang;

		$oFileModel = &getModel('file');
		$oEpayView = &getView('epay');
		$oStoreController = &getController('ncart');
		$oNcartModel = &getModel('ncart');

		$logged_info = Context::get('logged_info');

		// get module config
		$config = $oNcartModel->getModuleConfig();
		Context::set('config',$config);

		if($config->guest_buy != 'Y' && !$logged_info)
		{
			return new Object(-1, 'msg_no_guest_buy');
		}

		$cartnos = Context::get('cartnos');
		$cart = $oNcartModel->getCartInfo($cartnos);

		if (!count($cart->item_list))
		{
			return new Object(-1, $lang->msg_no_items);
		}


		/*
		 * stock check
		 */

		$oNproductModel = &getModel('nproduct');

		//quantity
		foreach ($cart->item_list as $key=>$val) 
		{
			$item_info = $oNproductModel->getItemInfo($val->item_srl);

			if(!$stock[$val->item_srl])
			{
				if($stock[$val->item_srl] !== 0) $stock[$val->item_srl] = $oNproductModel->getItemExtraVarValue($val->item_srl, 'stock');
				if($stock[$val->item_srl] == '0') return new Object(-1, sprintf(Context::getLang('msg_not_enough_stock'), $item_info->item_name));
			}

			if($stock[$val->item_srl] != null)
			{
				if($stock[$val->item_srl] < $val->quantity) return new Object(-1, sprintf(Context::getLang('msg_not_enough_stock'), $item_info->item_name));
				if($stock[$val->item_srl] === 0 || $stock[$val->item_srl] > 0) $stock[$val->item_srl] = $stock[$val->item_srl] - $val->quantity;
				if($stock[$val->item_srl] < 0) return new Object(-1, sprintf(Context::getLang('msg_not_enough_stock'), $item_info->item_name));
			}
		}

		/*
		 * end
		 */

		Context::set('list',$cart->item_list);
		Context::set('sum_price',$cart->sum_price);
		Context::set('total_price',$cart->total_price);
		Context::set('delivery_fee',$cart->delivery_fee);
		Context::set('total_discounted_price',$cart->total_discounted_price);
		Context::set('total_discount_amount',$cart->total_discount_amount);
		
		// get order title
		$order_title = $oNcartModel->getOrderTitle($cart->item_list);
		$args->item_name = $order_title;

		// pass payment amount, item name, etc.. to epay module.
		// Context::set('payment_amount', 10000);
		$args->epay_module_srl = $this->module_info->epay_module_srl;
		$args->module_srl = $this->module_info->module_srl;
		$args->price = $cart->total_price;
		//$args->order_srl = $order_srl;
		
		if($logged_info)
		{
			$args->purchaser_name = $logged_info->nick_name;
			$args->purchaser_email = $logged_info->email_address;
			$args->purchaser_telnum = "$lang->msg_phone_input"."ex)010-0000-0000";
		}
		else if(!$logged_info)
		{
			$args->purchaser_name = $lang->non_member;
			$args->purchaser_email = $lang->msg_email_input;
			$args->purchaser_telnum = "$lang->msg_phone_input"."ex)010-0000-0000";
		}
		$args->join_form = 'fo_insert_order';

		$output = $oEpayView->getPaymentForm($args);
		if (!$output->toBool()) 
		{
			return $output;
		}
		$epay_form = $output->data;
		Context::set('epay_form', $epay_form);
		unset($args);

		Context::addJsFile('./modules/member/tpl/js/krzip_search.js');
		Context::set('soldout_process', $this->soldout_process);

		// mileage info
		$my_mileage = $oNcartModel->getMileage($logged_info->member_srl);
		if (!$my_mileage) $my_mileage = 0; 
		Context::set('my_mileage', $my_mileage);

		// fieldset
		$fieldset_list = $oNcartModel->getFieldSetList($this->module_info->module_srl);
		Context::set('fieldset_list', $fieldset_list);

		if($logged_info)
		{
			$args->member_srl = $logged_info->member_srl;
			$args->opt = '1';
			$output = executeQueryArray('ncart.getAddressList', $args);
			if (!$output->toBool()) return $output;
			unset($args);
			Context::set('address_list', $output->data);
		}

		$this->setTemplateFile('orderitems');
	}

	function dispNcartOrderComplete() 
	{
		$oNcartModel = &getModel('ncart');
		$oEpayModel = &getModel('epay');
		$logged_info = Context::get('logged_info');

		$order_srl = Context::get('order_srl');
		if (!$order_srl) return new Object(-1, 'msg_invalid_request');

		$payment_info = $oEpayModel->getTransactionByOrderSrl($order_srl);
		Context::set('payment_info',$payment_info);



		$order_info = $oNcartModel->getOrderInfo($order_srl);
		//$item_list = $oNcartModel->getPaidOrderItems($order_srl);
		Context::set('order_info', $order_info);
		$extra_vars = unserialize($order_info->extra_vars);

		// fieldset
		$fieldset_list = $oNcartModel->getFieldSetList($this->module_info->module_srl);
		foreach($fieldset_list as $key=>&$val)
		{
				foreach($val->fields as $key2=>&$field)
				{
						if(isset($extra_vars->{$field->column_name}))
						{
							$field->value = $extra_vars->{$field->column_name};
						}
				}
		}
		Context::set('fieldset_list', $fieldset_list);
		Context::set('order_status', $this->getOrderStatus());

		$this->setTemplateFile('ordercomplete');
	}

	function dispNcartNonOrderList() 
	{
		$non_order_srl = Context::get('non_order_srl');
		$non_password = Context::get('non_password');
		$logged_info = Context::get('logged_info');

		if(!$non_order_srl || !$non_password) return new Object(-1, '주문번호와 비밀번호를 입력해주세요.');
		
		$non_order_srl = trim($non_order_srl);
		$non_password = trim($non_password);
		
		$args->order_srl = $non_order_srl;

		//입력 받은 order_srl 로 data 얻어오기.
		
		$output = executeQueryArray('ncart.getOrderInfo', $args);

		if(!$output->data) return new Object(-1,'주문번호가 잘못 됬습니다.');


		//order_srl 로 암호 얻어 와서 입력 받은 값과 비교.

		$compare_password = $output->data[0]->non_password;

		$compare_p=substr($compare_password, 0, 12);
		
		$non_password = crypt($non_password,$compare_password);

		if($non_password != $compare_password) return new Object(-1,'비밀번호가 다릅니다.');

		$oNcartModel = &getModel('ncart');
		$config = $oNcartModel->getModuleConfig();
		
		$args->member_srl = 0;
		$args->non_order_srl =  $non_order_srl;
		$args->startdate = $startdate . '000000';
		$args->enddate = $enddate . '235959';
		$output = executeQueryArray('ncart.getNonOrderItems', $args);

		$item_list = $output->data;
		$order_list = array();
		if ($item_list) {
			foreach ($item_list as $key=>$val) {
				$item = new ncartItem('ncart', $val, $config->currency, $config->as_sign, $config->decimals);
				if ($item->option_srl)
				{
					$item->price += ($item->option_price);
				}
				$item_list[$key] = $item;

				if (!isset($order_list[$val->order_srl])) $order_list[$val->order_srl] = array();

				$order_list[$val->order_srl][] = $item;
			}
		}

		Context::set('list', $item_list);
		Context::set('order_list', $order_list);
		Context::set('order_status', $this->getOrderStatus());
		Context::set('delivery_inquiry_urls', $this->delivery_inquiry_urls);

		$this->setTemplateFile('orderlist');

		Context::set('non_password', 0);

	}



	function dispNcartOrderDetail() 
	{
		$oFileModel = &getModel('file');
		$oEpayModel = &getModel('epay');
		$oNcartModel = &getModel('ncart');

		$logged_info = Context::get('logged_info');

		$order_srl = Context::get('order_srl');
		$order_info = $oNcartModel->getOrderInfo($order_srl);

		Context::set('order_info', $order_info);
		Context::set('order_status', $this->getOrderStatus());

		$payment_info = $oEpayModel->getTransactionByOrderSrl($order_srl);
		Context::set('payment_info',$payment_info);
		Context::set('payment_method',$this->getPaymentMethods());

		Context::set('delivery_inquiry_urls', $this->delivery_inquiry_urls);
		Context::set('delivery_companies', $oNcartModel->getDeliveryCompanies());
		Context::set('soldout_process', $this->soldout_process);

		$this->setTemplateFile('orderdetail');
	}

	function dispNcartReplyComment() 
	{
		// 권한 체크
		if(!$this->grant->write_comment) return new Object(-1,'msg_not_permitted');

		// 목록 구현에 필요한 변수들을 가져온다
		$parent_srl = Context::get('comment_srl');

		// 지정된 원 댓글이 없다면 오류
		if(!$parent_srl) return new Object(-1, 'msg_invalid_request');

		// 해당 댓글를 찾아본다
		$oCommentModel = &getModel('comment');
		$oSourceComment = $oCommentModel->getComment($parent_srl, $this->grant->manager);

		// 댓글이 없다면 오류
		if(!$oSourceComment->isExists()) return new Object(-1, 'msg_invalid_request');
		if(Context::get('document_srl') && $oSourceComment->get('document_srl') != Context::get('document_srl')) return new Object(-1, 'msg_invalid_request');

		// 대상 댓글을 생성
		$oComment = $oCommentModel->getComment();
		$oComment->add('parent_srl', $parent_srl);
		$oComment->add('document_srl', $oSourceComment->get('document_srl'));

		// 필요한 정보들 세팅
		Context::set('oSourceComment',$oSourceComment);
		Context::set('oComment',$oComment);
		Context::set('module_srl',$this->module_info->module_srl);

		/** 
		 * 사용되는 javascript 필터 추가
		 **/
		//Context::addJsFilter($this->module_path.'tpl/filter', 'insert_comment.xml');

		$this->setTemplateFile('commentform');
	}

	function dispNcartAddressList() {
		$oNcartModel = &getModel('ncart');
		$oNcartModel->checkBrowser(); // iphone check

		$logged_info = Context::get('logged_info');
		if (!$logged_info) return new Object(-1, 'msg_login_required');

		$args->member_srl = $logged_info->member_srl;
		$args->opt = '1';
		$output = executeQueryArray('ncart.getAddressList', $args);
		if (!$output->toBool()) return $output;
		Context::set('list', $output->data);

		$fieldset_list = $oNcartModel->getFieldSetList($this->module_info->module_srl);
		Context::set('fieldset_list', $fieldset_list);

		$this->setLayoutFile('default_layout');
		$this->setTemplateFile('addresslist');
	}

	function dispNcartAddressManagement() {
		$oNcartModel = &getModel('ncart');

		$logged_info = Context::get('logged_info');
		if (!$logged_info) return new Object(-1, 'msg_login_required');

		$args->member_srl = $logged_info->member_srl;
		$args->opt = '1';
		$output = executeQueryArray('ncart.getAddressList', $args);
		if (!$output->toBool()) return $output;

		Context::set('list', $output->data);

		$fieldset_list = $oNcartModel->getFieldSetList($this->module_info->module_srl);
		Context::set('fieldset_list', $fieldset_list);

		$this->setLayoutFile('default_layout');
		$this->setTemplateFile('addressmanagement');

		Context::addJsFile('./modules/member/tpl/js/krzip_search.js');
	}

	function dispNcartRecentAddress() {
		$oNcartModel = &getModel('ncart');

		$logged_info = Context::get('logged_info');
		if (!$logged_info) return new Object(-1, 'msg_login_required');

		$args->member_srl = $logged_info->member_srl;
		$args->opt = '2';
		$args->sort_index = 'address_srl';
		$args->sort_order = 'desc';
		$output = executeQueryArray('ncart.getAddressList', $args);
		if (!$output->toBool()) return $output;
		Context::set('list', $output->data);

		$fieldset_list = $oNcartModel->getFieldSetList($this->module_info->module_srl);
		Context::set('fieldset_list', $fieldset_list);

		$this->setLayoutFile('default_layout');
		$this->setTemplateFile('recentaddress');
	}

	function dispNcartLogin() {

		$oNcartModel = &getModel('ncart');
		// get module config
		$config = $oNcartModel->getModuleConfig();
		Context::set('config',$config);

		$this->setTemplateFile('login_form');

	}

	function dispNcartNonLoginOrder() {

		$this->setTemplateFile('orderlistlogin');

	}
}
/* End of file ncart.view.php */
/* Location: ./ncart/ncart.view.php */
