<?php
include_once dirname(dirname(__DIR__)) . '/bootstrap/autoload.php';

sanitize();

if (post('name') != null) {
	$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();
		echo 'Created';
	}
	$role = Model::factory(\Incoviba\common\Role::class)->where('description', 'administrador')->findOne();
	if ($role == false) {
		$role = Model::factory(\Incoviba\common\Role::class)->create(['description' => 'administrador']);
		$role->save();
	}
	$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();
	}
	$perm = Model::factory(\Incoviba\common\Permission::class)->where('type', 2)->where('ext_id', $role->id)->where('all', 1)->where('access', 1)->findOne();
	if ($perm == false) {
		$perm = Model::factory(\Incoviba\common\Permission::class)->create([
			'type' => 2,
			'ext_id' => $role->id,
			'all' => 1,
			'access' => 1
		]);
		$perm->save();
	}
	header('Location: next_step.php?step=create_admin');
} else {
	echo view('install.admin');
}
?>
