<?php
/*
 * shopping/product/unit/Load.class.php
 * 
 * CopyRight(C) 2010 Shopformer Development Team. All Right Reserved
 * URL: http://sourceforge.jp/projects/shopformer/
 * 
 * 
 * Mail: m_nakashima@users.sourceforge.jp
 * Auther: Masanori Nakashima
 * Last Update: 2010-06-18
 */
require_once( dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'PackageConfig.class.php');
class shopping_product_Load extends system_login_ModuleBase {
	
	function shopping_product_Load() {
	}
	function execute( & $request ) {
		
		$dbo					= $request->getAttribute( 'dbo' );
		$productNumber			= stripslashes( $_GET['shpdn'] );
		$productId				= stripslashes( $_GET['shpdi'] );
		$owner					= trim( stripslashes( $_GET['owner']) );
		$shoppingProductObject	= spider_Controller::createObject('shopping_DaoShoppingProduct');
		$loginUserObject		= $this->getLoginUserObject( $request );
		
		if ( strlen(trim($productNumber)) == 0 && strlen(trim($productId)) == 0 ) {
			$request->addLocaledError('shopping.error.product.invalidid',SPIDER_LOG_LEVEL_FATAL,array(''));
		} else if( strlen(trim($productNumber)) > 0 && preg_match('/^[0-9]+$/',$productNumber) > 0 ){
			if ( !$dbo->loadByNumber( $shoppingProductObject, $productNumber, false ) ) {
				$request->addLocaledError('shopping.error.product.notfound',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		} else if( strlen(trim($productId)) > 0 && preg_match('/^[0-9a-zA-Z\\_]+$/',$productId) > 0 ){
			if ( !$dbo->loadById( $shoppingProductObject, $productId, false ) ) {
				$request->addLocaledError('shopping.error.product.notfound',SPIDER_LOG_LEVEL_FATAL,array(''));
			}
		}

		if( !$request->isError() ) {
			$shoppingProductObject->openTargetArray	= array();
			// 所属カテゴリの読み込み
			$shoppingProductObject->categoryIdArray	= array();
			$shoppingProductObject->categoryIdArray_org	= array();
			$sql	= 'SELECT category_id FROM '.TABLE_NAME_SHOPPING_CATEGORY_PRODUCT
				.' WHERE product_id='.$dbo->quote($shoppingProductObject->product_id)
				.' ORDER BY order_number ASC'
			;
			$rows	= $dbo->queryAll( $sql, 'hash', false );
			if ( $rows === false ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
			} else {
				foreach( $rows as $row ) {
					array_push( $shoppingProductObject->categoryIdArray, trim($row['category_id']));
					array_push( $shoppingProductObject->categoryIdArray_org, trim($row['category_id']));
				}
			}
			// 添付画像の読み込み
			$shoppingProductObject->fileIdArray		= array();
			$shoppingProductObject->fileIdArray_org	= array();
			$sql	= 'SELECT file_id,order_number FROM '.TABLE_NAME_SHOPPING_PRODUCT_FILE
				.' WHERE product_id='.$dbo->quote($shoppingProductObject->product_id)
				.' ORDER BY order_number ASC'
			;
			$rows	= $dbo->queryAll( $sql, 'hash', false );
			if ( $rows === false ) {
				return false;
			} else {
				foreach( $rows as $row ) {
					$shoppingProductObject->fileIdArray[$row['order_number']]	= trim($row['file_id']);
					$shoppingProductObject->fileIdArray_org[$row['order_number']]	= trim($row['file_id']);
				}
			}
			// 販売単位の読み込み
			$unitIdArray		= array();
			$shoppingProductObject->unitObjectArray		= array();
			$daoShoppingProductUnit		= spider_Controller::createObject('shopping_DaoShoppingProductUnit');
			$sql	= 'SELECT * FROM '.TABLE_NAME_SHOPPING_PRODUCT_UNIT
				.' WHERE product_id='.$dbo->quote($shoppingProductObject->product_id)
			;
			if( $this->isLogin( $request ) && SYSTEM_LOGIN_USER_ADMINISTRATORS == $loginUserObject->getLoginGroupLevel() ) {
				// 管理者ログインの場合、削除以外の販売単位を閲覧可
				$sql	.= ' AND status_flag < 200 ';
			} else if( $this->isLogin( $request ) && preg_match('/^[lL][oO][gG][iI][nN]$/',$owner) > 0 ) {
				// 管理者以外でログインしている場合、自身の販売単位は削除以外閲覧可、他販売単位は掲載中のみ閲覧可
				$sql	.= ' AND (';
				$sql	.= ' ( owner_id='.$dbo->quote($loginUserObject->getUniqueId());
				$sql	.= ' AND status_flag < 200 )';
				$sql	.= ' OR ';
				$sql	.= ' ( owner_id<>'.$dbo->quote($loginUserObject->getUniqueId());
				$sql	.= ' AND status_flag >= 100 ';
				$sql	.= ' AND status_flag < 200 ';
				$sql	.= ' AND ( open_date IS NULL OR open_date<='.$dbo->quote(date('Y-m-d H:i:s')).' )';
				$sql	.= ' AND ( close_date IS NULL OR close_date>='.$dbo->quote(date('Y-m-d H:i:s')).' ) )';
				$sql	.= ' )';
			} else {
				$sql	.= ' AND status_flag >= 100 ';
				$sql	.= ' AND status_flag < 200 ';
				$sql	.= ' AND ( open_date IS NULL OR open_date<='.$dbo->quote(date('Y-m-d H:i:s')).' )';
				$sql	.= ' AND ( close_date IS NULL OR close_date>='.$dbo->quote(date('Y-m-d H:i:s')).' )';
			}
			$sql	.= ' ORDER BY order_number ASC';
			$rows	= $dbo->queryAll( $sql, $daoShoppingProductUnit, false, false );
			if ( $rows === false ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
			} else {
				foreach( $rows as $row ) {
					$row->loadRelationExceptProduct( $dbo );
					$row->shoppingProductObject	= & $shoppingProductObject;
					// 公開設定
					$row->memberViewableArray	= array();
					$row->memberPurchasableArray	= array();
					$memberViewableStr	= sprintf('%016b',$row->member_viewable);
					$memberPurchasableStr	= sprintf('%016b',$row->member_purchasable);
					$keyCol	= 0;
					foreach ( $GLOBALS['MEMBER_MEMBER_CLASS_HASH'] as $key=>$value ) {
						if ( substr($memberViewableStr,15-$keyCol,1) == '1' ) {
							array_push($row->memberViewableArray,$key);
						}
						if ( substr($memberPurchasableStr,15-$keyCol,1) == '1' ) {
							array_push($row->memberPurchasableArray,$key);
						}
						$keyCol++;
					}
					// 
					$row->optimizeLoadedVars($dbo);
					array_push($shoppingProductObject->unitObjectArray,$row);
					array_push($unitIdArray,$dbo->quote($row->unit_id));
				}
			}
			// 販売単位に関連する商品フラグIDのハッシュを作成
			if( count($unitIdArray) > 0 ) {
				$unitFlagIdHash = array();
				$sql	= 'SELECT '.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.unit_id, '
					. TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.flag_id '
					. ' FROM '.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION
					.' WHERE unit_id IN ('. implode( ',', $unitIdArray ) . ')'
					.' AND (('.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.open_date IS NULL'
					.' AND '.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.close_date IS NULL)' 
					.' OR ('.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.open_date <= '.$dbo->quote(date('Y-m-d'))
					.' AND '.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.close_date >= '.$dbo->quote(date('Y-m-d')).')'
					.' OR ('.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.open_date <= '.$dbo->quote(date('Y-m-d'))
					.' AND '.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.close_date IS NULL)'
					.' OR ('.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.open_date IS NULL'
					.' AND '.TABLE_NAME_SHOPPING_PRODUCT_UNIT_FLAG_RELATION.'.close_date >= '.$dbo->quote(date('Y-m-d')).'))'
				;
				$rows	= $dbo->queryAll( $sql, 'hash', false );
				if ( $rows === false ) {
					$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
				} else {
					foreach( $rows as $row ) {
						$unitId		= trim($row['unit_id']);
						if ( !is_array($unitFlagIdHash[$unitId]) ) {
							$unitFlagIdHash[$unitId] = array();
						}
						array_push($unitFlagIdHash[$unitId],trim($row['flag_id']));
					}
				}
				$shoppingProductObject->unitFlagIdHash	= $unitFlagIdHash;
			} else {
				$shoppingProductObject->unitFlagIdHash	= array();
			}
			// オプション文字列の分割
			$shoppingProductObject->optimizeLoadedVars();
			// オーナー情報の読み込み
			$ownerId = $shoppingProductObject->owner_id;
			if ( $shoppingProductObject->owner_id ) {
				$memberObject	= spider_Controller::createObject('member_DaoMember');
				if( strlen(trim($ownerId)) > 0 ) {
					// 会員IDが指定されているなら編集の為読み込み
					if( $dbo->loadById( $memberObject, $ownerId ) ) {
						$shoppingProductObject->ownerObject = $memberObject;
					}
				}
			}
			// 公開設定
			if( $this->isLogin( $request )
				&& SYSTEM_LOGIN_USER_ADMINISTRATORS == $loginUserObject->getLoginGroupLevel() ) {
			} else {
				if ( !in_array($loginUserObject->member_class,$shoppingProductObject->memberViewableArray) ) {
					$request->addLocaledError('shopping.error.product.permittion.view',SPIDER_LOG_LEVEL_FATAL,array(''));
				}
			}
			// 関連商品IDの読み込み
			$sql	= 'SELECT * FROM '.TABLE_NAME_SHOPPING_PRODUCT_RELATION
			.' LEFT OUTER JOIN '.TABLE_NAME_SHOPPING_PRODUCT
			.' ON '.TABLE_NAME_SHOPPING_PRODUCT.'.product_id='.TABLE_NAME_SHOPPING_PRODUCT_RELATION.'.related_product_id'
			.' WHERE '.TABLE_NAME_SHOPPING_PRODUCT_RELATION.'.product_id='.$dbo->quote($shoppingProductObject->product_id)
			.' AND '.TABLE_NAME_SHOPPING_PRODUCT.'.status_flag BETWEEN 100 AND 199'
			;
			if( preg_match('/^\\/'.util_CharUtility::escapeRegxStr(SYSTEM_DIR_NAME_ADMIN_PANEL).'\\//',SPIDER_URI_APP) > 0 ){
				// 管理パネルでは条件なし
			} else if( $this->isLogin( $request ) && is_a($loginUserObject,'member_DaoMember') ){
				// 会員ログインの場合
				$definedClassKeyArray	= array_keys($GLOBALS['MEMBER_MEMBER_CLASS_HASH']);
				$keyCol = 1;
				foreach ( $definedClassKeyArray as $key=>$classKey ) {
					if ( $classKey == $loginUserObject->member_class ) {
						break;
					}
					$keyCol = $keyCol * 2;
				}
				$sql	.= ' AND '.TABLE_NAME_SHOPPING_PRODUCT.'.member_viewable & '.$keyCol.' = '.$keyCol;
			} else {
				// ログインしていない場合
				$sql	.= ' AND '.TABLE_NAME_SHOPPING_PRODUCT.'.member_viewable & 1 = 1';
			}
			$sql	.= ' ORDER BY '.TABLE_NAME_SHOPPING_PRODUCT_RELATION.'.display_order ASC';
			$relatedProductObjectArray	= $dbo->queryAll( $sql, $shoppingProductObject, false, false );
			if( false === $relatedProductObjectArray ){
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
			} else {
				foreach( $relatedProductObjectArray as $n => $obj ) {
					$relatedProductObjectArray[$n]->loadRelatedFiles( $dbo );
				}
				$request->setAttribute('shopping.product.relatedProductObjectArray',$relatedProductObjectArray);
			}
			// 検索データ連携
			$shoppingProductObject->loadRelatedSearchData( $dbo );
			// 最近チェックした商品をクッキーに記録
			$recentProductIdStrings	= '';
			if( isset($_COOKIE['SHPPID']) && strlen(trim($_COOKIE['SHPPID'])) > 0 ){
				$recentProductIdStrings	= trim($_COOKIE['SHPPID']);
			}
			$recentProductIdArray	= explode(',',$recentProductIdStrings);
			if( !is_array($recentProductIdArray) ){
				$recentProductIdArray	= array();
			}
			if( !in_array($shoppingProductObject->product_id,$recentProductIdArray) ){
				array_unshift($recentProductIdArray,$shoppingProductObject->product_id);
			}
			if( count($recentProductIdArray) > 12 ){
				array_pop($recentProductIdArray);
			}
			$recentProductIdStrings	= implode(',',$recentProductIdArray);
			setcookie('SHPPID', $recentProductIdStrings, time()+(60*60*24*90));
			// 関連の深い商品の自動表示：同時に注文されたことがある or カテゴリが同じ or キーワードが同じ or
			
		}
		
		$request->setAttribute('shopping.product.product_object',	$shoppingProductObject);
	}
}
?>