<?php
/*
 * shopping/product/unit/LoadList.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(dirname(__FILE__)))
.DIRECTORY_SEPARATOR.'system'
.DIRECTORY_SEPARATOR.'login'
.DIRECTORY_SEPARATOR.'ModuleBase.class.php');
require_once( dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'PackageConfig.class.php' );
require_once( dirname(dirname(__FILE__))
.DIRECTORY_SEPARATOR.'DaoShoppingProduct.class.php' );
class shopping_bookmark_LoadList extends system_login_ModuleBase {
	
	function shopping_bookmark_LoadList() {
	}
	function execute( & $request ) {
		$dbo				= $request->getAttribute( 'dbo' );
		$pageRows			= stripslashes( $_GET['pr'] );
		$pageNumber			= stripslashes( $_GET['pn'] );
		$sortItem			= $_GET['shpsi'];
		$sortOrder			= $_GET['shpso'];
		$shoppingCategoryId	= $_GET['shpci'];
		$userAgentClass			= $request->getAttribute('spider.access_agent_class');

		$accessAgentClass	= $request->getAttribute('spider.access_agent_class');
		$loginUserObject	= $this->getLoginUserObject( $request );
		
		// ページング制御
		if ( !is_numeric( $pageNumber ) || $pageNumber < 1 ) {
			$pageNumber	= 1;
		}
		if ( !is_numeric( $pageRows ) || $pageRows < 1 ) {
			if( 'au'==$userAgentClass || 'docomo'==$userAgentClass || 'docomo2'==$userAgentClass || 'softbank'==$userAgentClass) {
				$pageRows		= 5;
			} else {
				$pageRows		= 20;
			}
		} else if ( $pageRows > 100 ) {
			if( 'au'==$userAgentClass || 'docomo'==$userAgentClass || 'docomo2'==$userAgentClass || 'softbank'==$userAgentClass) {
				$pageRows		= 5;
			} else {
				$pageRows		= 20;
			}
		}
		// 並び替え制御
		$sortOrderArray = array();
		if ( is_array($sortOrder) ) {
			$sortOrderArray = $sortOrder;
		} else {
			if ( strlen(trim($sortOrder)) > 0 ) {
				array_push($sortOrderArray,$sortOrder);
			}
		}
		$sortItemArray			= array();
		$orderConditionArray	= array();
		$duplicateCheckArray	= array();
		if ( is_array($sortItem) ) {
			$sortItemArray = $sortItem;
		} else {
			if ( strlen(trim($sortItem)) > 0 ) {
				array_push($sortItemArray,$sortItem);
			}
		}
		// 並べ替え
		if ( !is_array($sortItemArray) || count($sortItemArray) == 0 ) {
			// 並び替え項目が指定されていなければ
			array_push($sortItemArray,'order');
			array_push($sortItemArray,'upd');
			$sortOrderArray	= array();
			array_push($sortOrderArray,'ASC');
			array_push($sortOrderArray,'DESC');
		} else {
			// 並び替え項目が指定されている場合
			if( !in_array('order',$sortItemArray) ) { array_push($sortItemArray,'order'); }
			if( !in_array('upd',$sortItemArray) ) { array_push($sortItemArray,'upd'); }
			if( !in_array('reg',$sortItemArray) ) { array_push($sortItemArray,'reg'); }
		}
		foreach ( $sortItemArray as $key => $sortItemName ) {
			$orderCondition	= '';
			if ( strlen(trim($sortItemName)) > 0 && !in_array($sortItemName,$duplicateCheckArray) ) {
				// 並び替えの設定
				if ( strlen(trim($sortOrderArray[$key])) == 0 ) {
					// 何も指定されていなければ、降順
					$sortOrderArray[$key]	= 'DESC';
				} else {
					if( preg_match('/^[aA][sS][cC]$/',$sortOrderArray[$key] ) > 0 ) {
						$sortOrderArray[$key]	= 'ASC';
					} else {
						$sortOrderArray[$key]	= 'DESC';
					}
				}

				if( 'did' == $sortItemName ) {
					$orderCondition	= TABLE_NAME_SHOPPING_PRODUCT.'.product_id '.$sortOrderArray[$key];
				} else if ( 'upd' == $sortItemName ) {
					$orderCondition	= TABLE_NAME_SHOPPING_PRODUCT.'.updated_date '.$sortOrderArray[$key];
				} else if ( 'dname' == $sortItemName ) {
					$orderCondition	= TABLE_NAME_SHOPPING_PRODUCT.'.product_kana '.$sortOrderArray[$key];
				} else if ( 'order' == $sortItemName ) {
					$orderCondition	= TABLE_NAME_SHOPPING_PRODUCT.'.order_number '.$sortOrderArray[$key];
				}
				if( strlen($orderCondition) > 0 ) {
					array_push($orderConditionArray,$orderCondition);
					array_push($duplicateCheckArray,$sortItemName);
				}
			}
		}
		$orderConditionString	= '';
		if ( count( $orderConditionArray ) > 0 ) {
			$orderConditionString	= ' ORDER BY ' . implode( ', ', $orderConditionArray );
		}
		
		$categoryIdArray = array();
		if ( is_array($shoppingCategoryId) ) {
			$categoryIdArray = $shoppingCategoryId;
		} else {
			if ( strlen(trim($shoppingCategoryId))>0 ) {
				array_push($categoryIdArray,$shoppingCategoryId);
			}
		}

		$condition_array	= array();
		$joinTables			= array();
		
		// 
		if( is_object($loginUserObject)
			&& strlen($loginUserObject->member_id)>0 ) {
			$str = TABLE_NAME_SHOPPING_PRODUCT_BOOKMARK.'.member_id='.$dbo->quote($loginUserObject->member_id);
			array_push( $condition_array, $str );
		} else {
			$request->addLocaledError('system.error.login.user.requirelogin',SPIDER_LOG_LEVEL_ERROR,array());
			return false;
		}
		
		// 状態フラグ条件
		$str = '( '.TABLE_NAME_SHOPPING_PRODUCT.'.status_flag>=100'
			.' AND '.TABLE_NAME_SHOPPING_PRODUCT.'.status_flag<200'
			.' )';
		array_push( $condition_array, $str );
		
		// カテゴリ条件
		if( count($categoryIdArray) > 0 ) {
			$categoryConditionArray	= array();
			foreach( $categoryIdArray as $categoryId ) {
				if( strlen(trim($categoryId)) > 0 ) {
					$categoryObject	= spider_Controller::createObject('shopping_DaoShoppingCategory');
					if( $dbo->loadById( $categoryObject, $categoryId, true ) ) {
						array_push( $categoryConditionArray, $dbo->quote($categoryId) );
						$idArray	= $categoryObject->getAllChildCategoryIdArray();
						if( is_array( $idArray ) ) {
							foreach( $idArray as $id ) {
								array_push( $categoryConditionArray, $dbo->quote($id) );
							}
						}
					}
				}
			}
			if( count($categoryConditionArray) > 0 ) {
				array_push( $joinTables,TABLE_NAME_SHOPPING_CATEGORY_PRODUCT );
				$str	= TABLE_NAME_SHOPPING_CATEGORY_PRODUCT.'.category_id IN('.implode(',',$categoryConditionArray).')';
				array_push( $condition_array, $str );
			}
		}
		
		$condition_string	= '';
		if ( count( $condition_array ) > 0 ) {
			$condition_string	= ' WHERE ' . implode( ' AND ', $condition_array );
		}
		
		// トータル件数を取得
		$sql	= 'SELECT COUNT(DISTINCT('.TABLE_NAME_SHOPPING_PRODUCT. '.product_id)) '
			. ' FROM ' . TABLE_NAME_SHOPPING_PRODUCT
		;
		if ( in_array( TABLE_NAME_SHOPPING_CATEGORY_PRODUCT, $joinTables ) ) {
			$sql	.= ' LEFT OUTER JOIN ' . TABLE_NAME_SHOPPING_CATEGORY_PRODUCT
				. ' ON ' . TABLE_NAME_SHOPPING_CATEGORY_PRODUCT . '.product_id='.TABLE_NAME_SHOPPING_PRODUCT.'.product_id '
			;
		}
		$sql	.= ' LEFT OUTER JOIN ' . TABLE_NAME_SHOPPING_PRODUCT_BOOKMARK
			. ' ON ' . TABLE_NAME_SHOPPING_PRODUCT_BOOKMARK . '.product_id='.TABLE_NAME_SHOPPING_PRODUCT.'.product_id '
		;
		$sql	.= $condition_string;
		$totalCount	= 0;
		$totalCount	= $dbo->queryOne( $sql );
		if ( $totalCount === false ) {
			$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
		} else {
			if ( is_numeric( $totalCount ) || $totalCount < 0 ) {
				$totalPage		= ceil( $totalCount / $pageRows );
			} else {
				$totalCount	= 0;
				$totalPage		= 1;
			}
		}
		// オフセットの整理
		if ( !is_numeric( $pageNumber ) || $pageNumber <= 0 ) {
			$pageNumber	= 1;
		} else if ( $pageNumber > $totalPage	 ) {
			$pageNumber	= $totalPage;
		}
		
		// IDをページ分取得
		$sql	= 'SELECT DISTINCT '.TABLE_NAME_SHOPPING_PRODUCT.'.* '
			. ' FROM ' . TABLE_NAME_SHOPPING_PRODUCT
		;
		if ( in_array( TABLE_NAME_SHOPPING_CATEGORY_PRODUCT, $joinTables ) ) {
			$sql	.= ' LEFT OUTER JOIN ' . TABLE_NAME_SHOPPING_CATEGORY_PRODUCT
				. ' ON ' . TABLE_NAME_SHOPPING_CATEGORY_PRODUCT . '.product_id='.TABLE_NAME_SHOPPING_PRODUCT.'.product_id '
			;
		}
		$sql	.= ' LEFT OUTER JOIN ' . TABLE_NAME_SHOPPING_PRODUCT_BOOKMARK
			. ' ON ' . TABLE_NAME_SHOPPING_PRODUCT_BOOKMARK . '.product_id='.TABLE_NAME_SHOPPING_PRODUCT.'.product_id '
		;
		$sql	.= $condition_string
			. $orderConditionString
		;
		$dbo->setLimit( $pageRows, ( $pageNumber - 1 ) * $pageRows );
		$shoppingProductObject	= spider_Controller::createObject('shopping_DaoShoppingProduct');
		$productObjectArray	= $dbo->queryAll( $sql, $shoppingProductObject, false, false );
		$lastQueryHash['loadQuery']	= $sql;
		$request->setSession(SHOPPING_SESSION_NAME_PRODUCT_SEARCH_LAST_QUERY, $lastQueryHash, SPIDER_SESSION_SCOPE_GLOBAL);
		if ( $productObjectArray === false ) {
			$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
		} else {
			$productIdArray		= array();
			$productObjectHash		= array();
			foreach( $productObjectArray as $key => $object ) {
				$productId			= $object->product_id;
				$this->setLockStatus( $request, $object );
				if( 'default' != $accessAgentClass ) {
					// 携帯の場合は文字数を削っておく
					if( mb_strlen( $object->description ) > 60 ) {
						$object->description	= mb_substr( $object->description, 0, 56 ).'..';
					}
				}
				// オプション文字列の分割
				for( $i=1; $i<=5; $i++ ) {
					$optionFieldName		= 'option'.$i.'_items';
					$optionNameArrayName	= 'option'.$i.'_item_array';
					$optionPriceArrayName	= 'option'.$i.'_price_array';
					if( strlen( $object->$optionFieldName ) > 0 ) {
						// オプション選択肢が設定されているなら処理
						$object->$optionFieldName			= str_replace("\r\n","\n",$object->$optionFieldName);
						$object->$optionFieldName			= str_replace("\r","\n",$object->$optionFieldName);
						$object->$optionNameArrayName		= array();
						$object->$optionPriceArrayName	= array();
						$itemStringArray				= explode("\n",$object->$optionFieldName);
						if( preg_match('/\\:/',$object->$optionFieldName) > 0 ) {
							// :を含むなら価格と分割
							foreach( $itemStringArray as $str ) {
								list( $itemName, $itemPrice )	= explode(':',$str);
								array_push($object->$optionNameArrayName,$itemName);
								if( strlen($itemPrice)==0 ) {
									$itemPrice	= 0;
								}
								array_push($object->$optionPriceArrayName,$itemPrice);
							}
						} else {
							$object->$optionNameArrayName	= $itemStringArray;
						}
					}
				}
				$productObjectHash[$productId]	= $object;
				array_push($productIdArray,$object->product_id);
			}
			// 所属カテゴリIDの読み込み
			$sql	= 'SELECT * FROM '.TABLE_NAME_SHOPPING_CATEGORY_PRODUCT
				.' WHERE product_id IN (\''.implode('\',\'',$productIdArray).'\')'
				.' ORDER BY order_number ASC'
			;
			$rows	= $dbo->queryAll( $sql, 'hash' );
			if( false === $rows ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
			} else {
				foreach( $rows as $row ) {
					$productId	= trim($row['product_id']);
					$categoryId	= trim($row['category_id']);
					if( isset($productObjectHash[$productId]) ) {
						array_push($productObjectHash[$productId]->categoryIdArray,$categoryId);
					}
				}
			}
			// 画像ファイル情報の読み込み
			$sql	= 'SELECT * FROM '.TABLE_NAME_SHOPPING_PRODUCT_FILE
				.' WHERE product_id IN (\''.implode('\',\'',$productIdArray).'\')'
				.' ORDER BY order_number ASC'
			;
			$rows	= $dbo->queryAll( $sql, 'hash', false );
			if( false === $rows ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($sql));
			} else {
				foreach( $rows as $row ) {
					$productId		= trim($row['product_id']);
					$fileId			= trim($row['file_id']);
					$orderNumber	= trim($row['order_number']);
					if( isset($productObjectHash[$productId]) ) {
						$productObjectHash[$productId]->fileIdArray[$orderNumber]	= $fileId;
					}
				}
			}
			
			// 販売単位の読み込み
			$unitIdArray			= array();
			$daoShoppingProductUnit		= spider_Controller::createObject('shopping_DaoShoppingProductUnit');
			$sql	= 'SELECT * FROM '.TABLE_NAME_SHOPPING_PRODUCT_UNIT
				.' WHERE product_id IN (\''.implode('\',\'',$productIdArray).'\')'
				.' AND status_flag<200 '
			;
			// 状態フラグ条件
			$sql .= ' AND ( '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.status_flag>=100'
				.' AND '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.status_flag<200 )'
				.' AND ( '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.open_date IS NULL OR '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.open_date<='.$dbo->quote(date('Y-m-d H:i:s')).' )'
				.' AND ( '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.close_date IS NULL OR '.TABLE_NAME_SHOPPING_PRODUCT_UNIT.'.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 ) {
				return false;
			} else {
				foreach( $rows as $row ) {
					$productId		= trim($row->product_id);
					if( isset($productObjectHash[$productId]) ) {
						// オプション文字列の分割
						for( $i=1; $i<=5; $i++ ) {
							$optionFieldName		= 'option'.$i.'_items';
							$optionNameArrayName	= 'option'.$i.'_item_array';
							$optionPriceArrayName	= 'option'.$i.'_price_array';
							$optionCostArrayName	= 'option'.$i.'_cost_array';
							if( strlen( $row->$optionFieldName ) > 0 ) {
								// オプション選択肢が設定されているなら処理
								$row->$optionFieldName			= str_replace("\r\n","\n",$row->$optionFieldName);
								$row->$optionFieldName			= str_replace("\r","\n",$row->$optionFieldName);
								$row->$optionNameArrayName		= array();
								$row->$optionPriceArrayName		= array();
								$row->$optionCostArrayName		= array();
								$itemStringArray				= explode("\n",$row->$optionFieldName);
								if( preg_match('/\\:/',$row->$optionFieldName) > 0 ) {
									// :を含むなら価格と分割
									foreach( $itemStringArray as $str ) {
										list( $itemName, $itemPrice, $itemCost )	= explode(':',$str);
										array_push($row->$optionNameArrayName,$itemName);
										if( strlen($itemPrice)==0 ) {
											$itemPrice	= 0;
										}
										if( strlen($itemCost)==0 ) {
											$itemCost	= 0;
										}
										array_push($row->$optionPriceArrayName,$itemPrice);
										array_push($row->$optionCostArrayName,$itemCost);
									}
								} else {
									$row->$optionNameArrayName	= $itemStringArray;
								}
							}
						}
						$row->shoppingProductObject	= & $productObjectHash[$productId];
						array_push($productObjectHash[$productId]->unitObjectArray,$row);
						// unit_id配列の作成
						if ( !in_array($row->unit_id,$unitIdArray) ) {
							array_push($unitIdArray,$dbo->quote($row->unit_id));
						}
					}
				}
			}
			// 販売単位に関連する商品フラグIDのハッシュを作成
			$unitFlagIdHash = array();
			if( count($unitIdArray) > 0 ) {
				$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, false );
				if ( $rows === false ) {
					return false;
				} 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']));
					}
				}
			}

			$productObjectArray	= $productObjectHash;

			$request->setAttribute( 'shopping.bookmark.product_array',	$productObjectArray );
			$request->setAttribute( 'shopping.bookmark.total_count',		$totalCount );
			$request->setAttribute( 'shopping.bookmark.total_page',		$totalPage );
			$request->setAttribute( 'shopping.bookmark.page_number',		$pageNumber );
			$request->setAttribute( 'shopping.bookmark.page_rows',		$pageRows );
			$request->setAttribute( 'shopping.bookmark.sort_item_array',	$sortItemArray );
			$request->setAttribute( 'shopping.bookmark.sort_order_array',$sortOrderArray );
			$request->setAttribute( 'shopping.bookmark.category_id_array',	$categoryIdArray );

			$request->setAttribute( 'shopping.bookmark.unit_flag_id_hash',	$unitFlagIdHash );
			
			$has_next_page	= false;
			if( $pageNumber < $totalPage ) {
				$has_next_page	= true;
			}
			$request->setAttribute( 'shopping.bookmark.has_next_page', $has_next_page );
			$has_prev_page	= false;
			if( $pageNumber > 1 ) {
				$has_prev_page	= true;
			}
			$request->setAttribute( 'shopping.bookmark.has_prev_page', $has_prev_page );
			
			// ページナビゲーション配列作成
			$page_navi_array = array();
			if ( $pageNumber < 10 ) {
				if ( $totalPage < 10 ) {
					for($i=1;$i<=$totalPage;$i++) {
						array_push($page_navi_array,$i);
					}
				} else {
					for($i=1;$i<=10;$i++) {
						array_push($page_navi_array,$i);
					}
				}
			} else {
				$startPage	= floor(($pageNumber-1)/10) * 10 + 1;
				for($i=$startPage;( $i<$startPage+10 && $i<=$totalPage );$i++) {
					array_push($page_navi_array,$i);
				}
			}
			$request->setAttribute('shopping.bookmark.page_navi_array', $page_navi_array );
			
		}
	}
}
?>