<?php
require_once(SITE_LOGICS . 'support/model.php');

class LogicSupport extends SupportModelClass {

	/*-------------------------------------------------------------------------
	* @ メンバ変数
	-------------------------------------------------------------------------*/
	private $htmlStr = NO_STRING;	// 表示用HTML文字列

	/*-------------------------------------------------------------------------
	* @function_name: ロジックのコンストラクタ
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function __construct() {
		parent::__construct();
	}

	/*-------------------------------------------------------------------------
	* @function_name: ロジック（各クラス共通）
	* @parameter	: なし
	* @return		: TRUE:ロジック成功、FALSE:ロジック失敗
	-------------------------------------------------------------------------*/
	function logic() {
		try {

			// 初期データ処理
			$this -> init();

			// ロジック実行
			$this -> biz();

		} catch (Exception $e) {
			throw $e;
		}
	}

	/*-------------------------------------------------------------------------
	* @function_name: ロジックの実行
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function biz() {
		if($this -> getType()		== NO_STRING
			|| $this -> getType()	== TYPE_INPUT) {		// 入力画面
			$this -> select();
		} else if($this -> getType() == TYPE_COMPLETE) {	// 完了画面
			$this -> send();
		}
	}


	/*-------------------------------------------------------------------------
	* @function_name: データの取得
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function select() {
		// 変数宣言部
		$rs		= null;

		// データの取得
		$rs = $this -> getAccountCommon($this -> getUserData(PARAM_USER_ACCOUNT));

		$this -> setUserData($this -> getRowData($rs));

		$this -> restore();
	}

	/*-------------------------------------------------------------------------
	* @function_name: データの登録
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function send() {

		// 変数宣言部
		$mail	= $this -> getEmail();
		$rs		= null;

		// データ用生成用のデータを取得する
		$rs = $this -> getAccountByEmailCommon($mail);
				
		$template = $this -> getMailTemplate(
		    "send_mail_for_admin.xml",
		    $this -> getSendParamsForAdmin($rs)
        );
		
		if($this -> isLoopData($rs)){
		    $rowData = $this -> getRowData($rs);
		    
		    $firstName    = $this -> getColumnData($rowData, PARAM_FIRST_NAME);
		    $lastName     = $this -> getColumnData($rowData, PARAM_LAST_NAME);
		    
		    $template["full_name"] = "{$firstName} {$lastName}";
		}
		
		$errorDetails = [];
		if(!$this -> createZendeskTicket($template, $errorDetails)){
		    $details = "Unexpected response code found on Zendesk API [Inquiry Form Issue/Warning].\n\n".
		              "Response Code: {$errorDetails["response_code"]}\n".
		              "Response String: {$errorDetails["response_str"]}\n\n".
		              "Ticket Body:\n\n {$errorDetails["ticket_body"]}"; 
		    
		    $this -> notifyErrorToSlack($details);
		}
		
		// ユーザ側へ送信
		$this -> sendMailByTmp('send_mail_for_user.xml'
		    , $this -> getSendParamsForUser($rs)
		    , $mail
		    , VAR_CS_MAIL_ADDRESS);
	}

	/*-------------------------------------------------------------------------
	 * @function_name: Zendeskチケットの新規作成
	 * @parameter	: template, details
	 * @return		: boolean
	 -------------------------------------------------------------------------*/
	private function createZendeskTicket(Array $template, &$details = null){
	    $ticketingConf = $this -> getSettingConfiguration("zendesk_ticketing_api_conf");
	    
	    $hashed = base64_encode("{$ticketingConf -> username}:{$ticketingConf -> password}");
	    
	    $handle = curl_init();
	    
	    if($ticketingConf -> staging)
	        $template["body"] = "[STAGING TICKET]\n{$template["body"]}";
	    
	    $params = [
	        "ticket" => [
	            "subject" => $template["title"],
	            "priority" => "urgent",
	            "recipient" => $ticketingConf -> recipient,
	            "comment" => [
	                "body" => $template["body"]
	            ],
	            "requester" => [
	                "locale_id" => $this -> getZendeskLocaleCode(),
	                "name" => isset($template["full_name"]) ? $template["full_name"] : NO_STRING,
	                "email" => $this -> getEmail()
	            ]
	        ]
	    ];
	    
	    curl_setopt_array($handle, [
	        CURLOPT_URL => $ticketingConf -> endpoint_url,
	        CURLOPT_RETURNTRANSFER => true,
	        CURLOPT_FOLLOWLOCATION => true,
	        CURLOPT_ENCODING => "utf8",
	        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	        CURLOPT_CUSTOMREQUEST => $ticketingConf -> request_method,
	        CURLOPT_POSTFIELDS => json_encode($params),
	        CURLOPT_HTTPHEADER => [
	            "Content-type: application/json",
	            "Authorization: Basic {$hashed}"
            ]
        ]);
	    
        $output = curl_exec($handle);

	    $httpcode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
	    
	    curl_close($handle);
	    
	    $details = [
	        "response_code" => $httpcode,
	        "ticket_body" => 
	               "<subject>{$template["title"]}</subject>\n".
	               "<content>\n{$template["body"]}</content>",
	        "response_str" => $output
	    ];
	    
	    return $httpcode === 201; 
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name: Slackへのエラー通知
	 * @parameter	: details
	 * @return		: なし
	 -------------------------------------------------------------------------*/
	private function notifyErrorToSlack($details){
	    $slackChannels = $this -> getSettingConfiguration("slack_notif_channel");
	    
	    $handle = curl_init();
	    
	    $message = ["text" => $details];
	    
	    curl_setopt_array($handle, [
	        CURLOPT_URL => $slackChannels -> user_details_channel,
	        CURLOPT_RETURNTRANSFER => true,
	        CURLOPT_FOLLOWLOCATION => true,
	        CURLOPT_ENCODING => "utf8",
	        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	        CURLOPT_POSTFIELDS => json_encode($message),
	        CURLOPT_CUSTOMREQUEST => "POST",
	        CURLOPT_HTTPHEADER => [
	            "Content-type: application/json",
	        ]
	    ]);
	    
	    curl_exec($handle);
	    
	    if($err = curl_error($handle))
	        echo $err;
	        
	    curl_close($handle);
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: ページ出力文字列取得関数
	* @parameter	: なし
	* @return		: HTML文字列
	-------------------------------------------------------------------------*/
	function getDisplay() {
		return $this -> htmlStr;
	}
}
?>