<?php
namespace Controllers;
// Контроллер групп пользователей
class Usergroups extends Controller {

	public function __construct() {
		parent::__construct();
		$this->model=new \Models\Usergroups($this->db, $this->f3);
	}

	function directory() {
		$groups=$this->model->select_groups(null, array('order'=>'title'));
		$this->f3->set('data', $groups);
		$this->f3->set('page_data', $this->model->page_data('directory'));
	}

	function form() {
		$id=$this->f3->get('GET.id');
		$data=array();
		$inc='add';
		if($id>0) {
			$data=$this->model->select_groups(array('id=?', $id), array('limit'=>1));
			if(!$data) {
				$this->f3->set('page_data', $this->messages->message('not_found'));
				return;
			}
			$inc='change';
		}
		$this->f3->set('modules', $this->model->modules);
		$this->f3->set('data', $data[0]);
		$this->f3->set('page_data', $this->model->page_data($inc));
	}

	function post_form() {
		$post=$this->f3->get('POST');
		if($post['id'])$action='change';
		else $action='add';
		$res=$this->model->save_group($post, $action);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function delete() {
		$id=$this->f3->get('GET.id');
		$users=$this->users->select_users(array('group_id=?', $id));
		if($users) {
			$res=array(
				'success'=>false,
				'txt'=>'usergroups_can_not_delete'
			);
		}
		else {
			$res=$this->model->delete($id);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}
}
