<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, Openzc, Inc.
 * @license      http://www.openzc.cn/license.txt
 */
class msgModel{
	function Run(&$atts, &$refObj, &$fields){
		global $messageStack;
		$attlist = "type=all,name=,tpl=,loop=false";//$type:error,success,caution
		FillAtts($atts,$attlist);
		FillFields($atts,$fields,$refObj);
		extract($atts, EXTR_OVERWRITE);
		$message=array();
		if(count($messageStack->messages)==0){
			$messageStack->size('header');
			$_SESSION['messageToStack'] = array();
		}
		
		$messageStack->size($name);
		if(!$tpl){$tpl="message.tpl";}
		$html=file_get_contents(TPL_MODULES."tpl/".$tpl);
		$GLOBALS["tplfile"][]=str_replace(TEMPLATE_TPL,"",TPL_MODULES."tpl/".$tpl);
		
		foreach($messageStack->messages as $k => $v){
			if(strstr($v['params'],"Error") || strstr($v['params'],"error") || strstr($v['params'],"danger")){$v['type']="error";}
			if(strstr($v['params'],"Success") || strstr($v['params'],"success")){$v['type']="success";}
			if(strstr($v['params'],"Warning") || strstr($v['params'],"warning")){$v['type']="caution";}
			if(strstr($v['params'],"Caution") || strstr($v['params'],"caution")){$v['type']="caution";}
			if($v['class']=="shopping_cart"){$v['type']="error";}
			$v['text']=preg_replace("'<img(.*?)>'is","",$v['text']);
			$message[$v['class']][]=$v;
		}
		$_SESSION['messageToStack'] = array();
		if($name){
			if(isset($_GET['action']) && $name=="contact_us" && $_GET['action']=="success"){
				$message[$name][]=["type"=>"success","text"=>TEXT_SUCCESS];
			}
			$result="";
		
			if($type=="all" && $loop=="true"){
				$result=[];
				if($name!="all"){
					$name=array_filter(explode(",",$name));
					foreach($name as $k => $v){
						if(isset($message[$v])){
							foreach($message[$v] as $a => $b){
								$result[]=$b;
							}
						}
					}
					
				}else{
					foreach($message as $k => $v){
						foreach($v as $a => $b){
							$result[]=$b;
						}
					}
				}
				return $result;
			}
			if($type && $type!="all"){
				$type=array_filter(explode(",",$type));
				$type=array_value_to_key($type);
				foreach($message[$name] as $k => $v){
					if(isset($type[$v['type']])){
						$content=$this->getTpl($html,$v['type']);
						$str=str_replace("[field:text/]",$v['text'],$content);
						$result.=$str;
					}
				}
			}else{
				foreach($message[$name] as $k => $v){
					$content=$this->getTpl($html,$v['type']);
					$str=str_replace("[field:text/]",$v['text'],$content);
					$result.=$str;
				}
			}
		}

		return $result;
	}
	
	private function getTpl($html,$name){
		$start=strpos($html,"{type:".$name."}")+strlen("{type:".$name."}");
		$end=strpos($html,"{/type:".$name."}");
		$length=$end-$start;
		if($length<0){
			return false;
		}
		$content=substr($html,$start,$length);
		return $content;
    }
}
?>