<?php

class users {
	
	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';
		}
		
		$data = $DB->selectPage($totalCount,"
								SELECT * FROM users 
								ORDER BY $sort $dir 
								LIMIT ?d,?d",$start,$limit);	
		$json=array("totalCount"=>$totalCount,"data"=>$data);
		echo json_encode($json);
	}
	
	public function save(){
		global $DB;
		
		$user_id=intval($_GET[user_id]);
		if($_POST['email']!='E-mail')$obj["email"]=$_POST['email'];
		if($_POST['mobile_phone']!='+7 928XXXXXXX') $obj["mobile_phone"]=$_POST['mobile_phone'];
		if($_POST['home_phone']!='+7 495 XXXXXXX') $obj["home_phone"]=$_POST['home_phone'];
		if($_POST['full_name']!="ФИО") $obj["full_name"]=$_POST['full_name'];

		if($_POST['new_pass'] || $_POST['new_pass_confirm']) {
			if($_POST['new_pass']==$_POST['new_pass_confirm']){
				$obj["pass"]=md5($_POST['new_pass']);
			} else {
				error("Пароли не совпадают!");
			}
		}
		
		if($user_id==0){
			if(!$obj["full_name"]||$obj["full_name"]=="ФИО") error("Введите ФИО пользователя!");
			$obj["login"]=preg_replace("/[^a-zA-Z0-9_]/",'',$_POST['login']);
			if(!$obj["login"]||$obj["login"]!=$_POST["login"]) error("Введите Логин в формате [a-zA-Z0-9_]!");
			
			if(!$obj["pass"]) error("Введите пароль!");
			
			$DB->query("INSERT INTO users set ?a",$obj);
		} else {
			$DB->query("UPDATE users set ?a WHERE id=?d",$obj,$user_id);
		}
		
		success();
	}

	public function details(){
		global $DB;
		$data = $DB->select("SELECT * FROM users WHERE users.id=?d",intval($_POST["id"]));	
		
		$json=array("success"=>true,"data"=>$data);
		echo json_encode($json);
	}

}
?>