<?php
class AdvertisementModelClass extends ModelClassEx {
	/*-------------------------------------------------------------------------
	* @ メンバ変数
	-------------------------------------------------------------------------*/

	private $lang			= NO_STRING;
	private $rs 			= null;
	private $mail 			= NO_STRING;
	private $IP 			= NO_STRING;
	private $adsID 			= NO_STRING;
	private $adID 			= NO_STRING;
	private $adDetails 		= NO_STRING;
	private $language 		= NO_STRING;
	private $slanguage 		= NO_STRING;
	private $from 			= NO_STRING;
	private $to 			= NO_STRING;
	private $img1Flg		= NO_STRING;
	private $rs2			= NO_STRING;	
	private $location		= NO_STRING;	
	private $slocation		= NO_STRING;	
	private $link 			= NO_STRING;	
	private $fileName 		= NO_STRING;	
	private $adName 		= NO_STRING;	
	private $sequence 		= NO_STRING;	
	private $saveName       = NO_STRING;

	/*-------------------------------------------------------------------------
	* @function_name: コントロールパネルシステムindexモデルクラスコンストラクタ
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	function __construct() {
		// スーパークラスコンストラクタ呼び出し
		parent::__construct();
	}


	/*-------------------------------------------------------------------------
	* @function_name: 初期設定関数
	* @parameter	: なし
	* @return		: 成功:success、失敗:error
	-------------------------------------------------------------------------*/
	public function init() {

		try {

			// パラメータの設定
			$this -> setParameter();

			// チェック
			return $this -> validate();

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

	/*-------------------------------------------------------------------------
	* @function_name: パラメータの設定
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	private function setParameter() {
		$this -> lang			= $this -> getLangage();
		$this -> mail 			= $this -> getDataPost('mail', true);
		$this -> IP 			= $this -> getDataPost('ip', true);
		$this -> adsID 			= $this -> getDataPost('adsId', true);
		$this -> adID 			= $this -> getDataPost('adID', true);
		$this -> language 		= $this -> getDataPost('language', true);
		$this -> slanguage 		= $this -> getDataPost('slanguage', true);
		$this -> from 			= $this -> getDataPost('from', true);
		$this -> to 			= $this -> getDataPost('to', true);
		$this -> img1Flg		= $this -> getDataPost(PARAM_IMG_1_FLG);
		$this -> location 		= $this -> getDataPost('location', true);
		$this -> slocation 		= $this -> getDataPost('slocation', true);
		$this -> link 			= $this -> getDataPost('link', true);
		$this -> adName 		= $this -> getDataPost('adName', true);
		$this -> fileName 		= $this -> getDataPost('fileName', true);
		$this -> sequence 		= $this -> getDataPost('sequence', true);
	}

	/*-------------------------------------------------------------------------
	* @function_name: パラメータの再設定
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	public function restore() {
		$this -> fileName 		= $this -> getColumnData($this -> adDetails, 'file_name');
		$this -> adName 		= $this -> getColumnData($this -> adDetails, 'ads_id');
		$this -> adID 			= $this -> getColumnData($this -> adDetails, 'id');
		$this -> link 			= $this -> getColumnData($this -> adDetails, 'redirect_link');
		$this -> location 		= $this -> getColumnData($this -> adDetails, 'ads_location');
		$this -> language 		= $this -> getColumnData($this -> adDetails, 'language');
	}

	/*-------------------------------------------------------------------------
	* @function_name: サーバ側データチェック
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function validate() {
		// ログインチェック
		if(!$this -> checkAdminUserLogin()) {
			throw new Exception(NO_STRING);
		}

		/**
		 *
		 * -- anton --
		 * 04/22/2019
		 *
		 */
		$redirect = ($this -> lang != "en" ? "" : "{$this -> lang}/");

		if(!$this -> checkAdminUserAccess('ADVT', array(''))){
			$this -> popUpSessionMessage(ERROR, 'E_ERROR_NO_PAGE_ACCESS', array());
			header('Location: /'.$redirect.'menu');
			exit();
		}

		if($this -> getType() == TYPE_IMAGE_MANAGER_DETAIL){
			if(!$this -> checkAdIDExist($this -> adID)){
				$this -> setType(TYPE_IMAGE_MANAGER);
			}
		}elseif($this -> getType() == TYPE_UPDATE) {
			if(!in_array($this -> location, ['menu', 'login'])){
				$this -> setType(TYPE_IMAGE_MANAGER_DETAIL);
			}

			if(!in_array($this -> language, ['en', 'ja', 'sc', 'tc', 'id'])){
				$this -> setType(TYPE_IMAGE_MANAGER_DETAIL);
			}
		}elseif($this -> getType() == TYPE_IMAGE_MANAGER_UPLOAD_COMPLETE) {
			if(!$this -> checkExistImage($_FILES['img1']['name'])){
				$this -> popUpSessionMessage(ERROR, 'E_EXIST_DATA', array('Filename '));
				$this -> setType(TYPE_IMAGE_MANAGER);
			}	
			
			if(!$this -> isUpload(PARAM_IMG1)) {
			    $this -> popUpSessionMessage(ERROR, 'E_ERROR_UPLOAD_ADMIN_INVALID', array());
			    $this -> setType(TYPE_IMAGE_MANAGER);
			}
		}
	}

	/*-------------------------------------------------------------------------
	* @function_name: HTML表示用のデータ取得関数
	* @parameter	: なし
	* @return		: HTML表示用データ配列
	-------------------------------------------------------------------------*/
	public function dispHTML() {
		return array();
	}

	/*-------------------------------------------------------------------------
	* @function_name: データ一覧の表示
	* @parameter	: なし
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	public function echoList() {
		// 変数宣言部
		$rtn	= NO_STRING;
		$row	= null;

		if($this -> isLoopData($this -> rs)) {
			$start		= ($this -> getTargetPage() - VAL_INT_1) * VAR_DEFAULT_PAGE_COUNT;
			$end		= $this -> getTargetPage() * VAR_DEFAULT_PAGE_COUNT;
			$listCount	= count($this -> rs);

			for($cnt = $start; $cnt < $end && $cnt < $listCount; $cnt++) {
				
				$row = $this -> getRowData($this -> rs, $cnt);

				$rtn .= '<tr>'.
						'<td>'.$this -> getColumnData($row, 'mail').'</td>' .
						'<td>'.$this -> getColumnData($row, 'ip_address').'</td>' .
						'<td>'.$this -> getColumnData($row, 'device').'</td>' .
						'<td>'.$this -> getColumnData($row, 'ads_id').'</td>' .
						'<td>'.$this -> getColumnData($row, 'ads_location').'</td>' .
						'<td>'.$this -> getColumnData($row, 'redirect_link').'</td>' .
						'<td>'.$this -> getColumnData($row, 'language').'</td>' .
						'<td>'.$this -> getColumnData($row, 'details').'</td>'.
						'<td>'.$this -> getColumnData($row, 'create_time').'</td>'.
						'</tr>';

			}
		} else {
			$rtn = '<tr><td colspan="8">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}
		echo $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 一覧データの設定
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function setResult($rs) {
		$this -> rs = $rs;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 一覧データの設定
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function setImages($rs2) {
		$this -> rs2 = $rs2;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 一覧データの設定
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function setAdDetails($rs) {
		$this -> adDetails = $rs[NO_COUNT];
	}

	/*-------------------------------------------------------------------------
	* @function_name: 一覧データの設定
	* @parameter	: なし
	* @return		: TRUE:成功、FALSE:失敗
	-------------------------------------------------------------------------*/
	public function getAdID() {
		return $this -> adID;
	}

	/*-------------------------------------------------------------------------
	* @function_name: ページャの表示
	* @parameter	: なし
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	function dispPager() {
		echo  $this -> getPagerCommon($this -> getTargetPage()
				, $this -> getTotalPageCommon(VAR_DEFAULT_PAGE_COUNT, count($this -> rs))
				, count($this -> rs)
				, NO_STRING
				, false);
	}

	/*-------------------------------------------------------------------------
	* @function_name: 検索条件の取得
	* @parameter	: 結果セット
	* @return		: 検索条件配列
	-------------------------------------------------------------------------*/
	public function getWhere() {
		// 変数宣言部
		$where		= NO_STRING;
		$rtn		= array();

		if($this -> mail != NO_STRING){
			$where .= ' AND mail = (\')' . $this -> mail . '(\')';	
		}

		if($this -> IP != NO_STRING){
			$where .= ' AND ip_address = (\')' . $this -> IP . '(\')';	
		}

		if($this -> adsID != NO_STRING){
			$where .= ' AND ads_id LIKE (\')%' . $this -> adsID . '%(\')';	
		}

		if($this -> from != NO_STRING) {			
			$where .= ' AND create_time >= (\')' . $this -> from . ' 00:00:00(\') ';
		}

		if($this -> to != NO_STRING) {				// 終了日
			$where .= ' AND create_time < (\')' . date('Y-m-d H:i:s', strtotime($this -> to . ' +1 days')) . '(\') ';
		}

		if($this -> language != NO_STRING) {				// 終了日
			$where .= ' AND language = (\')' . $this -> language . '(\')';
		}

		$start	= ($this -> getTargetPage() - VAL_INT_1) * VAR_DEFAULT_PAGE_COUNT;

		$page = ' LIMIT ' . $start . DELIMIT_COMMA . VAL_INT_50;

		$rtn[] = $where;
		$rtn[] = $page;

		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	public function echoFrom() {
		echo $this -> from;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	public function echoTo() {
		echo $this -> to;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	public function echoMail() {
		echo $this -> mail;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	public function echoIP() {
		echo $this -> IP;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 
	* @parameter	: 
	* @return		: 
	-------------------------------------------------------------------------*/
	public function echoAdsId() {
		echo $this -> adsID;
	}


	public function echoLanguageList() {
		// 変数宣言部
		$language[] = array(PARAM_DATA_KEY => 'en'
						, PARAM_DATA_VALUE => 'EN');
		$language[] = array(PARAM_DATA_KEY => 'ja'
						, PARAM_DATA_VALUE => 'JA');
		$language[] = array(PARAM_DATA_KEY => 'sc'
						, PARAM_DATA_VALUE => 'SC');
		$language[] = array(PARAM_DATA_KEY => 'tc'
						, PARAM_DATA_VALUE => 'TC');
		$language[] = array(PARAM_DATA_KEY => 'id'
						, PARAM_DATA_VALUE => 'ID');

		echo $this -> dispListOption($language, $this -> language);
	}

	/*-------------------------------------------------------------------------
	* @function_name: KYC画像のアップロード（個人用）
	* @parameter	: なし
	* @return		: なし
	-------------------------------------------------------------------------*/
	public function loadImageAds() {
		// ルートディレクトリを取得する
		$path = SYSTEM_DOCUMENT_ADS;

		// 該当ディレクトリの確認
		if(!file_exists($path))
			mkdir($path, 0777);
		else
			chmod($path, 0777);
		
	    $extName = basename($_FILES[PARAM_IMG1][PARAM_NAME]);
	    $extName = substr($extName, strpos($extName, "."));
	    
    	$this -> saveName = "ad_{$this -> language}_{$this -> createUId()}.{$extName}";
    	
    	// 画像の移動
    	if(move_uploaded_file($_FILES[PARAM_IMG1][PARAM_TMP_NAME], $path . DELIMIT_SLASH . $this -> saveName)) {
    	    // ファイルパーミッションの変更
    	    chmod($path . DELIMIT_SLASH . $this -> saveName, 0777);
    	    
    	    return true;
    	}
    	
    	return false;    
	}
	
	/**
	 * 
	 * some of existing values will be re-used in update query
	 * 
	 */
	public function referToExistingDetails($result){
	    $this -> saveName = $result["file_name"];
	}
	
	public function getImageAdRegistData(){
	    return [
	        VAL_INT_10, 
	        $this -> saveName, 
	        $this -> adsID, 
	        $this -> location, 
	        $this -> link, 
	        $this -> language, 
	        $this -> getAdminUserData(PARAM_UID)
	    ];
	}
	
	/*-------------------------------------------------------------------------
	* @function_name: アップロードファイルの存在確認
	* @parameter	: パラメータ
	* @return		: 存在する:true、存在しない:false
	-------------------------------------------------------------------------*/
	public function isUpload($param) {
		// 変数宣言部
		$rtn = false;

		if(isset($_FILES[$param])) {

			if(is_uploaded_file($_FILES[$param][PARAM_TMP_NAME])) {
				$rtn = true;
			}
		}

		return $rtn;
	}

	/*-------------------------------------------------------------------------
	* @function_name: 画像1フラグの取得
	* @parameter	: なし
	* @return		: 画像1フラグ
	-------------------------------------------------------------------------*/
	public function getImg1Flg() {
		return $this -> img1Flg;
	}

	public function echoImageList(){
		// 変数宣言部
		$rtn	= NO_STRING;
		$row	= null;

		if($this -> isLoopData($this -> rs2)) {
			for($cnt = 0; $cnt < count($this -> rs2); $cnt++) {		
				$row = $this -> getRowData($this -> rs2, $cnt);

				$siteDomain = SITE_DOMAIN_FULL;
				$siteProtocol = SITE_PROTOCOL;
				
				$rtn .=<<<HTMLTABLE
				<tr id="{$this -> getColumnData($row, 'id')}">
                    <td><img src="{$siteProtocol}://{$siteDomain}/documents/ads/{$this -> getColumnData($row, 'file_name')}" class="img-thumbnail" alt="Cinque Terre" width="70">'</td>
                    <td><p class="ml-3 mt-3">{$this -> getColumnData($row, 'ads_id')}</p></td>
                    <td><p class="ml-3 mt-3">{$this -> getColumnData($row, 'file_name')}</p></td>
                    <td><p class="ml-3 mt-3">{$this -> getAdminNameByUid($this -> getColumnData($row, 'created_by'))}</p></td>
                    <td><p class="ml-3 mt-3">{$this -> getColumnData($row, 'create_time')}</p></td>
                    <td class="blocka">
                       <a href="#">
                        <span id="{$this -> getColumnData($row, 'id')}" class="fa fa-info-circle fa-lg ml-3 mt-3" style="color: #0275d8;"></span>
                       </a>
                    </td>
                    <td class="blocka">
                       <a href="javascript:deleteAd('{$this -> getColumnData($row, 'id')}')">
                        <span class="fa fa-trash fa-lg ml-3 mt-3" style="color: #0275d8;"></span>
                       </a>
                    </td>
                </tr>
HTMLTABLE;
			}
		} else {
			$rtn = '<tr><td colspan="7">' . $this -> getMessage(INFO, 'I_NO_SUCHE_SEARCH_DATA', array()) . '</td></tr>';
		}
		echo $rtn;
	}

	public function echoFileName(){
		echo $this -> fileName;
	}

	public function echoAdName(){
		echo $this -> adName;
	}

	public function echoLink(){
		echo $this -> link;
	}

	public function echoID(){
		echo $this -> adID;
	}

	public function echoLocation(){
		$location 		= array('login', 'menu');
		$options 		= array();
		$rtn 			= NO_STRING;

		switch($this -> getType()){
		    case TYPE_DELETE:
		    case TYPE_IMAGE_MANAGER_UPLOAD_COMPLETE:
		    case TYPE_IMAGE_MANAGER_DETAIL:
		    case TYPE_UPDATE:
		        $loc = $this -> location;
		        break;
		    default:
		        $loc = $this -> slocation;
		        break;
		}
		
		foreach ($location as $value) {
			if($loc == $value){
				$options[] = '<option value="'.$loc.'" selected="selected">'.$loc.'</option>';
			}else{
				$options[] = '<option value="'.$value.'">'.$value.'</option>';
			}
		}
		$rtn = implode(' ', $options);
		echo $rtn;
	}

	public function echoLanguage(){
		$language 		= array('en', 'ja', 'sc', 'tc', 'id');
		$options 		= array();
		$rtn 			= NO_STRING;

		switch($this -> getType()){
		    case TYPE_DELETE:
		    case TYPE_IMAGE_MANAGER_UPLOAD_COMPLETE:
		    case TYPE_IMAGE_MANAGER_DETAIL:
		    case TYPE_UPDATE:
		        $lang = $this -> language;
		        break;
		    default:
		        $lang = $this -> slanguage;
		        break;
		}
		
		foreach ($language as $value) {
			if($lang == $value){
				$options[] = '<option value="'.$lang.'" selected="selected">'.$lang.'</option>';
			}else{
				$options[] = '<option value="'.$value.'">'.$value.'</option>';
			}
		}
		$rtn = implode(' ', $options);
		echo $rtn;
	}

	public function echoAdLanguage(){
		echo $this -> language;
	}

	public function echoAdLocation(){
		echo $this -> language;
	}

	public function getUpdateData(){
		$rtn = array();

		$rtn[] =  $this -> adName;
		$rtn[] =  $this -> link;
		$rtn[] =  $this -> location;
		$rtn[] =  $this -> language;
		$rtn[] =  $this -> saveName;
		$rtn[] =  $this -> adID;
		return $rtn;
	}
	
	public function deleteAdImageFile($result){
	    $toDelete = SYSTEM_DOCUMENT_ADS."/{$result["file_name"]}";
	    
	    if(@file_exists($toDelete))
	        unlink($toDelete);
	}

	public function getUpdateSequence(){
		$rtn 		= array();
		$adID 		= array();
		$condition = array();
		$adID 		= $this -> sequence;
		$IDarray 	= explode(',', $adID);
		$cnt 		= 1;
		
		foreach ($IDarray as $value) {
			$condition[] = $value . ' THEN ' . $cnt;
			$cnt++;
		}

		$rtn[] = implode(' WHEN ', $condition);

		var_dump($rtn);
	}

	public function getWhereAds(){

		$rtn = array();
		$whereStr = NO_STRING;
		
		switch($this -> getType()){
		    case TYPE_IMAGE_MANAGER:
		    case TYPE_SEARCH:
		        if($this -> slocation != NO_STRING){
		            $whereStr .= ' AND ads_location = (\')'.$this -> slocation.'(\')';
		        }else{
		            $whereStr .= ' AND ads_location = (\')login(\')';
		        }
		        if($this -> slanguage != NO_STRING){
		            $whereStr .= ' AND language = (\')'.$this -> slanguage.'(\')';
		        }else{
		            $whereStr .= ' AND language = (\')en(\')';
		        }
		        break;
		        
		    case TYPE_DELETE:
		    case TYPE_IMAGE_MANAGER_UPLOAD_COMPLETE:
		    case TYPE_UPDATE:
		        $whereStr .= ' AND ads_location = (\')'.$this -> location.'(\')';
		        $whereStr .= ' AND language = (\')'.$this -> language.'(\')';
		        break;
		}
		
		
		$rtn[] = $whereStr;
		return $rtn;
	}

	public function getDeleteData(){
		return [
		    $this -> adID
		];
	}

	public function checkExistImage($fileName){
		$rtn = true;
		$file = $this -> accessSelect('CHECK_EXIST_AD', array($fileName));

		if((count($file)) > NO_COUNT){
			$rtn = false;
		}

		return $rtn;
	}

	public function sessionLocation(){
		return $_SESSION['location'];
	}

	public function sessionLanguage(){
		return $_SESSION['language'];
	}

	/*-------------------------------------------------------------------------
	* @function_name: getActivity
	* @parameter	: none
	* @return		: 表示用HTML文字列
	-------------------------------------------------------------------------*/
	public function getActivity(){
		$type             = $this -> getType();
		$details          = array();
		$fileDetails      = $this -> getFileDetailsByID($this -> adID);
		
   		if($type == TYPE_IMAGE_MANAGER_UPLOAD_COMPLETE){
   			$message = "Uploaded {$this -> saveName} [{$this -> adsID}]";
   		}elseif($type == TYPE_DELETE && $this -> isLoopData($fileDetails)){
   			$message = "Deleted [{$this -> getColumnData($fileDetails, 'ads_id')}]";
   		}elseif($type == TYPE_UPDATE && $this -> isLoopData($fileDetails)){
   			 $origID 		= $this -> getColumnData($fileDetails, 'ads_id');
			 $newID 		= $this -> adName;
			 $origLink 		= $this -> getColumnData($fileDetails, 'redirect_link');
			 $newLink 		= $this -> link;
			 $origLang 		= $this -> getColumnData($fileDetails, 'language');
			 $newLang 		= $this -> language;
			 $origLoc 		= $this -> getColumnData($fileDetails, 'ads_location');
			 $newLoc 		= $this -> location;
			 
   			if($origID != $newID){
   			    $details[] = "Edited ID of {$this -> getColumnData($fileDetails, 'ads_id')} from [{$origID}] to [{$newID}]";
   			}

   			if($origLink != $newLink){
   			    $details[] = "Edited Link of {$this -> getColumnData($fileDetails, 'ads_id')} from [{$origLink}] to [{$newLink}]";
   			}

   			if($origLang != $newLang){
   			    $details[] = "Edited Language of {$this -> getColumnData($fileDetails, 'ads_id')} from [{$origLang}] to [{$newLang}]";
   			}

   			if($origLoc != $newLoc){
   			    $details[] = "Edited Location of {$this -> getColumnData($fileDetails, 'ads_id')} from [{$origLoc}] to [{$newLoc}]";
   			}

   			if($this -> isUpload(PARAM_IMG1)){
   			    $details[] = "Uploaded New Image of {$this -> getColumnData($fileDetails, 'ads_id')}";
   			}
   			
   			if($details != NULL){
   				$message = implode(", <br/>", $details);
   			}else{
   				$message = "Saved without any changes";
   			}
   		}

		$rtn = array();

		$rtn[] = $this -> getAdminUserData(PARAM_UID);
		$rtn[] = $_SERVER[PARAM_REMOTE_ADDR];
		$rtn[] = $_SERVER[PARAM_HTTP_USER_AGENT];
		$rtn[] = 26;
		$rtn[] = date("Y-m-d H:i:s");
		$rtn[] = $message;

		return $rtn;
	}

	public function getFileDetailsByID($id){
	    return $this -> getRowData($this -> accessSelect('SELECT_AD_DETAILS', array($id)));
	}
}