<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
	/**
	 * Leo
	 * 取得門市營業資料
	 * @param start_date, end_date, store
	 * @return list[]
	 */
	public function SelectBusinessList($params)
	{


		$a_where_arr = []; //sql條件陣列 
		$a_where_arr_val = [];
		$s_where_arr = ""; //sql條件字串，用$a_where_arr條件陣列轉換而來

		// 時間條件
		$a_where_arr[] = "_sts.transaction_end_at BETWEEN :startTime AND :endTime";
		$a_where_arr_val["startTime"] = date('Y-m-d 00:00:00', strtotime($params['start_date']));
		$a_where_arr_val["endTime"] = date('Y-m-d 23:59:59', strtotime($params['end_date']));

		// 門市判斷條件
		if ($params['store'] != 0) {
			$a_where_arr[] = "_sts.store_id = :store";
			$a_where_arr_val["store"] = $params['store'];
		}

		//門市查詢控制項 store_ctrl 0:只顯示營運中門市 1:顯示全門市
		if ($this->store_ctrl == 0) {
			$a_where_arr[] = " _s.store_state = 1 ";
		}

		//sql條件陣列轉換
		if (!empty($a_where_arr)) {
			$s_where_arr = " WHERE " . implode(" AND ", $a_where_arr);
		}
		//拼接sql字串
		$sql = sprintf(
			"WITH transaction_statement_count AS (SELECT 
				_sts.store_id
				,CAST(_sts.transaction_end_at AS DATE) AS transaction_date
				,SUM(_sts.order_amount) AS total_amount
				,SUM(_sts.cash_1000_in) AS cash_1000
				,SUM(_sts.cash_500_in - _sts.cash_500_out) AS cash_500
				,SUM(_sts.cash_100_in - _sts.cash_100_out) AS cash_100
				,SUM(_sts.cash_50_in - _sts.cash_50_out) AS cash_50
				,SUM(_sts.cash_10_in - _sts.cash_10_out) AS cash_10
				,SUM(_sts.cash_5_in - _sts.cash_5_out) AS cash_5
				,SUM(_sts.cash_1_in - _sts.cash_1_out) AS cash_1
			FROM 
				[%s].[dbo].[store_transaction_statement] AS _sts
				LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _sts.store_id
			%s
			GROUP BY
				_sts.store_id
				,CAST(_sts.transaction_end_at AS DATE) 
			)SELECT
				_tsc.*,
				_s.store_name,
				_c.cashier_id
			FROM
				transaction_statement_count AS _tsc
				LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _tsc.store_id
				LEFT JOIN [%s].[dbo].[cashier] AS _c ON _c.store_id = _tsc.store_id
			",
			$this->database_trend,
			$this->database_trend,
			$s_where_arr,
			$this->database_trend,
			$this->database_trend
		);
		//準備執行sql
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute($a_where_arr_val);
		$row = $sth->fetchAll(PDO::FETCH_ASSOC);
		//整理回傳資料
		$a_store_data = [];
		foreach ($row as $k => &$v) {
			$a_store_data[] = $v;
		}
		return $a_store_data;
	}
}
