<?php 




app::api("getdataapiutilisateurs",function($data){
	if(!Droit("module-utilisateur")->ok()) return false;
	$sql = "SELECT * FROM ¤USERS";
	if (!user::isAdmin()) {
		$sql .=" WHERE type<>'Administrateur'";
	}
	if (!empty($data["_action"])) {
		if(!empty($data["item"])) $item = $data["item"];
		switch ($data["_action"]) {
			case 'save':
				$action = is_numeric($item["id"])?"modifier":"ajouter";
				if ($action == "modifier" && Droit("droit-utilisateur")->ok()) {
					Droit::setAll($item["id"],$item["data"]);
				}
				if(Droit("$action-utilisateur")->ok()){
					if ($action == "modifier") {
						$id = $item["id"];
						if (!db::row("SELECT id FROM ¤USERS where id<>$id and type='Administrateur'")) {
							if ($item["type"] != "Administrateur") {
								app::apiRep("alert","Modification impossible !");
								return $item;
							}
						}
					}
					$id = db::save("¤USERS",$item);
					$item = db::row("SELECT * FROM ($sql) t where id=$id");
					client::notification("Enregistré","success");
				}
			break;
			case 'delete':
				if(Droit("supprimer-utilisateur")->ok()){
					$id = $item["id"];
					if (db::row("SELECT id FROM ¤USERS where id<>$id and type='Administrateur'")) {
						db::query("DELETE FROM ¤USERS where id=$id");
					}else{
						app::apiRep("alert","Suppression impossible !");
					}
				}
			break;
			case 'load':
				$item = db::row("SELECT * FROM ($sql) t where id=".$item["id"]);
			break;
			case 'activation':
				db::save("¤USERS",[
					"id"=>$item["id"],
					"etat"=>$data["args"]?1:0
					]);
			break;
			case "deleteall":
				$ids = "0";
				foreach ($data["data"] as $key => $value) {
					$ids .= ",".$value["id"];
				}
				db::query("DELETE FROM ¤USERS where id in ($ids)");
			break;
		}

		if(!empty($data["item"])){
			return $item;
		}
	}else{
		$sql = "SELECT * FROM ($sql) t order by id DESC";
		$rep = db::pagination($sql,$data);
		foreach ($rep["data"] as $key => $value) {
			if(empty($rep["data"][$key]["data"])){
				$rep["data"][$key]["data"] = json_decode(Droit::json($value["id"]));
			}
		}
		$rep["sql"] = app::encrypt($sql,"sqlquery");
		$rep["print_url"] = "/admin/print/table?s=".app::encrypt($sql,"sqlquery");
		return $rep;
	}
});