<?php
error_reporting(E_ALL & ~(E_NOTICE | E_WARNING)); // 關閉警示及錯誤訊息
session_write_close();
/**
 * Step 1: Require the Slim Framework using Composer's autoloader
 *
 * If you are not using Composer, you need to load Slim Framework with your own
 * PSR-4 autoloader.
 */
require "./vendor/autoload.php";
require_once "../action/Parameters.php";

/**
 * Step 2: Instantiate a Slim application
 *
 * This example instantiates a Slim application using
 * its default settings. However, you will usually configure
 * your Slim application now by passing an associative array
 * of setting names and values into the application constructor.
 */
$config = array(
	"settings" => array(
		"database" => array(
			"driver" => "sqlsrv",
			"host" => $DataSource,
			"port" => 1433,
			"db_trend" => $DataBase_Trend,
			"db_alarm" => $DataBase_Alarm,
			"username" => $UserID, 
			"password" => $Password
		)
	),
	"debug" => true
);

$container = new \Slim\Container($config);
$app = new \Slim\App($container);

$container = $app->getContainer();
$container['pdo_sql'] = function ($_container) {
	$db_cfg = $_container->settings->get("database");
    switch ($db_cfg["driver"]) {
		case "pgsql":
			$dsn = sprintf("pgsql:host=%s;port=%d;dbname=%s;", $db_cfg["host"], ((int)$db_cfg["port"] | 5432), $db_cfg["db_trend"]);
			break;
		case "mysql":
			$dsn = sprintf("mysql:host=%s;dbname=%s;port=%d", $db_cfg["host"], $db_cfg["db_trend"], ((int)$db_cfg["port"] | 3306));
			break;
		case "sqlsrv":
			// $dsn = sprintf("sqlsrv:Server=%s,%d; Database=%s;", $db_cfg["host"], ((int)$db_cfg["port"] | 1433), $db_cfg["db_trend"]);
			$dsn = sprintf("sqlsrv:Server=%s; Database=%s;", $db_cfg["host"], $db_cfg["db_trend"]);
			break;
		default:
			throw new Exception($db_cfg["driver"]." Not Support.");
	}
	return new PDO ($dsn, $db_cfg["username"], $db_cfg["password"]);
};

/**
 * Step 3: Define the Slim application routes
 *
 * Here we define several Slim application routes that respond
 * to appropriate HTTP request methods. In this example, the second
 * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete`
 * is an anonymous function.
 */
 
// for cors and options
$app->add(function ($req, $res, $next) {
	$response = $next($req, $res);
	$response = $response->withHeader('Access-Control-Allow-Origin', '*');
	$response = $response->withHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS'); // 'GET, POST, PUT, DELETE, PATCH, OPTIONS'
	if ($req->getMethod() === 'OPTIONS') {
		$response = $response->withHeader('Access-Control-Allow-Headers', 'Content-Type');
		$response->withStatus(200);
	}
    return $response;
});

// For ProductionData API
$app->group("/ProductionData", function () {
	// @Router /Users/{uid}/accessTokens
	$this->get("", function ($request, $response, $args) {
		$input = $request->getParams();
		if (!isset($input["deviceId"]) || !(int)$input["deviceId"]) {
			$response->withStatus(400)->write("deviceId error");
			return $response;
		}
		// print_r($this->settings->get("database")["db_trend"]);	
		$dateArr = array(
			"startTime" => date("Y-m-d H:i:s", strtotime("now -10 second")),
			"endTime"=> date("Y-m-d H:i:s")
		);
		$output = array();
		try {
			/* 
			label: "全線速度", value: "line_speed"
			label: "A軸計米", value: "cont_a"
			label: "B軸計米", value: "cont_b"
			label: "預浸黏度", value: "viscosity_left"
			label: "含浸黏度", value: "viscosity_right"
			label: "裁張計數器", value: "crop"
			label: "左間隙滾筒", value: "PV_1_left"
			label: "右間隙滾筒", value: "PV_1_right"
			*/
			if (isset($input["startTime"])) {
				if (!isset($input["endTime"]) || !strtotime($input["startTime"]) || !strtotime($input["startTime"])) {
					$response->withStatus(400)->write("datetime error");
					return $response;
				}
				if (strtotime($input["endTime"]) < strtotime($input["startTime"])) {
					$response->withStatus(400)->write("endTime can not be less than startTime error");
					return $response;
				}
				$dateArr = array(
					"startTime" => date("Y-m-d H:i:s", strtotime($input["startTime"])),
					"endTime"=> date("Y-m-d H:i:s", strtotime($input["endTime"]))
				);
			}
			$target = sprintf("LINE%02d", $input["deviceId"]);
			$sql = sprintf("SELECT 
								CONVERT(VARCHAR, Time_Stamp, 120) AS captureTime, 
								FORMAT(ISNULL(line_speed, 0), '0.00') AS lineSpeed, 
								FORMAT(ISNULL(cont_a, 0), '0.00') AS contA, 
								FORMAT(ISNULL(cont_b, 0), '0.00') AS contB, 
								FORMAT(ISNULL(viscosity_left, 0), '0.00') AS viscosityLeft, 
								FORMAT(ISNULL(viscosity_right, 0), '0.00') AS viscosityRight, 
								FORMAT(ISNULL(crop, 0), '0.00') AS crop, 
								FORMAT(ISNULL(PV_1_left, 0), '0.00') AS PVLeft,
								FORMAT(ISNULL(PV_1_right, 0), '0.00') AS PVRight
							FROM %s.dbo.%s
							WHERE Time_Stamp >= :startTime AND Time_Stamp <= :endTime", $this->settings->get("database")["db_trend"], $target);
			// print_r($sql);
			// print_r($dateArr);
			$sth = $this->pdo_sql->prepare($sql);
			$sth->execute($dateArr);
			$output = $sth->fetchAll(PDO::FETCH_ASSOC);
		} catch (Exception $e) {
			$response->withStatus(500)->write($e->getMessage());
			return $response;
		}
		// print_r($output);
		$response->withJson($output);
		return $response;
	});
});
/**
 * Step 4: Run the Slim application
 *
 * This method should be called last. This executes the Slim application
 * and returns the HTTP response to the HTTP client.
 */
$app->run();
?>