<?php
session_start();
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Faceboob\FacebookSDKException;
use Facebook\FacebookCanvasLoginHelper;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;

use Facebook\HttpClients\FacebookHttpable;
use Facebook\HttpClients\FacebookCurl;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\FacebookRedirectLoginHelper;

class FBHomeController extends AppController
{
 

	var $name = 'Facebook';
	var $uses = array('Expense','Participant');
	var $helpers = array('Html', 'Form');
	
 
	public function beforeRender() {
		parent::beforeRender();
	
		$this->layout = 'facebook';
	}
	
	
	
	function index()
	{
		
		
		$app_id = '1539535046303692';
		$app_secret = '0f0e28f812b7c330c57be7ec8024a760';
		$app_namespace = 'expensecount';
		
 		 
		App::import('vendor', 'Facebook'.DS.'Entities'.DS.'AccessToken');
		App::import('vendor', 'Facebook'.DS.'FacebookSession');
		App::import('vendor', 'Facebook'.DS.'FacebookRequest');
		App::import('vendor', 'Facebook'.DS.'FacebookResponse');
		App::import('vendor', 'Facebook'.DS.'FacebookSDKException');
		
		App::import('vendor', 'Facebook'.DS.'Entities'.DS.'SignedRequest');
		
		App::import('vendor', 'Facebook'.DS.'FacebookSignedRequestFromInputHelper');
		App::import('vendor', 'Facebook'.DS.'FacebookRedirectLoginHelper');
		App::import('vendor', 'Facebook'.DS.'FacebookCanvasLoginHelper');
		App::import('vendor', 'Facebook'.DS.'GraphObject');
		App::import('vendor', 'Facebook'.DS.'GraphUser');
		App::import('vendor', 'Facebook'.DS.'GraphSessionInfo');
		
		App::import('vendor', 'Facebook'.DS.'HttpClients'.DS.'FacebookHttpable');
		App::import('vendor', 'Facebook'.DS.'HttpClients'.DS.'FacebookCurl');
		App::import('vendor', 'Facebook'.DS.'HttpClients'.DS.'FacebookCurlHttpClient');
		 
		
		
		 
		
		// Facebook APP keys
		FacebookSession::setDefaultApplication($app_id,$app_secret);
		
		// Helper for fb canvas authentication
		$helper = new FacebookCanvasLoginHelper();
		
		
		
		// see if  $_SESSION exists
		if (isset($_SESSION) && isset($_SESSION['fb_token']))
		{
			// create new fb session from saved fb_token
			$session = new FacebookSession($_SESSION['fb_token']);
		
			// validate the fb_token to make sure it's still valid
			try
			{
				$session->validate();
			}
			catch (Exception $e)
			{
				// catch any exceptions
				$session = null;
			}
		}
		else
		{
			// no $_SESSION exists
			try
			{
				// create fb session
				$session = $helper->getSession();
			}
			catch(FacebookRequestException $ex)
			{
				// When Facebook returns an error
				//print_r($ex);
				$session = null;
			}
			catch(\Exception $ex)
			{
				// When validation fails or other local issues
				//print_r($ex);
				$session = null;
			}
		}
		
		
		
		// check if 1 of the 2 methods above set $session
		if (isset($session))
		{
			$request = new FacebookRequest( $session, 'GET', '/me/friends' );
			try{
		
				$response = $request->execute();
				$graphObject = $response->getGraphObject();
				//echo  print_r( $graphObject, 1 );
				/* $fid = $graphObject->getProperty('id');// echo $fid;
				$femail = $graphObject->getProperty('email')// echo $femail;
				$ffirst_name = $graphObject->getProperty('name ');// echo $ffirst_name; */
				
				//$facebook_id = $graphObject->getProperty('id');
				//$request = new FacebookRequest( $session, 'GET', '/'.$facebook_id.'/friends?access_token='.$session->getToken() );
				
				// $response = $request->execute();
				//$graphObject = $response->getGraphObject();
				
				
				
				
				//var_dump($graphObject);exit;
				
				 
				$expenseIdArray = $this->Participant->getExpenseIdListByFacebookId($facebook_id);
				 
				if(!empty($expenseIdArray)){ 
				 
					 $data = $this->Expense->findExpenseInfoByIds($expenseIdArray);
					 if(!empty($data)){
					 	$expenseList = $data["expenseList"];
					 	$participantList = $data["participantList"];
					 	foreach($expenseList as $key=>$value){
					 		$finalResult[$key]["unique_url"] = $value["Expense"]["unique_url"];
					 		$finalResult[$key]["title"] = $value["Expense"]["title"];
					 		$finalResult[$key]["currency"] = $value["Expense"]["currency"];
					 		$finalResult[$key]["description"] = $value["Expense"]["description"];
					 		$finalResult[$key]["create_date"] = $value["Expense"]["create_date"];
					 		$finalResult[$key]["expense_type"] = $value["Expense"]["expense_type"];
					 		
					 		$finalResult[$key]["participantName"] = $this->getParticipantName($value["Expense"]["id"],$participantList);
					 	}
					 }
					 					 
				}
				
				
				$first_name = $graphObject->getProperty('first_name');
				if(strlen($first_name) > 15){
					$first_name = substr($first_name,0,15);
				}
				
				
				$this->set("expenseList",$finalResult);
				$this->set("facebook_token",$session->getToken());
				$this->set("facebook_name",$first_name);
				//$this->Session->write("aaa",$session->getToken());
				 
				//echo "<br/>";
				//echo "id:".$facebook_id;
				//echo "Session<pre>";
				// print_r($session->getToken());exit;
				//echo "<br/>";
			//	echo "Name:".$graphObject->getProperty('first_name');
				
				
				//echo "<br/>";
				//echo "Email:".$graphObject->getProperty('email');
				
				//get list of expense info based on facebook ID
				
				$this->render('index');
				 
				
				/* echo $fid;
				echo "===========<br/>";
				echo $femail;
				echo "===========<br/>";
				echo $ffirst_name;
				echo "===========<br/>"; */
			} catch (Exception $ex) {
				// echo $ex->getMessage();
		
			}
		
		}
		else
		{
		
			$helper = new FacebookRedirectLoginHelper("https://apps.facebook.com/expensecount");
			$auth_url = $helper->getLoginUrl();
			echo "<script>window.top.location.href='".$auth_url."'</script>";
		
			//session_destroy();
			// We use javascript because of facebook bug https://developers.facebook.com/bugs/722275367815777
			// Fix from here: http://stackoverflow.com/a/23685616/796443
			// IF bug is fixed this line won't be needed, as app will ask for permissions onload without JS redirect.
			//$oauthJS = "window.top.location = 'https://www.facebook.com/dialog/oauth?client_id=$app_id&redirect_uri=https://apps.facebook.com/$app_namespace/&scope=user_location,email';";
		}
		
		
		//App::import('vendor', 'Facebook'.DS.'FacebookRequest');
		/* App::import('vendor', 'Facebook'.DS.'FacebookSDKException');
		App::import('vendor', 'Facebook'.DS.'FacebookRequestException');
		App::import('vendor', 'Facebook'.DS.'GraphObject');
		App::import('vendor', 'Facebook'.DS.'GraphUser');
		
		App::import('vendor', 'Facebook'.DS.'FacebookSession');
		
		//$Facebook = new FacebookSession('942666942429370','d41f9f9dc531dcf2f6de520ca1111a71');
		FacebookSession::setDefaultApplication('942666942429370', 'd41f9f9dc531dcf2f6de520ca1111a71'); */
		//collect facebook data and set it to input form	
		//FacebookSession::setDefaultApplication('', '');
		
		
	/* 	App::import('Vendor', 'FacebookRedirectLoginHelper', array('file' =>'FacebookRedirectLoginHelper.php'));
		App::import('Vendor', 'FacebookSDKException', array('file' =>'FacebookSDKException.php'));
		App::import('Vendor', 'FacebookSession', array('file' => 'FacebookSession.php'));
		App::import('Vendor', 'FacebookRequest', ['file' =>'FacebookRequest.php']);
		App::import('Vendor', 'FacebookRequestException', ['file' =>'FacebookRequestException.php']);
		
		$helper = new \Facebook\FacebookRedirectLoginHelper(Router::url('/', true), "942666942429370", $secret);
		 */
		$data["User"]["name"] = "Rajib Deb";  //fb		 
		$data["User"]["phone"] = "0162005136"; // fb
		$data["User"]["email"] =  "test@gmail.com";//fb 
		
		
		/* if($session) {
		
			try {
		
				$user_profile = (new FacebookRequest(
						$session, 'GET', '/me'
				))->execute()->getGraphObject(GraphUser::className());
		
				echo "Name: " . $user_profile->getName();
		
			}  catch(FacebookRequestException $e) {
		
				echo "Exception occured, code: " . $e->getCode();
				echo " with message: " . $e->getMessage();
		
			}  
		
		} else {
			echo "NO session";
		}
		 */

		$this->request->data = $data;
	
	}
	
