<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
	/**
	 * Leo
	 * 取得物流交易資料(info)
	 * @param start_date, end_date, store
	 * @return list[]
	 */
	public function SelectTransactionList($params)
	{
		$n_date_type = (int) $params['date_type']; //查詢時間區間類型 1:依據交易完成時間 2:依據收款時間


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

		// 時間條件
		$a_where_arr[] = sprintf(
			"_sts.%s BETWEEN :startTime AND :endTime",
			$n_date_type == 2 ? "received_at" : "transaction_end_at"
		);
		$a_where_arr_val["startTime"] = date('Y-m-d H:i:00', strtotime($params['start_date']));
		$a_where_arr_val["endTime"] = date('Y-m-d H:i: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(
			"SELECT 
				_sts.store_id,
				_sts.trading_id,
				_sts.received_ledger_id,
				_sts.shopee_order_id,
				_sts.shopee_shipment_id,
				_sts.payment_type,
				_sts.order_amount,
				_sts.trading_status,
				_sts.transaction_start_at AS transaction_start_time,
				_sts.transaction_end_at AS transaction_end_time,
				_sts.received_at AS received_datetime,
				_sts.order_amount,
				_sts.cash_1000_in,
				_sts.cash_500_in,
				_sts.cash_100_in,
				_sts.cash_50_in,
				_sts.cash_10_in,
				_sts.cash_5_in,
				_sts.cash_1_in,
				_sts.cash_500_out,
				_sts.cash_100_out,
				_sts.cash_50_out,
				_sts.cash_10_out,
				_sts.cash_5_out,
				_sts.cash_1_out,
				_sts.sub_1000_in,
				_sts.sub_500_in,
				_sts.sub_100_in,
				_sts.sub_500_out,
				_sts.sub_100_out,
				_sts.cashier_id,
				_sts.store_id,
				_s.store_name
			FROM 
				[%s].[dbo].[store_transaction_statement] AS _sts
				LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _sts.store_id				
			%s
			",
			$this->database_trend,
			$this->database_trend,
			$s_where_arr
		);
		//準備執行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) {
			$v["cash_1000"] = $v["sub_1000_in"] + $v["cash_1000_in"];
			$v["cash_500"] = $v["sub_500_in"] + $v["cash_500_in"] - $v["cash_500_out"] - $v["sub_500_out"];
			$v["cash_100"] = $v["sub_100_in"] + $v["cash_100_in"] - $v["cash_100_out"] - $v["sub_100_out"];
			$v["cash_50"] = $v["cash_50_in"] - $v["cash_50_out"];
			$v["cash_10"] = $v["cash_10_in"] - $v["cash_10_out"];
			$v["cash_5"] = $v["cash_5_in"] - $v["cash_5_out"];
			$v["cash_1"] = $v["cash_1_in"] - $v["cash_1_out"];
			$a_store_data[] = $v;
		}
		return $a_store_data;
	}
}
