<?php

/**
 * Show All user / Show Detail (if user id is present)
 */
Slim::get('/admin/user/list(/:id)',function($id = 0) {
	User::check_login('admin');
	//User::check_permit('edit','user');
	
	if ($id == 0) {
		$current_page = (isset($_GET['p']) ? $_GET['p'] : 1);
		$count_per_page = 30;
		
		if (isset($_GET["find"])) $find = $_GET["find"];
		else $find = "";
		
		$data = User::getAll($current_page,$count_per_page,$find);
		$page = User::generatePage($current_page,$count_per_page,Slim::urlfor("admin_user"),$find);
		
		Slim::render('admin/user/list.html',array(
			'page' => $page,
			'data' => $data,
			"find" => (isset($_GET['find']) ? $_GET['find'] : "")

		));
	} else {
		$data = User::get($id);
		Slim::render('admin/user/view.html',array(
			"data" => $data
		));
	}
})->name('admin_user');

/**
 * New user
 */
Slim::get('/admin/user/new/',function() {
	User::check_login('admin');
	//User::check_permit('edit','user');

	$columns = User::getColumns();
	$store = Store::getAll(1,999);

	Slim::render("admin/user/new.html",array(
		"columns"=>$columns,
		"stores"=>$store
	));
})->name('admin_user_new');

Slim::post('/admin/user/new/',function() {
	User::check_login('admin');
	//User::check_permit('edit','user');

	$data = $_POST;
	
	if (User::create($data)) {
		redir_by_id("admin_user");
	} else {
		Slim::render('admin/user/new.html',array(
			"data" => $_POST
		));
	}
});

/**
 * Edit user
 */
Slim::get('/admin/user/edit(/:id)',function($id = 0) {
	User::check_login('admin');
	//User::check_permit('edit','user');

	if ($id == 0) redir_by_id("admin_user");
	$access = array();
	$data = User::get($id);
	$store = Store::getAll(1,999);

	$users = User::editUserPermit($_SESSION['user']['edit']);
	Slim::render('admin/user/edit.html',array(
		"data" => $data,
		"stores"=>$store
	));
})->name('admin_user_edit'); 

Slim::post('/admin/user/edit(/:id)',function($id = 0) {
	User::check_login('admin');
	//User::check_permit('edit','user');

	if ($id == 0) redir_by_id('admin_user');
	$data = $_POST;
	if (User::update($id,$data)) {
		redir_by_id('admin_user');
	} else {
		Slim::render('admin/user/edit.html',array(
			"data" => $_POST
		));
	}
});

/**
 * Delete user
 */
Slim::get('/admin/user/del(/:id)',function($id = 0) {
	User::check_login('admin');
	//User::check_permit('edit','user');

	if ($id == 0) redir_by_id('admin_user');
	
	User::remove($id);
	redir_by_id('admin_user');
})->name('admin_user_del');
