<?php

namespace App\Http\Controllers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller
{
	public function __construct()
	{
		$this->middleware('can:admin');
	}

	/**
	 * Add or edit a node
	 */
	public function add_edit(Request $request,User $o)
	{
		if ($request->post()) {
			$this->authorize('admin',$o);

			$request->validate([
				'email' => 'required|email|unique:users,email,'.($o->exists ? $o->id : 0),
				'name' => 'required|min:3',
				'pgp_pubkey' => [
					'nullable',
					'min:64',
					//function ($attribute,$value,$fail) { return $fail('Not this time'); }
				],
				'active' => 'required|boolean',
				'admin' => 'required|boolean',
			]);

			foreach (['name','email','pgp_pubkey','active','admin'] as $key)
				$o->{$key} = $request->post($key);

			if (! $o->exists)
				$o->password = base64_encode(random_bytes(20));

			$o->save();

			if ($o->wasRecentlyCreated)
				event(new Registered($o));

			return redirect()->action([self::class,'home']);
		}

		return view('user.addedit')
			->with('o',$o);
	}

	public function home()
	{
		return view('user.home');
	}
}