<?php
require_once 'corex/autoload.php';

$user = new User();

if (!$user->isLoggedIn()) {
	Redirect::to('index/php');
}

if (Form::exists()) {
	if (Token::check(Form::data('token'))) {
		
		$validate = new Validate();
		$validation = $validate->check($_POST, array(
			'name' => array(
				'required' => true,
				'min' => 2,
				'max' => 50
			)
		));

		if ($validation->passed()) {
			
			try{
				$user->update(array(
					'name' => Form::data('name')
				));
				Session::flash('home', 'Your details have been updated!');
				Redirect::to('index.php');
			} catch(Exception $e){
				die($e->getMessage());
			}

		} else {
			foreach ($validation->errors() as $error) {
				echo $error;
				echo '<br/>';
			}
		}
	}
}
?>

<form action="" method="POST">
	<div class="field">
		<label for="name">Name</label>
		<input type="text" name="name" value="<?php echo $user->data()->name; ?>">
	</div>
	<input type="submit" name="Update">
	<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
</form>