<?php

namespace App\Classes\Frame\Action;

use App\User;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;

use App\Classes\Frame\Action;

class Login extends Action
{
	/**
	 * Handle user logins
	 *
	 * @param array $fielddata
	 * @return bool
	 */
	public function handle()
	{
		// First field data element is user, the second is the password
		if (count($this->so->fo->getFieldData()) != 2 OR ! $this->so->fo->getFieldDataId(0) OR ! $this->so->fo->getFieldDataId(1))
		{
			$this->mode = 2; // MODE_FIELD
			// $this->action = 2; // ACTION_GOTO

			$this->so->sendBaseline($this->so->co,RED.'INVALID DETAILS, TRY AGAIN *00');

			return FALSE;
		}

		try {
			$this->uo = User::where('login',$this->so->fo->getFieldDataId(0))->firstOrFail();

		} catch (ModelNotFoundException $e) {
			$this->so->sendBaseline($this->so->co,RED.'USER NOT FOUND, TRY AGAIN *00');

			return FALSE;
		}

		if ($this->uo->password != $this->so->fo->getFieldDataId(1))
		{
			$this->uo = new User;
			$this->so->sendBaseline($this->so->co,RED.'INVALID PASSWORD, TRY AGAIN *00');

			return FALSE;
		}

		$this->so->log('info','User Login: '.$this->uo->name);
		$this->page = ['frame'=>1,'index'=>'a']; // @todo Get from DB.

		$this->action = 2; // ACTION_GOTO
		$this->mode = FALSE;

		return TRUE;
	}
}