<?php 
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');

if (!Schema::hasTable($tableNames['permissions'])) { 
	Schema::create($tableNames['permissions'], function ($table) {
	    $table->increments('id');
	    $table->string('name');
	    $table->string('guard_name');
	    $table->timestamps();
	});
}

if (!Schema::hasTable($tableNames['roles'])) { 
	Schema::create($tableNames['roles'], function ($table) {
	    $table->increments('id');
	    $table->string('name');
	    $table->string('guard_name');
	    $table->timestamps();
	});
	$roles = array('administrador','usuario');
	for ($i=0; $i <count($roles) ; $i++) { 
		 DB::table($tableNames['roles'])->insert([
	        'name' => $roles[$i],
	        'guard_name' => 'web',
    	]);
	}
}
if (!Schema::hasTable($tableNames['model_has_permissions'])) {
	Schema::create($tableNames['model_has_permissions'], function ($table) use ($tableNames, $columnNames) {
	    $table->unsignedInteger('permission_id');

	    $table->string('model_type');
	    $table->unsignedBigInteger($columnNames['model_morph_key']);
	    $table->index([$columnNames['model_morph_key'], 'model_type', ]);

	    $table->foreign('permission_id')
	        ->references('id')
	        ->on($tableNames['permissions'])
	        ->onDelete('cascade');

	    $table->primary(['permission_id', $columnNames['model_morph_key'], 'model_type'],
	            'model_has_permissions_permission_model_type_primary');
	});
}

if (!Schema::hasTable($tableNames['model_has_roles'])) {
	Schema::create($tableNames['model_has_roles'], function ($table) use ($tableNames, $columnNames) {
	    $table->unsignedInteger('role_id');

	    $table->string('model_type');
	    $table->unsignedBigInteger($columnNames['model_morph_key']);
	    $table->index([$columnNames['model_morph_key'], 'model_type', ]);

	    $table->foreign('role_id')
	        ->references('id')
	        ->on($tableNames['roles'])
	        ->onDelete('cascade');

	    $table->primary(['role_id', $columnNames['model_morph_key'], 'model_type'],
	            'model_has_roles_role_model_type_primary');
	});
}
if (!Schema::hasTable($tableNames['role_has_permissions'])) {
	Schema::create($tableNames['role_has_permissions'], function ($table) use ($tableNames) {
	    $table->unsignedInteger('permission_id');
	    $table->unsignedInteger('role_id');

	    $table->foreign('permission_id')
	        ->references('id')
	        ->on($tableNames['permissions'])
	        ->onDelete('cascade');

	    $table->foreign('role_id')
	        ->references('id')
	        ->on($tableNames['roles'])
	        ->onDelete('cascade');

	    $table->primary(['permission_id', 'role_id']);
	});
}
app('cache')
    ->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
    ->forget(config('permission.cache.key'));

?>
