<?php

class services {

public function __construct(){
		global $err;
		
		$act=preg_replace('/[^a-z_]/','',$_GET['act']);
		if($act){
			call_user_func(array(&$this,$act));
		} 
	}

	public function get(){
		global $DB;
		$limit=intval($_POST['limit']);
		$start=intval($_POST['start']);
		
		$dir=preg_replace("/[^(ASC|DESC)]/",'',$_POST['dir']);
		if($dir!='ASC'&&$dir!='DESC') $dir='ASC';
		$sort=$_POST['sort'];
		if(!$sort){
			$sort='id';
		}
		
		$where_str=array();
		
		function parse_sql_query($item){
			return $item;
		}
		
		$search=$_POST;
		if (strlen($search["name"]) && $search["name"] != "Название"){
			$query = split(" ", $search["name"]);
			foreach ($query as $item)
			$where_str[] = " name LIKE '%".parse_sql_query($item)."%'";
		}		
		
		if (count($where_str)) {
			$where = join(" AND ", $where_str);			
		} else {
			$where = "1=1";
		}
		
		$data = $DB->selectPage($totalCount,"
								SELECT * FROM idate WHERE $where 
								ORDER BY $sort $dir 
								LIMIT ?d,?d",$start,$limit);	
		$json=array("totalCount"=>$totalCount,"data"=>$data);
		echo json_encode($json);
	}
	
	public function save(){
		global $DB;
		
		$idate_id=intval($_GET[idate_id]);
		$obj["name"]=$_POST['name'];
		$obj["day"]=$_POST['day'];
		
		$obj["name"]=preg_replace("/[^a-zA-Z0-9_]/",'',$_POST['name']);
		if(!$obj["name"]||$obj["name"]!=$_POST["name"]) error("Введите название в формате [a-zA-Z0-9_]!");
		if($obj["day"] > 28 || $obj["day"] < 1) error("Введите число в пределах 1-28!");
		$DB->query("INSERT INTO idate set ?a",$obj);
		
		success();
	}
	
}

?>