<?php

namespace App\Http\Controllers;

use App\Models\Filearea;
use Illuminate\Http\Request;

class FileareaController extends Controller
{
	/**
	 * Add or edit a echoarea
	 */
	public function add_edit(Request $request,Filearea $o)
	{
		if ($request->post()) {
			$this->authorize('admin',$o);

			$request->validate([
				'domain_id' => 'required|exists:domains,id',
				'name' => 'required|min:4|max:35|regex:/^[a-zA-Z-_~]{4,}$/|unique:fileareas,name,'.($o->exists ? $o->id : 0),
				'description' => 'required',
				'active' => 'required|boolean',
				'show' => 'required|boolean',
				'nodelist' => 'nullable|string|max:12',
				'sec_read' => 'required|integer|min:0|max:7',
				'sec_write' => 'required|integer|min:0|max:7',
			]);

			foreach (['name','description','active','show','notes','domain_id'] as $key)
				$o->{$key} = $request->post($key);

			$o->setRead($request->post('sec_read'));
			$o->setWrite($request->post('sec_write'));

			$o->save();

			if ($request->post('nodelist')) {
				$o->domain->nodelist_filename = $request->post('nodelist');
				$o->domain->nodelist_filearea_id = $o->id;
				$o->domain->save();
			}

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

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

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