	public function getParticipantName($expenseId,$participantList){
		$participantName = "";
		if(!empty($participantList)){
			foreach($participantList as $key=>$value){
				if(trim($value["Participant"]["expense_id"]) == trim($expenseId)){
					$participantName = $value["Participant"]["name"];
				}
			}
		}
		
		return $participantName;
	}
	
	public function createDonor()
	{		 
		$data["name"] = $this->data["User"]["name"];  //fb		
		$data["phone"] = $this->data["User"]["phone"]; // fb
		$data["email"] =  $this->data["User"]["email"];//fb
		$data["bloodgroup"] = $this->data["User"]["bloodgroup"]; //input  // A+=1,B+=2,O+=3,AB+=4,A-=5,B-=6,O-=7,AB-=8
		$data["birth_date"] = $this->data["User"]["birth_date"];
		$data["password"] = ""; //
		$data["from_facebook"] = 1;	
		$data["district"] = $this->data["User"]["district"];
		$data["area"] = $this->data["User"]["district"]; 	
		$data["facebook_profile"] = $this->data["User"]["facebook_profile"];
		$data["last_donate_date"] = $this->data["User"]["last_donate_date"];;
	
		$this->loadModel('User');
			
		$status = $this->User->createUser($data);
		if($status == true){
			echo __("LBL_DATA_SAVED");
			//echo $unique_url;
			//$this->Session->write('Config.language', 'ind');
			//$this->render('index');
		} else {
			echo __("LBL_DATA_INSERTION_FAILED");
		}
	}
	
	 
}
?>