<?php

// 頁面專用WebAPI, 不管任何的頁面, class名稱固定為 [WebAPIForMenuPage], 不可變更
class WebAPIForMenuPage extends base_class
{
    //查詢資料
    public function Selectload_page_data()
    {


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

        //時間條件設定
        $a_where_arr[] =  "_adk.Time_Stamp BETWEEN :start_at AND :end_at";
        $a_where_arr_val["start_at"] =  date("Y-m-01");
        $a_where_arr_val["end_at"] = date("Y-m-d");



        //sql條件陣列轉換
        if (!empty($a_where_arr)) {
            $s_where_arr = " WHERE " . implode(" AND ", $a_where_arr);
        }

        $sql = sprintf(
            "SELECT
                _adk.ACM,
                _adk.Time_Stamp,
                _adk.Today_KWH
            FROM
                [%s].[dbo].[ACM_Daily_KWH] AS _adk
            %s",
            $this->database_trend,
            $s_where_arr
        );
        $sth = $this->pdo_sql->prepare($sql);
        $sth->execute($a_where_arr_val);
        $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
        $res = [];
        foreach ($rows as $k => $v) {
            if (empty($res[$v["ACM"]])) {
                $res[$v["ACM"]] = [
                    "tag" => $v["ACM"],
                    "month" => 0,
                    "day" => 0,
                ];
            }
            //本月加總
            $res[$v["ACM"]]["month"] = (float) bcadd($res[$v["ACM"]]["month"], $v["Today_KWH"], 2);
            //本日數值
            if ($v["Time_Stamp"] == date("Y-m-d")) {
                $res[$v["ACM"]]["day"] = bcadd($res[$v["ACM"]]["day"], $v["Today_KWH"], 2);
            }
        }
        $res = array_values($res);
        return $res;
    }
}
