<?php

include_once "class.abs_class_trait.php";
include_once "class.abs_class_api.php";

abstract class base_class
{
	use base_class_trait;
	use base_class_api;
	// 資料庫連線
	protected $pdo_sql;
	// 資料庫相關參數
	protected $datasource;
	protected $database_trend;
	protected $database_alarm;
	protected $uid;
	protected $pwd;

	public $user_id;
	//設定門市顯示控制項
	public $store_ctrl;

	public function SetDataBase($ds, $db, $db2, $id, $pw, $is_conn)
	{
		$this->datasource     = $ds;
		$this->database_trend = $db;
		$this->database_alarm = $db2;
		$this->uid = $id;
		$this->pwd = $pw;
		if ($is_conn) {
			$this->SetPdoConn(new PDO(sprintf("sqlsrv:Server=%s; Database=%s;", $this->datasource, $this->database_trend), $this->uid, $this->pwd));
		}
	}

	public function SetPdoConn($conn)
	{
		$this->pdo_sql = $conn;
		// PDO 設定為例外模式(exception mode)，或是在捕捉例外的部分沒有處理到此類例外
		$this->pdo_sql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}

	public function InputDecode($input)
	{
		$input_decode = json_decode($input, true);
		return is_string($input) && is_array($input_decode) && (json_last_error() == JSON_ERROR_NONE) ? $input_decode : $input;
	}

	public function XSSFilter($val)
	{
		return htmlspecialchars(strip_tags($val), ENT_QUOTES);
	}

	private function _SetErrorLog($msg, $sqlstr = '', $params = array())
	{
		file_put_contents("./Api_log/Error_" . date("Ymd") . ".txt", print_r(array(
			"time_stamp" => date("Y-m-d H:i:s"),
			"message" => $msg,
			"sqlstr" => $sqlstr,
			"params" => $params
		), true) . "\r\n", FILE_APPEND);
	}
	//Leo POST
	public static function SockPost($URL, $Query, $Header = [], &$curlerror = [])
	{
		$ch = curl_init();
		$a_http_header = [];
		if (!empty($Header)) {
			$a_http_header = $a_http_header + $Header;
		}
		curl_setopt($ch, CURLOPT_URL, $URL);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $Header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $Query);
		//連線逾時設定 單位秒
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
		//回傳逾時設定 (此為總時間 會包含連線時間 因此不可低於連線逾時設定時間) 單位秒
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);
		$SSL = (substr($URL, 0, 8) == "https://" ? true : false);
		if ($SSL) {
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		}
		$strReturn = curl_exec($ch);
		$curl_errno  = curl_errno($ch);
		$curl_error = curl_error($ch);
		$curlerror = [
			'curl_errno' => $curl_errno,
			'curl_error' => $curl_error,
		];

		curl_close($ch);

		return $strReturn;
	}
	/**
	 * Leo
	 * line_notify 通知
	 */
	public static function line_notify($notify_data, $custom_token = "")
	{
		//token定義

		// 正式 3.0蝦皮新群組
		// $token = "wvP73wXFGYH6Wv7rLQzbxymiEISID6WIi83F34OThQM";

		// 2.0蝦皮舊群組
		// $token = "cfJG7yetD7j3uGgQztA3QeSZNDslKoH81VdSF0LBgYE";

		// 測試
		$token = "R0GZ9CZdXnf3fPQZWSHKCwtkWpbpbdXXvT4FDoeWGXe";

		//個人
		// $token = "VLUSg6rCbuPuh2bkRcH18nwnCekPiZPeDMyJRJk5VdI";

		//判斷是否有指定line通知位置，有的話則指向指定位置
		if ($custom_token != "") {
			$token = $custom_token;
		}

		$url = "https://notify-api.line.me/api/notify";
		//傳遞資料格式化
		$s_data = "\n";
		foreach ($notify_data as $k => $v) {
			$s_data .= $k . ":" . $v . "\n";
		}
		//補上版本戳記
		$s_data .= "系統版本:SPX3.0\n";

		$Header = [
			"Authorization:Bearer $token"
		];
		$data = [
			"message" => $s_data,
		];
		$error = [];
		self::SockPost($url, $data, $Header, $error);
	}
	/**
	 * Leo
	 * Log紀錄 
	 */
	public static function WriteLog(
		string $_sFile, /*資料夾路徑*/
		string $_sFileName, /*檔案名稱*/
		array $_aLogarr, /*要紀錄的內容(會以json轉寫進去)*/
		string $_sLogType = 'Debug' /*log類型(預設Debug)*/
	) {
		/*
        $_sFile     資料夾名稱
        $_sFileName 檔案名稱
        $_aLogarr   要寫入的內容陣列，陣列內為一鍵值對應一條文字內容
        $_sLogType  Log型態 預設為Debug
        */

		if ($_sFile == '') return false;
		if ($_sFileName == '') return false;
		if ($_sLogType == "") return false;
		$_sFile = trim($_sFile);
		$_sFileName = trim($_sFileName);
		$_sLogType = trim($_sLogType);


		//類型允許清單
		$_aType_allow_list = array(
			'Debug',                //開發監測用
			'Info',                 //單純想記錄用
			'Notice',               //發送外部通訊軟體警示
			'Warn',                 //錯誤紀錄
			'Point',                //點數異動紀錄
			//'IP'                    //IP紀錄
		);
		//在清單內才紀錄
		if (in_array($_sLogType, $_aType_allow_list)) {
			$sPath =  dirname(dirname(__FILE__)) . "/Log/$_sFile";
			if (!is_dir($sPath)) {
				mkdir($sPath, 0700, true);
			}
			$_sFileTime = Date('Ymd');
			$sPath =  "$sPath/$_sFileName" . "_" . $_sFileTime . ".txt";

			$_aLogarr["Log_DateTime"] = self::GetNowMicroDate();
			$sStr = "";
			$sStr = json_encode($_aLogarr, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . ",";
			// if ($_sLogType == "IP") {
			// } else {
			// 	self::Log_arraytostr($_aLogarr, $sStr);
			// }
			error_log($sStr, 3, $sPath);
		} else {
			return false;
		}
	}
	/**
	 * Leo
	 * 取得時間 
	 * 含毫秒 
	 */
	public static function GetNowMicroDate(): string
	{
		# 當前毫秒時間
		$sM = (string) microtime(1);
		$aM = explode('.', $sM);
		return (string) Date('Y-m-d H:i:s.', $sM) . $aM[1];
	}
	/** 
	 * Leo
	 * Log紀錄陣列轉字串 
	 **/
	static function Log_arraytostr(&$arr, &$str)
	{
		if (is_array($arr)) {
			foreach ($arr as $key => $value) {
				if (!is_array($value)) {
					if ($value === "") {
						$str .= $key . PHP_EOL;
					} else {
						$str .= $key . " => " . $value . PHP_EOL;
					}
				} else {
					self::Log_arraytostr($value, $str);
				}
			}
		}
	}
}
