<?php
 /**
 *      [QKSHOP] (C) QIKEWEB Inc.
 *      This is NOT a freeware, use is subject to license terms
 */

class ServiceModel extends BaseModel{

	function addCategory($params){
		$act=$params['act'];
		if($act=="add"){
			$name = $params['name'];
			$parentId = $params['parentId'];
			$sortId = $params['sortId'];
			if(settype($sortId,"integer")===false){$sortId=50;}
			if(!$parentId || !settype($parentId,"integer")){$parentId=0;}
			
			$nameArr = explode("\r\n",$name);
			$i=0;
			foreach($nameArr as $item){
				$name = $item;
				if($name){
					if($act=="add"){
						$sql = "insert into qk_service_cat set ";
					}else if($act=="edit"){
						$sql = "update qk_service_cat set ";
					}
					$sql .= " name='$name',parentId='$parentId',sortId='$sortId'";
					if($act=="add"){
						$sql.=",posttime=UNIX_TIMESTAMP()";
					}else if($act=="edit"){
						$sql .= " where id='".$id."'";
					}
					if($this->db->query($sql)){
						$i++;
					};
				}
			}
			if($i>0 || $i==count($nameArr)){
				unset($i);
				return true;
			}
			unset($i);
		}
		return false;

	}

	function getCategory($catId=0){
		global $db;
		$tmp = array();
		$catInfo = $db->getRow("select name,parentId,sortId,id,posttime from qk_service_cat where id='".$catId."' order by sortId asc");
		if(!$catInfo['name'] && $catId!=0){return;}
		if($catId!==0){
				$grade=$this->getCatGrade($catId);
		$tmp[] = array("id"=>$catId,"name"=>$catInfo['name'],"parentId"=>$catInfo['parentId'],"grade"=>$grade,"sortId"=>$catInfo['sortId'],"id"=>$catInfo['id'],"posttime"=>$catInfo['posttime']);
		}
		$sql = "select * from qk_service_cat where parentId=".$catId." and iStatus=1 order by sortId asc";
		$res = $db->getAll($sql);
		if($res){
			foreach($res as $item){
				$tmp = array_merge($tmp,$this->getCategory($item['id']));
			}
		}
		return $tmp;
	}

	function getCatGrade($catId){
		global $db;
		$grade = 0;
		$cats = $catId;
		$sql = "select parentId from qk_service_cat where id='".$catId."'";
		$res = $db->getRow($sql);
			if($res && $res['parentId']>0){
				$grade++;
				$grade += $this->getCatGrade($res['parentId']);
			}
		return $grade;
	}

}
?>