<?php
namespace App\Controller;

use App\Service\DBToModel;
use App\Definition\Controller;
use Incoviba\common\Action;

class Admin
{
	use Controller;

	protected static function setDefault()
	{
		self::$default = view('admin.base');
	}
	public static function models()
	{
		$data = config('databases');
		$databases = array_keys($data);
		return view('admin.models', compact('databases'));
	}
	public static function listModels()
	{
		$db = post('database');
		$modeler = new DBToModel($db);
		echo $modeler->list();
	}
	public static function listNamespaces()
	{
		$base = [
				'Common',
				'Inmobiliaria',
				'Proyecto',
				'Venta'
		];
		$nss = [
				'Incoviba' => [
						'old' => $base,
						'new' => $base
				]
		];

		echo json_encode(['namespaces' => self::collapseMultiArray($nss)]);
	}
	protected static function collapseMultiArray($array, $level = '')
	{
		$output = [];
		foreach ($array as $key => $subarray) {
			if (is_array($subarray)) {
				$output = array_merge($output, self::collapseMultiArray($subarray, $level . '\\' . $key));
			} else {
				$output []= $level . '\\' . $subarray;
			}
		}

		return $output;
	}
	public static function createModel()
	{
		$db = post('database');
		$ns = post('namespace');
		$table = post('table');

		$modeler = new DBToModel($db);
		echo $modeler->create($ns, $table);
	}
	public static function list_roles()
	{
		$roles = \Model::factory(\Incoviba\common\Role::class)->findMany();
		echo view('admin.roles.list', compact('roles'));
	}
	public static function add_role()
	{
		echo view('admin.roles.add');
	}
	public static function do_add_role()
	{
		$role = \Model::factory(\Incoviba\common\Role::class)->where('description', post('description'))->findOne();
		if ($role === false) {
			$role = \Model::factory(\Incoviba\common\Role::class)->create(['description' => post('description')]);
			$role->save();
		}
		header('Location: ' . nUrl('admin', 'add_role'));
	}
	public static function role()
	{
		$role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role'));
		$actions = model(Action::class)->orderByAsc('description')->findMany();
    $permissions = [];
    foreach ($actions as $action) {
      $permissions []= (object) ['description' => $action->description, 'status' => false, 'inherited' => false];
    }
    array_walk($permissions, function(&$el, $i, $role) {
      if ($role->checkAccess($el->description)) {
        $el->status = true;
        if ($role->isInherited($el->description)) {
          $el->inherited = true;
        }
      }
    }, $role);
		echo view('admin.roles.show', compact('role', 'permissions'));
	}
	public static function add_role_permissions()
	{
		$role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role'));
		$locations = \Model::factory(\Incoviba\common\Location::class)->findMany();
		$actions = model(\Incoviba\common\Action::class)->findMany();
		echo view('admin.roles.add_permissions', compact('role', 'locations', 'actions'));
	}
	public static function do_add_role_permissions()
	{
		$role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role'));
		$actions = model(\Incoviba\common\Action::class)->findMany();
		foreach ($actions as $action) {
			$p = \Model::factory(\Incoviba\common\Permission::class)->where('type', 2)->where('ext_id', $role->id)->where('action_id', $action->id)->findOne();
			if (array_search($action->id, post('allowed'))) {
				if (!$p) {
					$data = [
						'type' => 2,
						'ext_id' => $role->id,
						'action_id' => $action->id
					];
					$p = model(\Incoviba\common\Permission::class)->create($data);
				}
				$p->status = 1;
			} else {
				if ($p !== false) {
					$p->status = 0;
				}
			}
			if ($p !== false) {
				$p->save();
			}
		}
		header('Location: ' . nUrl('admin', 'role', ['role' => $role->id]));
	}
	public static function list_users()
	{
		$users = \Model::factory(\Incoviba\common\User::class)->orderByAsc('name')->findMany();
		echo view('admin.users.list', compact('users'));
	}
	public static function add_user()
	{
		echo view('admin.users.add');
	}
	public static function do_add_user()
	{
		$user = \Model::factory(\Incoviba\common\User::class)->where('name', post('name'))->findOne();
		if ($user === false) {
			$user = \Model::factory(\Incoviba\common\User::class)->create();
			$user->name = post('name');
			$user->password(post('password'));

			$user->save();
		}
		header('Location: ' . url('', ['p' => 'admin', 'a' => 'add_user']));
	}
	public static function user()
	{
		$user = \Model::factory(\Incoviba\common\User::class)->findOne(get('user'));
		echo view('admin.users.show', compact('user'));
	}
	public static function add_user_role()
	{
		if (get('user') !== false) {
			$user = \Model::factory(\Incoviba\common\User::class)->findOne(get('user'));
			$roles = \Model::factory(\Incoviba\common\Role::class)->findMany();
			return view('admin.users.add_role', compact('user', 'roles'));
		} elseif (get('role') !== false) {
			$role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role'));
			$users = \Model::factory(\Incoviba\common\User::class)->findMany();
			return view('admin.roles.add_users', compact('users', 'role'));
		}
	}
	public static function do_add_user_role()
	{
		if (get('user') !== false) {
			$user = \Model::factory(\Incoviba\common\User::class)->findOne(get('user'));
			foreach (post('role') as $r_id) {
				$role = \Model::factory(\Incoviba\common\Role::class)->findOne($r_id);

				$usrRl = \Model::factory(\Incoviba\common\UserRole::class)->where('user', $user->id)->where('role', $role->id)->findOne();
				if ($usrRl === false) {
					$usrRl = \Model::factory(\Incoviba\common\UserRole::class)->create(['user' => $user->id, 'role' => $role->id]);
					$usrRl->save();
				}
			}
			header('Location: ' . url('', ['p' => 'admin', 'a' => 'user', 'user' => $user->id]));
		} elseif (get('role') !== false) {
			$role = \Model::factory(\Incoviba\common\Role::class)->findOne(get('role'));
			foreach (post('users') as $u_id) {
				$user = \Model::factory(\Incoviba\common\User::class)->findOne($u_id);

				$usrRl = \Model::factory(\Incoviba\common\UserRole::class)->where('user', $user->id)->where('role', $role->id)->findOne();
				if ($usrRl === false) {
					$usrRl = \Model::factory(\Incoviba\common\UserRole::class)->create(['user' => $user->id, 'role' => $role->id]);
					$usrRl->save();
				}
			}
			header('Location: ' . url('', ['p' => 'admin', 'a' => 'role', 'role' => $role->id]));
		}
	}
	public static function remove_user_role()
	{
		$q = "DELETE FROM user_roles WHERE user = ? AND role = ?";
		$st = \ORM::getDb()->prepare($q);
		$st->execute([get('user'), get('role')]);
		header('Location: ' . nUrl('admin'));
	}
	public static function delete_user()
	{
		$q = "DELETE FROM user_roles WHERE user = ?";
		$st = \ORM::getDb()->prepare($q);
		$st->execute([get('user')]);
		$q = "DELETE FROM logins WHERE user = ?";
		$st = \ORM::getDb()->prepare($q);
		$st->execute([get('user')]);
		$q = "DELETE FROM permissions WHERE type = 1 AND ext_id = ?";
		$st = \ORM::getDb()->prepare($q);
		$st->execute([get('user')]);
		$user = \model(\Incoviba\common\User::class)->findOne(get('user'));
		$user->delete();
		header('Location: ' . nUrl('admin', 'list_users'));
	}
	public static function reset_user()
	{
		$user = model(\Incoviba\common\User::class)->findOne(get('user'));
		$user->password('123456');
		$user->save();
		header('Location: ' . nUrl('admin', 'user', ['user' => $user->id]));
	}
}
?>
