<?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 category{
	function get_category_tree(){
		global $predata_class;
		$update_categories=false;
		/////////////////////////////副类目产品获取
		//$sql="select * from products where (products_id,master_categories_id) not in (select products_id,categories_id as master_categories_id from products_to_categories) and products_id in(select products_id from products_description where language_id=2)";
		//$a=openzcQuery($sql);
		//$a=openzc_table_to_list($a);
		//print_r($a);exit;
		/////////////////////////////

		$info=openzcQuery("show full fields from ".TABLE_CATEGORIES_DESCRIPTION);
		$info=openzc_table_to_list($info,'Field');
		if(!isset($info['categories_sub_id'])){
			openzcQuery("alter table ".TABLE_CATEGORIES_DESCRIPTION." add categories_sub_id text(0) null");
			$update_categories=true;
		}
		if(!isset($info['categories_sub_all_id'])){
			openzcQuery("alter table ".TABLE_CATEGORIES_DESCRIPTION." add categories_sub_all_id text(0) null");
			$update_categories=true;
		}
		if(!isset($info['categories_level'])){
			openzcQuery("alter table ".TABLE_CATEGORIES_DESCRIPTION." add categories_level int(2) null");
			$update_categories=true;
		}
		
			$sale=openzcQuery("select * from ".TABLE_SALEMAKER_SALES." where sale_status='1' order by sale_id asc");
			$sale=openzc_table_to_list($sale);
			$saledata=[];
			foreach($sale as $k => $v){
				$cid=explode(",",$v['sale_categories_all']);
				foreach($cid as $a => $b){
					if(!isset($saledata[$b])){
						$saledata[$b]['sale_name']=$v['sale_name'];
						$saledata[$b]['sale_deduction_type']=$v['sale_deduction_type'];
						switch($v['sale_deduction_type']){
							case 0:
								$saledata[$b]['sale_discount']=$v['sale_deduction_value']."%";
							break;
							case 1:
								$saledata[$b]['sale_discount']=$v['sale_deduction_value'];
							break;
							case 2:
								$saledata[$b]['sale_discount']=$v['sale_deduction_value'];
							break;
						}
					}
				}
			}
			$cache_categories_file="./cache/".md5("categories_tree_".$_SESSION['languages_id']).".inc";
			if(!is_file($cache_categories_file)){
				$update_categories=true;
			}
			//$update_categories=true;
			//类目数据更新
			if($update_categories==true){
				
				//更新当前栏目的子栏目
				$categories_sql="select c.categories_status,c.categories_id,c.parent_id,c.categories_image,cd.categories_name,cd.categories_description from ".TABLE_CATEGORIES." c inner join ".TABLE_CATEGORIES_DESCRIPTION." cd on cd.categories_id=c.categories_id and c.categories_status>0 and cd.language_id=".(int)$_SESSION['languages_id'];
				$categories=openzcQuery($categories_sql);
				$categories=openzc_table_to_list($categories,"categories_id");
				if(count($categories)==0){return false;}
				$parent_group=openzcQuery("select c.categories_id,c.parent_id from ".TABLE_CATEGORIES." c inner join ".TABLE_CATEGORIES_DESCRIPTION." cd on c.categories_id=cd.categories_id where cd.language_id='".(int)$_SESSION['languages_id']."' and c.categories_status=1");
				while (!$parent_group->EOF) {
					$parent_data[$parent_group->fields['parent_id']][]=$parent_group->fields['categories_id'];
					$parent_group->MoveNext();
				}

				foreach($categories as $k => $v){
					$categories[$k]['categories_sub_all_id']=$this->get_categories_sub_all_id($v['categories_id'],$parent_data,$v['categories_id']);
					
				}

				foreach($parent_data as $k => $v){
					if($k!=0){
						$categories_name=str_replace("'","\'",$categories[$k]['categories_name']);
						$categories_description=str_replace("'","\'",$categories[$k]['categories_description']);

						$string="('".$k."','".$_SESSION['languages_id']."','".$categories_name."','".$categories_description."','".join(",",$v)."','".$categories[$k]['categories_sub_all_id']."')";
						$update_values[]=$string;
					}
				}
				if(count($update_values)){
					$update_field="(categories_id,language_id,categories_name,categories_description,categories_sub_id,categories_sub_all_id)";
					$update_current_son_id_sql="replace into ".TABLE_CATEGORIES_DESCRIPTION." ".$update_field." values ".join(",",$update_values);
					openzcQuery($update_current_son_id_sql);
				}
				
				

				//更新类目层级
				$categories_level=$this->get_categories_level();
				foreach($categories_level as $k => $v){
					$sql="update ".TABLE_CATEGORIES_DESCRIPTION." set categories_level='".($k+1)."' where categories_id in(".$v.") and language_id='".$_SESSION['languages_id']."'";
					openzcQuery($sql);
				}
				openzcQuery("update ".TABLE_CATEGORIES_DESCRIPTION." set categories_sub_id='none',categories_sub_all_id='none' where categories_sub_id is null and language_id=".$_SESSION['languages_id']);

				$categories_sql="select c.categories_status,c.categories_id,c.parent_id,c.categories_image,cd.categories_name,cd.categories_description,cd.categories_sub_id,cd.categories_sub_all_id,cd.categories_level from ".TABLE_CATEGORIES." c inner join ".TABLE_CATEGORIES_DESCRIPTION." cd on cd.categories_id=c.categories_id and c.categories_status>0 and cd.language_id=".(int)$_SESSION['languages_id'];
				$categories=openzcQuery($categories_sql);
				$categories=openzc_table_to_list($categories,"categories_id");
				
			/*
			$categories=openzcQuery("select c.categories_status,c.categories_id,c.parent_id,c.categories_image,cd.categories_name,cd.categories_description,c.categories_sub_id,c.categories_sub_all_id,c.categories_level from ".TABLE_CATEGORIES." c inner join ".TABLE_CATEGORIES_DESCRIPTION." cd on cd.categories_id=c.categories_id and c.categories_status='1' and cd.language_id=".(int)$_SESSION['languages_id']);
			$categories=openzc_table_to_list($categories,"categories_id");
			*/
			
			//类目产品数量
			/*
			$procount=openzcQuery("select count(DISTINCT ptc.products_id) as count,ptc.categories_id from ".TABLE_PRODUCTS_TO_CATEGORIES." ptc left join ".TABLE_PRODUCTS." p on p.products_id=ptc.products_id left join ".TABLE_PRODUCTS_DESCRIPTION." pd on pd.products_id=p.products_id where p.products_status='1' and pd.language_id='".(int)$_SESSION['languages_id']."' group by ptc.categories_id");
			$procount=openzc_table_to_list($procount,"categories_id");
			*/
			//$procount_sql="select count(DISTINCT ptc.products_id) as count,ptc.categories_id from ".TABLE_PRODUCTS_TO_CATEGORIES." ptc inner join ".TABLE_PRODUCTS." p on p.products_id=ptc.products_id where p.products_status='1' and p.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=?) group by ptc.categories_id";
			/*
			$procount_sql="select products_id from ".TABLE_PRODUCTS." where products_status>0 union all select products_id from products_description where language_id=2";
			$sql="select p.master_categories_id,count(*) as count from products p where p.products_id in (".$procount_sql.") group by p.master_categories_id";
			$procount=openzcQuery($sql);exit;
			*/
			$procount_sql="select p.master_categories_id as categories_id,count(*) as count from ".TABLE_PRODUCTS." p where p.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id='".$_SESSION['languages_id']."') and p.products_status>0 group by p.master_categories_id order by null";
			
			$procount=openzcQuery($procount_sql);
			$procount=openzc_table_to_list($procount,"categories_id");
			
			//副类目产品统计暂时废弃
			/*
			$sql="select count(products_id) as count,master_categories_id as categories_id from ".TABLE_PRODUCTS." where (products_id,master_categories_id) not in (select products_id,categories_id as master_categories_id from ".TABLE_PRODUCTS_TO_CATEGORIES.") and products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") group by master_categories_id";
			$deputy_categories=openzcQuery($sql);
			$deputy_categories=openzc_table_to_list($deputy_categories,"categories_id");
			
			foreach($deputy_categories as $k => $v){
				$procount[$v['categories_id']]['count']=$procount[$v['categories_id']]['count']+$v['count'];
			}
			*/
			//类目价格范围获取
			
			$categories_price_range=$this->get_price_range();

				
				$update_time=openzcQuery("select * from ".TABLE_OPENZC_TRIGGER." where table_name='".TABLE_CATEGORIES."' order by id desc limit 0,1");
				$update_time=openzc_table_to_list($update_time);

				$recorder_file="./cache/".md5(DB_DATABASE).".inc";
				$recorder=json_decode(file_get_contents($recorder_file),true);
				$recorder[TABLE_CATEGORIES]['Update_time']=$update_time[0]['last_modified'];
				$recorder_file = fopen($recorder_file, "w") or die("Unable to open file recorder!");
				fwrite($recorder_file, json_encode($recorder));
				fclose($recorder_file);
			

			$categories=$this->get_categories_procount($categories,$procount);

			$categories=$this->get_categories_images($categories);
			
			foreach($categories as $k => $v){
				//$v['son']=$v['categories_sub_all_id'];
				if($v['categories_sub_id']!="none"){
					$v['has_sub_cat']=true;
				}
				if($v['categories_sub_all_id']=="none"){
					$range=$this->get_categories_range($categories_price_range,$v['categories_id']);
				}else{
					$range=$this->get_categories_range($categories_price_range,$v['categories_sub_all_id']);
				}
				
				$v['max']=$range['max'];
				$v['min']=$range['min'];
				
				//$v['max']=$categories_price_range[$k]['max'] ? $categories_price_range[$k]['max'] : '0';
				//$v['min']=$categories_price_range[$k]['min'] ? $categories_price_range[$k]['min'] : '0';
				$v['path']=join("_",$this->get_category_parent($k,$categories));
				$v['categories_link']=str_replace("&amp;","&",zen_href_link(FILENAME_DEFAULT, "&cPath=".$v['path']));
				$v['categories_link']=str_replace(HTTP_SERVER,"",$v['categories_link']);
				$v['categories_link']=str_replace(HTTPS_SERVER,"",$v['categories_link']);
				$v['current_status']=false;
				$categories[$k]=$v;
			}
			
			if(isset($_GET['cPath'])){
				$cPath=explode("_",$_GET['cPath']);
				foreach($cPath as $k => $v){
					$categories[$v]['current_status']="active";
				}
			}
			
			$cache_categories = fopen($cache_categories_file, "w") or die("Unable to open cache categories file!");
			fwrite($cache_categories, json_encode($categories));
			fclose($cache_categories);
		}else{
			$cache=file_get_contents($cache_categories_file);
			$categories=json_decode($cache,true);
		}
	
		return $categories;
	}
	function get_categories_sub_all_id($cid="",$parent_data=[],$string=""){
		$cid=array_filter(array_unique(explode(",",$cid)));
		$continue=false;
		$son_ids="";
		foreach($cid as $k => $v){
			if(isset($parent_data[$v])){
				$continue=true;
				$son_ids.=",".join(",",$parent_data[$v]);
				$string.=",".join(",",$parent_data[$v]);
			}
		}
		if($continue==true){
			$string=$this->get_categories_sub_all_id($son_ids,$parent_data,$string);
		}
		return $string;
	}
	function get_categories_level($level=0,$data=[]){
		if($level==0){
			$listdata=openzcQuery("select c.categories_id from ".TABLE_CATEGORIES." c inner join ".TABLE_CATEGORIES_DESCRIPTION." cd on c.categories_id=cd.categories_id where c.parent_id=0 and c.categories_status=1 and cd.language_id=".(int)$_SESSION['languages_id']);
			while (!$listdata->EOF) {
				foreach($listdata->fields as $k => $v){
					$data[$level][]=$v;
				}
				$listdata->MoveNext();
			}
			$data[$level]=join(",",$data[$level]);
			$level++;
			$data=$this->get_categories_level($level,$data);
		}else{
			$listdata=openzcQuery("select c.categories_id from ".TABLE_CATEGORIES." c inner join ".TABLE_CATEGORIES_DESCRIPTION." cd on c.categories_id=cd.categories_id where c.parent_id in(".$data[$level-1].") and c.categories_status=1 and cd.language_id=".(int)$_SESSION['languages_id']);
			if($listdata->resource->num_rows>0){
				while (!$listdata->EOF) {
					foreach($listdata->fields as $k => $v){
						$data[$level][]=$v;
					}
					$listdata->MoveNext();
				}
				$data[$level]=join(",",$data[$level]);
				$level++;
				$data=$this->get_categories_level($level,$data);
			}else{
				return $data;
			}
		}
		return $data;
	}
	function get_categories_range($range=[],$cids=""){
		$cids=array_filter(explode(",",$cids));
		$result=[];
		foreach($cids as $k => $v){
			if(isset($range[$v])){
				if(!isset($result['max'])){$result['max']=$range[$v]['max'];}
				if(!isset($result['min'])){$result['min']=$range[$v]['min'];}
				if($range[$v]['max']>$result['max']){$result['max']=$range[$v]['max'];}
				if($range[$v]['min']<$result['min']){$result['min']=$range[$v]['min'];}
			}
		}
		return $result;
	}
	function get_categories_procount($categories=[],$products_count=[]){
		foreach ($categories as $k => $v) {
			$count=0;
			if($v['categories_sub_id']!="none"){
				$ids=explode(",",$v['categories_sub_all_id']);
				foreach($ids as $a => $b){
					$count+=$products_count[$b]['count'];
				}
			}else{
				if(isset($products_count[$k])){
					$count=$products_count[$k]['count'];
				}else{
					$count=0;
				}
			}
			$categories[$k]['count']=$count;
		}
		return $categories;
	}

	function get_categories_sub_tree($categories=[],$categories_tree=[],$level=1){
		foreach($categories_tree as $k => $v){
			if($v['parent_id']==0){$level=1;}else{
				$level=$categories[$v['parent_id']]['categories_level']+1;
			}
			if(isset($v['sub']) && is_array($v['sub'])){
				$categories[$v['categories_id']]['sub']=$v['sub'];
				$categories=$this->get_categories_sub_tree($categories,$v['sub'],$level);
			}
			$categories[$v['categories_id']]['categories_level']=$level;
		}
		return $categories;
	}

	function get_categories_sub_id($categories=[],$str=[]){
		foreach($categories as $k => $v){
			$str[$v['categories_id']]=$v['categories_id'];
			if(isset($v['sub'])){
				$str=$this->get_categories_sub_id($v['sub'],$str);
			}
		}
		return $str;
	}

	function get_categories_subs($ary = array(), $pid = 0, $level = 10, $i = 1){
	    $arr = array();
	    foreach($ary as $rs){
	        if($rs['parent_id'] == $pid){
	            if($i <= $level){
	                $arr[$rs['categories_id']] = $rs;
	            }else{
	                break;
	            }
	            $n = $i;
	            $n++;
	            $sub = $this->get_categories_subs($ary, $rs['categories_id'],  $level, $n);
	            foreach($sub as $a => $b){
	            	$result[$pid][$b['categories_id']]=$b['categories_id'];
	            }
	            empty($sub) OR $arr[$pid]['sub'] = join(",",$result[$pid]);
	        }else{
	            continue;
	        }
	    }
	    return $arr;
	}

	function aryTree($ary = array(), $pid = 0, $level = 10, $i = 1,$parent=[]){
	    $arr = array();
	    foreach($parent[$pid] as $rs){
	            if($i <= $level){
	                $arr[$rs['categories_id']] = $rs;
	            }else{
	                break;
	            }
	            $n = $i;
	            $n++;
	            $sub = $this->aryTree($ary, $rs['categories_id'],  $level, $n,$parent);
	            empty($sub) OR $arr[$rs['categories_id']]['sub'] = $sub;
	        
	    }
	    return $arr;
	}
    
    function get_category_parent($id='',$categories=[],$str=[]){
		$parent_id=$categories[$id]['parent_id'];
		array_unshift($str,$id);
		if($parent_id!=0){
			$str=$this->get_category_parent($parent_id,$categories,$str);
		}
		return $str;
    }
  
    function get_category_has_sub($id='',$categories=[],$n=0){
		foreach($categories as $k=> $v){
			if($v['parent_id']==$id){
				$n=1;
				return $n;
			}
		}
		return $n;
	}
	function get_category_get_current_son($categories=[],$id='',$str=''){
		foreach($categories as $k => $v){
			if($v['parent_id']==$id){
				if($str){
					$str.=",".$v['categories_id'];
				}else{
					$str=$v['categories_id'];
				}
				if(array_key_exists("has_sub_cat",$v)){
					$str=$this->get_category_get_current_son($categories,$v['categories_id'],$str);
				}
			}
		}
		return $str;
	}
	
	
	function get_categories_list($GET=[],$parameter=[]){
		global $predata_class;
		
		if(!is_array($parameter['cid'])){$parameter['cid']=array_filter(explode(",",$parameter['cid']));}
		$categories=$predata_class->getPredata(TABLE_CATEGORIES);
		if($parameter["has_sub"]=="true"){
			
			foreach($parameter['cid'] as $k => $v){
				if($categories[$v]['has_sub_cat']==0){unset($parameter['cid'][$k]);}
			}
		}
		if($parameter["has_pro"]=="true"){
			
			foreach($parameter['cid'] as $k => $v){
				if(!isset($categories[$v]['count']) || !$categories[$v]['count']){
					unset($parameter['cid'][$k]);
				}
			}
		}
		if($parameter['row']){
			$i=0;
			foreach($parameter['cid'] as $k => $v){
				if($i>=$parameter['row']){unset($parameter['cid'][$k]);}
				$i++;
			}
		}
	
		return $this->show_categories_list($GET,$parameter);
	}
  
	function show_categories_list($GET=[],$parameter=[]){
		global $predata_class,$currencies;
		$categories_tree=$predata_class->getPredata(TABLE_CATEGORIES);
		if($_GET['main_page']=="index" && isset($_GET['cPath'])){
			$categories_tree=$this->get_current_status($categories_tree);
		}
		
		if($parameter['limit']){$limit=explode(",",$parameter['limit']);$row=0;}

		$n=0;
		foreach($parameter['cid'] as $k => $v){
			$status=true;
			if($parameter['limit']){
				if($row>=$limit[0] && $row < $limit[1]){
					$status=true;
				}else{
					$status=false;
				}
				$row++;
			}
			if($categories_tree[$v]['categories_status']==0){$status=false;}
			
			if($status==true){
				$datalist[$n]=$categories_tree[$v];
				$datalist[$n]['sort_index']=$n;
				if($parameter['imgsizer']){
					$datalist[$n]['categories_image']=$this->get_images_sizer($datalist[$n]['categories_image'],$parameter['imgsizer'],$parameter['bgcolor']);
				}
				if(isset($categories_tree[$v]['sale_name'])){
					if($categories_tree[$v]['sale_deduction_type']==1){
						$datalist[$n]['sale_discount']="-".$currencies->format($categories_tree[$v]['sale_discount']);
					}
					if($categories_tree[$v]['sale_deduction_type']==2){
						$datalist[$n]['sale_discount']=$currencies->format($categories_tree[$v]['sale_discount']);
					}
				}
				$n++;

			}
		}
		return $datalist;
	}
	function get_images_sizer($images='',$sizer='',$bgcolor=''){
		global $ImageSizer;
		if(!is_dir(IMGCACHE_DIR)){mkdir(IMGCACHE_DIR);}
		
		if($sizer){
			$sizer=explode(",",$sizer);
			$imgname=getCacheImgname(basename($images));
			$imgdir=IMGCACHE_DIR.$sizer[0]."-".$sizer[1]."/";
			$image_new=$imgdir.$imgname;
			if(!is_dir($imgdir)){
				mkdir($imgdir);
			}
			if(getCacheImgcheck($image_new)==true){
				$ImageSizer->Run(".".$images);
				$ImageSizer->resize($sizer[0],$sizer[1],$bgcolor);
				$ImageSizer->save($image_new);
			}
			$result=DIR_WS_CATALOG.str_replace(ROOT_PATH,"",$imgdir).$imgname;
		}
		$result=str_replace("//","/",$result);
		return $result;
		
	}
	function get_current_status($data=[],$current=''){
		if(!$current){
			$current=openzc_get_current_cpath($_GET['cPath']);
		}
		$data[$current]['current_status']=1;
		if($data[$current]['parent_id']!=0){
			$data=$this->get_current_status($data,$data[$current]['parent_id']);
		}
		return $data;
	}
	function get_all_top($result=array()){
		global $predata_class;
		$categories=openzcQuery("select categories_id from ".TABLE_CATEGORIES." where categories_status=1 and parent_id=0");
		$categories=openzc_table_to_list($categories,"categories_id");
		foreach($categories as $k => $v){
		    $result[$k]=$k;
		}
		return join(",",$result);
	}
	function get_categories_images($categories=[]){
		foreach($categories as $k => $v){
			if($v['categories_image']){
				if(is_file("./images/".$v['categories_image'])){
					$categories[$k]['categories_image']=DIR_WS_CATALOG."images/".$v['categories_image'];
				}else if(is_file("./".$v['categories_image'])){
					$categories[$k]['categories_image']=DIR_WS_CATALOG.$v['categories_image'];
				}
			}
		}
		return $categories;
	}
	function checkDataUpdate(){
		define("TABLE_OPENZC_TRIGGER",DB_PREFIX."openzc_trigger");
		$sql="select last_modified from ".TABLE_OPENZC_TRIGGER." where table_name in ('".TABLE_CATEGORIES."','".TABLE_CATEGORIES_DESCRIPTION."','".TABLE_PRODUCTS_TO_CATEGORIES."','".TABLE_PRODUCTS."') order by last_modified desc limit 1";
		$result=openzcQuery($sql);
		return $result->fields['last_modified'];
	}
	function get_price_range(){

		$sql="select p.master_categories_id as categories_id,round(max(p.products_price_sorter)) as max,round(min(p.products_price_sorter)) as min from ".TABLE_PRODUCTS." p where p.products_status>0 and p.products_id in(select products_id from ".TABLE_PRODUCTS_DESCRIPTION." where language_id=".$_SESSION['languages_id'].") group by p.master_categories_id order by null";
		
		$data=openzcQuery($sql);
		$data=openzc_table_to_list($data,"categories_id");
		return $data;
	}
	//查询语句预处理
	function get_prepare_sql($name="",$sql="",$varlist=[],$index_field=""){
		$sqllist=[];
		$using=[];
		foreach($varlist as $k => $v){
			$sql=str_replace("$".($k+1),$v,$sql);
		}
		$sqllist[]="PREPARE ".$name." from ".'"'.$sql.'"';
		foreach($varlist as $k => $v){
			$sqllist[]="set @var".($k+1)."='".$v."'";
			$using[]="@var".($k+1);
		}
		$sqllist[]="EXECUTE ".$name." USING ".join(",",$using);
		$sqllist[]="DEALLOCATE PREPARE ".$name;
		
		foreach($sqllist as $k => $v){
			if(strstr($v,"EXECUTE")){
				$data=openzcQuery($v);
				$data=openzc_table_to_list($data,$index_field);
			}else{
				openzcQuery($v);
			}
		}

		return $data;
	}
}
?>