<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
	/**
	 * Leo
	 * 取得收款明細
	 * @param start_date, end_date, store
	 * @return list[]
	 */
	public function SelectReceivedLedgerList($params)
	{


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

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

		// 門市判斷條件
		if ($params['store'] != 0) {
			$a_where_arr[] = "_srl.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 
				_srl.received_ledger_id,
				_srl.store_id,
				_srl.received_at AS received_date,
				_srl.received_start_at AS received_start_time,
				_srl.received_end_at AS received_end_time,
				_srl.logistics_amount_total,
				_srl.commodity_amount_total,
				_s.store_name,
				_c.cashier_id,
				_c.cashier_name
			FROM 
				[%s].[dbo].[store_received_ledger] AS _srl	
				LEFT JOIN [%s].[dbo].[store] AS _s ON _s.store_id = _srl.store_id	
				LEFT JOIN [%s].[dbo].[cashier] AS _c ON _c.store_id = _srl.store_id	
			%s
			",
			$this->database_trend,
			$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["total_amount"] = bcadd($v["logistics_amount_total"], $v["commodity_amount_total"], 0);
			$v["received_start_time"] = substr($v["received_start_time"], 0, 8);
			$v["received_end_time"] = substr($v["received_end_time"], 0, 8);

			$a_store_data[] = $v;
		}
		return $a_store_data;
	}
}
