<?php

namespace app\controllers;

use app\models\Friends;
use lithium\action\DispatchException;
use lithium\security\Auth;

use app\models\User;

class FriendsController extends \lithium\action\Controller {

	public function index() {
		$id = Auth::check('default');
		$id = $id['id'];
		$conditions = array('User.id' => $id);
		$with = array('Friends');
		$user = User::find('first', compact('conditions', 'with'));

		return compact('user');
	}

	public function view() {
		$friend = Friends::first($this->request->id);
		return compact('friend');
	}

	public function add() {
		$friend = Friends::create();
		if ($this->request->data) {
		$user = Auth::check('default');
		$ToUserId = $this->request->data['userid'];

		//If the user exists
		if(User::count($ToUserId) == 1)
		{

			$friendship = Friends::create(array('FromUserId' => $user['id'],
												'ToUserId' => $ToUserId,
												'StatusId' => Friends::status("open"),
												'SentTime' => date('Y-m-d H:i:s', time())));

			$friendship->save();

		}
	}
	return compact('user');
	}

	public function accept() {
		$user == Auth::check('default');
		$id = $this->request->data['id'];

		$relationship = Friends::find($id);

		//Ensure the user is accepting their own request
		if ($relationship->ToUserId == $user->id)
		{
			$relationship->ResponseTime = date('Y-m-d H:i:s', time());
			$relationship->StatusId = Friends::status('accepted');
			$relationship->save();
		}

		//Return them to their friends page (with ajax return the status I guess)
		return $this->redirect("Friendships::view");	
	}
	
	//Copied and pasted the code from above but it really should be handled inside the friendship
	//model;
	public function decline() {
		$user == Auth::check('default');
		$id = $this->request->data['id'];

		$relationship = Friendships::find($id);

		//Ensure the user is accepting their own request
		if ($relationship->ToUserId == $user->id)
		{
			$relationship->ResponseTime = date('Y-m-d H:i:s', time());
			$relationship->StatusId = Friendship::status('rejected');
			$relationship->save();
		}

		//Return them to their friends page (with ajax return the status I guess)
		return $this->redirect("Friendships::view");	
	}

	public function delete() {
		if (!$this->request->is('post') && !$this->request->is('delete')) {
			$msg = "Friends::delete can only be called with http:post or http:delete.";
			throw new DispatchException($msg);
		}
		Friends::find($this->request->id)->delete();
		$this->redirect('Friends::index');
	}
}

?>