<?php 

namespace app\controllers;
use app\models\User;
use app\models\Profile;
use \lithium\security\Auth;

class ProfileController extends \lithium\action\Controller {
	public $publicActions = array("view");

	public function view($username)
	{
		//Find the user profile
		$user = User::find('first', array('conditions' => compact('username')));
		//If the user variable isn't empty a user was found. 
		if (!empty($user))
		{
			
			//The only issue(?) is that this will update the profile views even if the user views their own profile, maybe we should fix that.  
			$user->incrementViews();
		
			$photo = null;
			$profile = $user->profile; 

			$history = Profile::history($user->animelist);
			return compact('user', 'photo', 'profile', 'history');
		}
		else
		{
			//Tell the user that user wasn't found.
		}
	} 

	public function create()
	{
		
	}


	public function edit($username)
	{
		$user = Auth::check('default');
		
		if ($user) {
			$user = User::find('first', array('conditions' => array('username' => $user['username'])));
			$profile = $user->profile;
			$photo;
			

			if (empty($this->request->data)) {
				return compact('profile', 'user');
			}

			//If a photo was uploaded
			if (isset($this->request->data['photo']))
			{
				/* Update / Add the profile picture */
				//Store the image in grid FS
				$photo = Photo::create($this->request->data["photo"]);

				//We don't to resave the photo in the profile data
				unset($this->request->data["photo"]);

				//Save the photo 
				$photo->save();

				//Since images are accessed via /image/mongoid we just store the mongo id so we
				//can substitue it in the <img src=""> tag.
				$user->profilepic = $photo->_id->__toString();
			}

			$user->profile = $this->request->data;
				
			if ($user->save(null, array('validate' =>false))) {
				return $this->redirect("/profile/view/$user->username");
			}
		}
	}
}