<?php

namespace App\Http\Controllers;

use Illuminate\Http\RedirectResponse;

use App\Http\Requests\SiteEdit;
use App\Models\SiteDetail;

/**
 * The AdminController governs all routes that are prefixed with 'a/'.
 *
 * This is everything about the configuration of the application as a whole, or administration of a site.
 */
class AdminController extends Controller
{
	/**
	 * Site setup
	 *
	 * @note This method is protected by the routes
	 * @param SiteEdit $request
	 * @return RedirectResponse
	 */
	public function setup(SiteEdit $request)
	{
		$site = config('site');
		$images = ['site_logo','email_logo'];
		$validated = collect($request->validated());

		// Handle the images
		foreach($images as $key)
			if ($x=$request->validated($key))
				$validated->put($key,$x->storeAs('site/'.$site->site_id,$x->getClientOriginalName(),'public'));

		foreach ($site->details as $oo)
			if ($validated->has($oo->key)) {
				// Dont set the following keys to null if they are null
				if (in_array($oo->key,$images) && is_null($validated->get($oo->key)))
					continue;

				$oo->value = $validated->get($oo->key) ?: '';
				$oo->save();

				$validated->forget($oo->key);
			}

		// Left over values to be created.
		foreach ($validated as $k=>$v) {
			$oo = new SiteDetail;
			$oo->key = $k;
			$oo->value = $v ?: '';

			$site->details()->save($oo);
		}

		return redirect()
			->back()
			->with('success','Settings saved');
	}
}