<?php

class clients {
	
	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["login"]) && $search["login"] != "Логин"){
			$query = split(" ", $search["login"]);
			foreach ($query as $item)
			$where_str[] = "login LIKE '%".parse_sql_query($item)."%'";
		}		
		if (strlen($search["home_phone"]) && $search["home_phone"] != "Домашний телефон"){
			$query = split(" ", $search["home_phone"]);
			foreach ($query as $item)
			$where_str[] = " cli.home_phone LIKE '%".parse_sql_query($item)."%'";
		}
		if (strlen($search["mobile_phone"]) && $search["mobile_phone"] != "Мобильный телефон"){
			$query = split(" ", $search["mobile_phone"]);
			foreach ($query as $item)
			$where_str[] = " cli.mobile_phone LIKE '%".parse_sql_query($item)."%'";
		}
		if (count($where_str)) {
			$where = join(" AND ", $where_str);			
		} else {
			$where = "1=1";
		}
		
		$data = $DB->selectPage($totalCount,"
								SELECT * FROM clients 
								WHERE $where
								ORDER BY $sort $dir 
								LIMIT ?d,?d",$start,$limit);	
		$json=array("totalCount"=>$totalCount,"data"=>$data);
		echo json_encode($json);
	}
	
	public function details(){
		global $DB;
		$data = $DB->select("SELECT * FROM clients WHERE id=?d",intval($_POST["id"]));	
		
		$json=array("success"=>true,"data"=>$data);
		echo json_encode($json);
	}
	
}
?>