<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\System;

class SystemController extends Controller
{
	public function __construct()
	{
		$this->middleware('auth');
	}

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

			$request->validate([
				'name' => 'required|min:3|unique:systems,name,'.($o->exists ? $o->id : 0),
				'location' => 'required|min:3',
				'sysop' => 'required|min:3',
				'address' => 'nullable|regex:/^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){1,127}(?![0-9]*$)[a-z0-9-]+\.?)$/i',
				'port' => 'nullable|digits_between:2,5',
				'active' => 'required|boolean',
			]);

			foreach (['name','location','sysop','address','port','active','method','notes'] as $key)
				$o->{$key} = $request->post($key);

			$o->save();

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

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

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