<?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)
        );
		
		$template["full_name"] = $this -> getInquirerName();
		
		$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 -> sendNotificationToSlack(0, $details);
		}else
		    $this -> sendNotificationToSlack(1, $template["body"]);
		
		// ユーザ側へ送信
		$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 = json_encode([
	        "ticket" => [
	            "subject" => $template["title"],
	            "priority" => "urgent",
	            "recipient" => $ticketingConf -> recipient,
	            "comment" => [
	                "body" => $template["body"]
	            ],
	            "requester" => [
	                "locale_id" => $this -> getZendeskLocaleCode(),
	                "name" => $template["full_name"],
	                "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 => $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"]}\n</subject>\n".
	               "<content>\n{$template["body"]}\n</content>\n".
	               "<params>\n{$params}\n</params>",
	        "response_str" => $output
	    ];
	    
	    return $httpcode === 201; 
	}
	
	/*-------------------------------------------------------------------------
	 * @function_name: 通知をSlackへ送信する機能
	 * @parameter	: details
	 * @return		: なし
	 -------------------------------------------------------------------------*/
	private function sendNotificationToSlack($notificationType, $details){
	    $slackChannels = $this -> getSettingConfiguration("slack_notif_channel");
	    
	    $handle = curl_init();
	    
	    $message = ["text" => $details];
	    
	    $channel = $notificationType === 1 ? 
	       $slackChannels -> successfully_submitted_tickets : 
	       $slackChannels -> user_details_channel;
	    
	    curl_setopt_array($handle, [
	        CURLOPT_URL => $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;
	}
}
?>