<?php
// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{

	//撈取碳排係數最新一筆資料
	public function SelectLoadCarbon($params)
	{

		$sql = sprintf(
			"SELECT TOP 1
					carbon_conversion_factor
				FROM
					[%s].[dbo].[CarbonConversion]
				ORDER BY
					sno desc",
			$this->database_trend
		);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute();
		$row = $sth->fetch(PDO::FETCH_ASSOC);
		if (isset($row["carbon_conversion_factor"])) {
			$row["carbon_conversion_factor"] = number_format($row["carbon_conversion_factor"], 3, ".", "");
		}
		return $row;
	}
	//碳排係數更新(以新增一筆資料的方式)
	public function Changeadd_data($params)
	{
		//碳排係數 數值
		$f_carbon_conversion = (float) $params["val"];


		$sql = sprintf(
			"INSERT INTO [%s].[dbo].[CarbonConversion] ( [carbon_conversion_factor], [created_by] )
			VALUES ( :carbon_conversion_factor, :created_by );",
			$this->database_trend
		);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([
			'carbon_conversion_factor' => $f_carbon_conversion,
			'created_by' => $this->user_id,
		]);
		if ($sth->rowCount() == 0) {
			throw new Exception("資料庫更新失敗", 1);
		}

		return "ok";
	}

	public function SelectLoadDevice($params)
	{

		$sql = sprintf(
			"SELECT [DL].[id]
				,[device_name]
				,[device_key]
				,CONVERT(varchar(5),[schedule_start_time],114) AS [start_time]
    			,CONVERT(varchar(5),[schedule_end_time],114) AS [end_time]
      			,[schedule_mode] AS [mode]
				,[DIL].[count]
			FROM [%s].[dbo].[device_list] AS [DL]
			LEFT JOIN (
				SELECT COUNT(*) AS [count],device_id
			 	FROM [%s].[dbo].[device_item_list]
			 	GROUP BY [device_id]
			) AS [DIL]
			ON [DIL].[device_id] = [DL].id
			WHERE [DIL].[count] IS NOT NULL AND [device_key] IS NOT NULL
			ORDER BY [device_key]
			",
			$this->database_alarm,
			$this->database_alarm
		);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([]);
		$res = $sth->fetchAll(PDO::FETCH_ASSOC);
		// foreach ($rows as $k => $v) {

		// 	$v["unit_price"] = (float) number_format($v["unit_price"], 3, ".", "");
		// 	$v["amount"] = (float) number_format($v["amount"], 3, ".", "");
		// 	$res[] = $v;
		// }

		return $res;
	}

	public function ChangeSaveDevice($params)
	{
		//	新增users資料表內容
		$sql = sprintf("UPDATE [%s].[dbo].[device_list] SET
						 [schedule_start_time] = :schedule_start_time
						,[schedule_end_time] = :schedule_end_time
						,[schedule_mode] = :schedule_mode
						,[updated_at] = getdate()
						,[updated_by] = :updated_by
						WHERE [id] = :id
				", $this->database_alarm);
		$sth = $this->pdo_sql->prepare($sql);
		$sth->execute([
			'schedule_start_time' => $params['start_time'],
			'schedule_end_time' => $params['end_time'],
			'schedule_mode' => $params['mode'],
			'updated_by' => $this->user_id,
			'id' => $params['id'],
		]);

	}
}
