<?php
/*
 * shopping/order/download/Execute.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.'PackageConfig.class.php' );
class shopping_order_download_Execute extends system_login_ModuleBase {
	
	function shopping_order_download_Execute(){
	}
	function execute( & $request ) {
		// 変数取得
		$dbo					= $request->getAttribute( 'dbo' );
		$sessionHashName		= 'shopping.order.download.columnSelectedArray';
		$sessionOffsetName		= 'shopping.order.download.currentOffset';
		$columnSelectedArray	= $request->getSession($sessionHashName);
		// 一度に書き込む数を固定
		$writeAtOnce	= 1;
		
		if( !is_array($columnSelectedArray) && strlen($columnSelectedArray) == 0 ) {
			$request->addLocaledError('system.error.common.csvdl.selectcolumn',SPIDER_LOG_LEVEL_FATAL,array(''));
		}
		// ダウンロードする対象クエリの確認
		$totalCount		= 0;
		$queryHash	= $request->getSession(SHOPPING_SESSION_NAME_ORDER_SEARCH_LAST_QUERY, SPIDER_SESSION_SCOPE_GLOBAL);
		if( !is_array($queryHash) ) {
			$request->addLocaledError('system.error.common.session.timeout',SPIDER_LOG_LEVEL_FATAL,array());
		} else if( strlen($queryHash['countQuery']) == 0 || strlen($queryHash['loadQuery']) == 0 ) {
			$request->addLocaledError('system.error.common.session.timeout',SPIDER_LOG_LEVEL_FATAL,array());
		} else {
			$totalCount	= $dbo->queryOne($queryHash['countQuery']);
			if ( $totalCount === false ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($queryHash['countQuery']));
			}
		}

		if( !$request->isError() ) {
			// 現在のオフセットを確認し登録されていなければ0に設定
			$offset			= $request->getSession($sessionOffsetName);
			if( preg_match('/^[0-9]+$/', $offset) == 0 ) {
				$offset		= 0;
			}
			$csvColumnOrder	= array();
			$pos	= 0;
			foreach( $columnSelectedArray as $columnVarName ) {
				$csvColumnOrder[$columnVarName]	= $pos;
				$pos++;
			}
			$dbo->setLimit( $writeAtOnce, $offset );
			$shoppingOrderObject	= spider_Controller::createObject('shopping_DaoShoppingOrder');
			$orderObjectArray	= $dbo->queryAll( $queryHash['loadQuery'], $shoppingOrderObject, true, false );
			if ( $orderObjectArray === false ) {
				$request->addLocaledError('database2.error.common',SPIDER_LOG_LEVEL_FATAL,array($queryHash['loadQuery']));
			} else {
				// ダウンロード一時ファイルURI
				$tmpUri	= '/shopping/order/download/orders.csv';
				$writer	= spider_Controller::createObject('system_DataFileWriter');
				if( 0 == $offset ) {
					// オフセットが0の場合書き込みモードでオープン
					if( $writer->open( $request, $tmpUri, 'w', DIR_NAME_TMP) ) {
						// カラム名を一行目に出力
						$num	= 0;
						foreach( $columnSelectedArray as $columnVarName ) {
							if( 'item_all' == $columnVarName ) {
							} else {
								if( $num > 0 ) { $writer->write(','); }
								$columnViewName	= '';
								if( isset($GLOBALS['SHOPPING_ORDER_CSV_DEFINITION'][$columnVarName]) ) {
									$columnViewName	= $GLOBALS['SHOPPING_ORDER_CSV_DEFINITION'][$columnVarName];
								}
								$writer->write(mb_convert_encoding('"'.str_replace('"','""',$columnViewName).'"', 'SJIS-win', 'UTF-8'));
								$num++;
							}
						}
						// 購入商品情報の項目ラベル一行目を商品最大数の数だけ書き込む
						if( in_array( 'item_all', $columnSelectedArray ) ) {
							$this->writeProductUnitLabel( $request, $writer );
						}

						$writer->write("\n");
					}
				} else {
					// オフセットが0以上の場合追記モードでオープン
					$writer->open( $request, $tmpUri, 'a+', DIR_NAME_TMP);
				}
				if( !$request->isError() ) {
					foreach( $orderObjectArray as $orderObject ) {
						$csvLine	= $orderObject->getCsvString($csvColumnOrder);
						if( strlen(trim($csvLine)) > 0 ) {
							$csvLine	= mb_convert_encoding( $csvLine, 'SJIS-win', 'UTF-8' );
							$writer->write( $csvLine );
						}
					}
					$writer->close( $request );
				}
			}
		}


		// CSV書き込み処理後にエラーを確認
		if( $request->isError() ) {
			// エラーが発生したら処理を中断してセッション等を削除
			$request->removeSession($sessionHashName);
			$request->removeSession($sessionOffsetName);
		} else {
			// エラーがないならオフセットを進める
			$offset	+= $writeAtOnce;
			if( $offset >= $totalCount ) {
				// 総数より進んだら処理完了してダウンロード
				$filePath	= system_DataFileWriter::getRealAbsolutePath( $request, $tmpUri, DIR_NAME_TMP );
				$request->removeSession($sessionHashName);
				$request->removeSession($sessionOffsetName);
				$download_file_name = 'orders_' . date('YmdHi') . '.csv';					
				$request->setResponseHeader( 'Content-Type', 'application/comma-separated-values; charset="Shift_JIS"' );
				$request->setResponseHeader( 'Content-Disposition', 'attachment; filename="' . $download_file_name . '"' );
				$request->setResponseHeader( 'Cache-Control', 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0' );
				$request->setResponseHeader( 'Pragma', '' );
				$request->setResponseHeader( 'Expires', '0' );
				$request->setResponseFile( $filePath );
			} else {
				// 総数より少ないならオフセットを更新して作成処理を続行 
				$request->setSession($sessionOffsetName,$offset);
			}
		}
		$request->setAttribute('shopping.order.download.writeAtOnce', $writeAtOnce );
		$request->setAttribute('shopping.order.download.offset', $offset );
		$request->setAttribute('shopping.order.download.culumnSelectedArray', $columnSelectedArray );
		$request->setAttribute('shopping.order.download.totalCount', $totalCount );

	}
	/**
	 * モジュールの後処理を行います。
	 * このメソッドをオーバーライドすることにより、モジュールの後処理として実行されます。
	 * @param $request 
	 */
	function post_process( & $request ) {
	}
	/**
	 * 購入商品情報の項目名の取得
	 */
	 function writeProductUnitLabel( & $request, & $writer ) {
		// 商品情報が指定されていた場合、購入商品数分繰り返す
		$dbo		= $request->getAttribute( 'dbo' );
		$queryHash	= $request->getSession(SHOPPING_SESSION_NAME_ORDER_SEARCH_LAST_QUERY, SPIDER_SESSION_SCOPE_GLOBAL);
		
		$totalItemCount = 0;
		$sql = $queryHash['countQuery'];
		$whereCond	= substr($sql,strpos($sql,'WHERE'));
		
		$sql = '';
		$sql	= 'SELECT COUNT('.TABLE_NAME_SHOPPING_ORDER.'.order_number) as countItem '
			.' FROM '.TABLE_NAME_SHOPPING_ORDER
			.' LEFT OUTER JOIN ' . TABLE_NAME_SHOPPING_ORDER_ITEM
			.' ON ' . TABLE_NAME_SHOPPING_ORDER_ITEM . '.order_id='.TABLE_NAME_SHOPPING_ORDER.'.order_id '
			.$whereCond
			.' GROUP BY '.TABLE_NAME_SHOPPING_ORDER.'.order_number'
			.' ORDER BY countItem DESC'
		;
		$result	= $dbo->queryAll( $sql, 'hash' );
		if( false === $result ) {
		} else {
			if ( count($result)>0 ) {
				$totalItemCount = $result[0]['countItem'];
			}
		}
		for ( $itemNumber = 1; $itemNumber<=$totalItemCount; $itemNumber++ ) {
			foreach ( $GLOBALS['SHOPPING_ORDER_UNIT_CSV_DEFINITION'] as $itemKey=>$itemName ) {
				$columnViewName = '"'.$GLOBALS['SHOPPING_LABEL_ORDER'].''.$GLOBALS['SHOPPING_LABEL_PRODUCT'].''.$itemNumber.':'.$itemName.'"';
				$writer->write(','.mb_convert_encoding($columnViewName, 'SJIS-win', 'UTF-8'));
			}
		}
	 }
}
?>