<?php
class HomeController extends AppController
{

	var $name = 'Homes';
	public $uses = array('Expense', 'TempExpenseEmail','AccessInfo');
	var $helpers = array('Html', 'Form');

	public $components = array('RequestHandler', 'Captcha');

    private $user_id;
	public function initialize()
	{
		$this->setDefaultTimeStamp();
	}


	public function beforeRender()
	{
		parent::beforeRender();

		$this->layout = 'visitor';
		if ($this->Session->check("homecontroller_layout")) {
			//$this->layout = '';
			$this->Session->delete("homecontroller_layout");
		}

	}

	/* public function beforeFilter() {
        parent::beforeFilter();
        $this->Cookie->name = 'Expenses';
        $this->Cookie->time = 3600;  // or '1 hour'
        $this->Cookie->path = '/Home/createGroupExpense';
        $this->Cookie->domain = 'localhost';
        $this->Cookie->secure = true;  // i.e. only sent if using secure HTTPS
        $this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
        $this->Cookie->httpOnly = true;
        $this->Cookie->type('aes');
    }*/

	function index() {}

	function track()
	{
		/*$unique_url = $this->Session->read("user_unique_url");
	    $expense_title = $this->Session->read("user_expense_title");
	    
	    $this->set('unique_url',$unique_url);
	    $this->set('expense_title',$expense_title);*/
	}


	public function changeLanguage($lang = null)
	{


		$language = $this->data["Home"]["global_selected_language"];

		if (empty($language)) {
			$language = $lang;
		}

		$url = $this->data["Home"]["global_current_url"];



		if (empty($url)) {
			$url = $this->webroot;
		}

		$language = trim($language);
		$allowedLanguage = array("eng", "ben", "jpn", "hin", "may", "chi", "rus", "urd", "spa", "ccn", "czh", "ben");

		if (!in_array($language, $allowedLanguage)) {
			$language = "eng";
		}

		$this->Session->write("Config.language", $language);
		$this->Cookie->write("Config.expcount.language", $language);

		$this->redirect(FULL_BASE_URL . $url);
		exit;
	}

	private function getSecretKey($length = 10)
	{

		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}

		return $randomString;
	}


	public function createGroupExpense($token = "", $name = "")
	{
        $this->user_id = $this->Session->read('userData.id');
        $profile_id =  $this->Session->read('userData.profile_id');
		if ((isset($token) && trim($token) != "")
			&& (isset($name) && trim($name) != "")
		) {

			if (strlen($name) > 15) {
				$name = substr($name, 0, 15);
			}

			//validate token;if token is valid, just set a session for facebook layout.
			$this->Session->write("homecontroller_layout", "facebook");
			$this->set("facebook_token", $token);
			$this->set("facebook_name", $name);
		}

		if ($this->request->is('ajax')) {
			Configure::write('debug', 0);

			$this->Expense->setGroupExpenseValidation();
			$this->Expense->set($this->data);

			if ($this->Expense->validates()) {
				echo Configure::read('expensecount.form.validation.success');
			} else {
				$errorMsg = "";
				$errorMsgArray =  $this->Expense->invalidFields();

				foreach ($errorMsgArray as $key => $value) {
					$errorMsg .= $key . Configure::read('expensecount.form.validation.pipe') . $value[0] . Configure::read('expensecount.form.validation.separator');
				}
				echo $errorMsg;
			}
			exit;
		}
        else if ($this->request->is('Post') && $this->data["Expense"]) {

			$captcha = $this->Session->read('captcha_code');
			if (strlen($captcha) > 0 && ($captcha == $this->request->data['Expense']['captcha'])) {
				$this->Session->delete('captcha_code');
				$this->Expense->setGroupExpenseValidation();
				$this->Expense->set($this->data);
				if ($this->Expense->validates()) {
					$data["title"] = $this->data["Expense"]["title"];
					$data["your_name"] = $this->data["Expense"]["YourName"];
					$data["participants"] = $this->data["Expense"]["participants"];
					$data["email"] = $this->data["Expense"]["emails"];
					$data["currency"] = $this->data["Expense"]["currency"];
					$data["description"] = $this->data["Expense"]["description"];
					$data["language"] = Configure::read('Config.language');
                    if(!empty($profile_id)){
                        $data['create_user'] = $profile_id;
                    }
					if (isset($this->data["Expense"]["createDate"])) {
						$data["create_date"] = $this->data["Expense"]["createDate"];
					} else {
						$data["create_date"] = $this->getSystemCurrentTimeStamp();
					}

					$data["expense_type"] = "1";
					$data["source"] = "1";

					$data["ip"] = $this->getClientIp();
					$data["user_agent"] = $this->getUserAgent();

					$data["secret_key"] = $this->data["Expense"]["captcha"];
                    $data['user_id'] = $this->user_id;
					$this->loadModel('Expense');

					$expenseIdStr = $this->Expense->createExpense($data, false);
					if ($expenseIdStr != "") {

						$expenseIdStrArr = explode(",", $expenseIdStr);
						$unique_url = $expenseIdStrArr[1];
						// data for userGroup
                        if (!empty($this->user_id)) {
							$userGrpdata['user_id'] = $this->user_id;
							$userGrpdata['unique_url'] = $unique_url;
							$userGrpdata['participant_id'] = '1' . '_0'; // creator id
							$userGrpdata['skip_process_validation'] = 1;
                            $this->addGroupSetting(['unique_url'=>$unique_url,'is_restricted_mode'=>$this->data["Expense"]['restrictedMode'], 'expense_id'=>$expenseIdStrArr[0]]);
                            $this->addPermission( [
                                'expense_id' => $expenseIdStrArr[0],
                                'unique_url' => $unique_url,
                                'profile_id' => $profile_id,
                                'user_id' => $this->user_id,
                                "role"  => OWNER
                            ]);
							//add userGroup
							$this->callAPI(HTTP_SITE_URL . "/users/groupadd.json", 'POST', json_encode($userGrpdata));
						}
						//set cookie for my expenses
                        if(empty($profile_id) && empty($this->user_id)){
                            $this->setCookie($data, $unique_url);
                        }

						$tmp_email = trim($this->data["Expense"]["emails"]);
						if (!empty($tmp_email)) {
							$this->Session->write('just_created_email', $tmp_email);
						}

						$this->Session->write('just_created', "yes");

						$this->redirect(array('controller' => $unique_url));
					} else {
						$this->Session->setFlash(__('DATA_CREATION_FAIL'));
					}
				} else {
					$this->Session->setFlash(__('CAPTCHA_NOT_EMPTY_MAX_CHAR'));
				}
			}
		} else {
			$token = $this->getSecretKey(5);
			$this->set("captcha", $token);
			$this->Session->write("captcha_code", $token);
            $this->setPermission();
		}
	}


	public function createMessExpense($token = "", $name = "")
	{
        $this->user_id = $this->Session->read('userData.id');
        $profile_id =  $this->Session->read('userData.profile_id');
		if ((isset($token) && trim($token) != "") && (isset($name) && trim($name) != "")) {
			if (strlen($name) > 15) {
				$name = substr($name, 0, 15);
			}

			//validate token;if token is valid, just set a session for facebook layout.
			$this->Session->write("homecontroller_layout", "facebook");
			$this->set("facebook_token", $token);
			$this->set("facebook_name", $name);
		}

		if ($this->request->is('ajax')) {
			Configure::write('debug', 0);

			$this->Expense->setGroupExpenseValidation();
			$this->Expense->set($this->data);

			if ($this->Expense->validates()) {
				echo Configure::read('expensecount.form.validation.success');
			} else {
				$errorMsg = "";
				$errorMsgArray =  $this->Expense->invalidFields();

				foreach ($errorMsgArray as $key => $value) {
					$errorMsg .= $key . Configure::read('expensecount.form.validation.pipe') . $value[0] . Configure::read('expensecount.form.validation.separator');
				}
				echo $errorMsg;
			}
			exit;
		}
        else if ($this->request->is('Post') && $this->data["Expense"]) {

			$captcha = $this->Session->read('captcha_code');
			if (strlen($captcha) > 0 && ($captcha == $this->request->data['Expense']['captcha'])) {

				$this->Session->delete('captcha_code');
				$this->Expense->setGroupExpenseValidation();
				$this->Expense->set($this->data);
				if ($this->Expense->validates()) {
					$data["title"] = $this->data["Expense"]["title"];
					$data["your_name"] = $this->data["Expense"]["YourName"];
					$data["participants"] = $this->data["Expense"]["participants"];
					$data["email"] = $this->data["Expense"]["emails"];
					$data["currency"] = $this->data["Expense"]["currency"];
					$data["description"] = $this->data["Expense"]["description"];
					$data["language"] = Configure::read('Config.language');

                    if(!empty($profile_id)){
                        $data['create_user'] = $profile_id;
                    }

					if (isset($this->data["Expense"]["createDate"])) {
						$data["create_date"] = $this->data["Expense"]["createDate"];
					} else {
						$data["create_date"] = $this->getSystemCurrentTimeStamp();
					}

					$data["expense_type"] = "2";
					$data["source"] = "1";
					$data["ip"] = $this->getClientIp();
					$data["user_agent"] = $this->getUserAgent();

					$data["secret_key"] = $this->data["Expense"]["captcha"];
                    $data['user_id'] = $this->user_id;
					$this->loadModel('Expense');

					$expenseIdStr = $this->Expense->createExpense($data, false);

					if ($expenseIdStr != "") {
						$expenseIdStrArr = explode(",", $expenseIdStr);
						$unique_url = $expenseIdStrArr[1];

						// data for userGroup
						if (!empty($this->user_id)) {
							$userGrpdata['user_id'] = $this->user_id;
							$userGrpdata['unique_url'] = $unique_url;
							$userGrpdata['participant_id'] = '1' . '_0'; // creator id
							$userGrpdata['skip_process_validation'] = 1;
                            $this->addGroupSetting(['unique_url'=>$unique_url,'is_restricted_mode'=>$this->data["Expense"]['restrictedMode'], 'expense_id'=>$expenseIdStrArr[0]]);
                            $this->addPermission( [
                                'expense_id' => $expenseIdStrArr[0],
                                'unique_url' => $unique_url,
                                'profile_id' => $profile_id,
                                'user_id' => $this->user_id,
                                "role"  => OWNER
                            ]);
                            //add userGroup
							$this->callAPI(HTTP_SITE_URL . "/users/groupadd.json", 'POST', json_encode($userGrpdata));
						}

						//set cookie for my expenses
                        if(empty($profile_id) && empty($this->user_id)){
                            $this->setCookie($data, $unique_url);
                        }

						$tmp_email = trim($this->data["Expense"]["emails"]);
						if (!empty($tmp_email)) {
							$this->Session->write('just_created_email', $tmp_email);
						}

						$this->Session->write('just_created', "yes");
						$this->redirect(array('controller' => $unique_url));
					} else {
						$this->Session->setFlash(__('DATA_CREATION_FAIL'));
					}
				} else {
					$this->Session->setFlash(__('CAPTCHA_NOT_EMPTY_MAX_CHAR'));
				}
			}
		} else {
			$token = $this->getSecretKey(5);
			$this->set("captcha", $token);
			$this->Session->write("captcha_code", $token);
            $this->setPermission();
		}
	}


	public function createFamilyExpense($token = "", $name = "")
	{
        $this->user_id = $this->Session->read('userData.id');
        $profile_id =  $this->Session->read('userData.profile_id');
		if ((isset($token) && trim($token) != "")
			&& (isset($name) && trim($name) != "")
		) {

			if (strlen($name) > 15) {
				$name = substr($name, 0, 15);
			}

			//validate token;if token is valid, just set a session for facebook layout.
			$this->Session->write("homecontroller_layout", "facebook");
			$this->set("facebook_token", $token);
			$this->set("facebook_name", $name);
		}

		if ($this->request->is('ajax')) {
			Configure::write('debug', 0);

			$this->Expense->setFamilyExpenseValidation();
			$this->Expense->set($this->data);

			if ($this->Expense->validates()) {
				echo Configure::read('expensecount.form.validation.success');
			} else {
				$errorMsg = "";
				$errorMsgArray =  $this->Expense->invalidFields();

				foreach ($errorMsgArray as $key => $value) {
					$errorMsg .= $key . Configure::read('expensecount.form.validation.pipe') . $value[0] . Configure::read('expensecount.form.validation.separator');
				}
				echo $errorMsg;
			}
			exit;
		} else if ($this->request->is('Post') && $this->data["Expense"]) {
			$captcha = $this->Session->read('captcha_code');
			if (strlen($captcha) > 0 && ($captcha == $this->request->data['Expense']['captcha'])) {
				$this->Session->delete('captcha_code');
				$this->Expense->setFamilyExpenseValidation();
				$this->Expense->set($this->data);
				if ($this->Expense->validates()) {

					$data["title"] = $this->data["Expense"]["title"];
					$data["currency"] = $this->data["Expense"]["currency"];
					$data["description"] = $this->data["Expense"]["description"];
					$data["language"] = Configure::read('Config.language');
					$data["email"] = $this->data["Expense"]["emails"];
                    if(!empty($profile_id)){
                        $data['create_user'] = $profile_id;
                    }
					if (isset($this->data["Expense"]["createDate"])) {
						$data["create_date"] = $this->data["Expense"]["createDate"];
					} else {
						$data["create_date"] = $this->getSystemCurrentTimeStamp();
					}

					$data["expense_type"] = "3"; //1=group expense,2=mess expense,3=family expense
					$data["source"] = "1";
					$data["ip"] = $this->getClientIp();
					$data["user_agent"] = $this->getUserAgent();

					$data["secret_key"] = $this->data["Expense"]["captcha"];
                    $data['user_id'] = $this->user_id;
					$this->loadModel('Expense');

					$expenseIdStr = $this->Expense->createExpense($data, false);

					if ($expenseIdStr != "") {
						$expenseIdStrArr = explode(",", $expenseIdStr);
						$unique_url = $expenseIdStrArr[1];
						// data for userGroup
						if (!empty($this->user_id)) {
							$userGrpdata['user_id'] = $this->user_id;
							$userGrpdata['unique_url'] = $unique_url;
							$userGrpdata['participant_id'] = '1' . '_0';
							$userGrpdata['skip_process_validation'] = 1;
                            $this->addGroupSetting(['unique_url'=>$unique_url,'is_restricted_mode'=>$this->data["Expense"]['restrictedMode'], 'expense_id'=>$expenseIdStrArr[0]]);
                            $this->addPermission( [
                                'expense_id' => $expenseIdStrArr[0],
                                'unique_url' => $unique_url,
                                'profile_id' => $profile_id,
                                'user_id' => $this->user_id,
                                "role"  => OWNER
                            ]);
                            //add userGroup
							$this->callAPI(HTTP_SITE_URL . "/users/groupadd.json", 'POST', json_encode($userGrpdata));
						}

						//set cookie for my expenses
                        if(empty($profile_id) && empty($this->user_id)) {
                            $this->setCookie($data, $unique_url);
                        }

						$tmp_email = trim($this->data["Expense"]["emails"]);
						if (!empty($tmp_email)) {
							$this->Session->write('just_created_email', $tmp_email);
						}

						$this->Session->write('just_created', "yes");
						$this->redirect(array('controller' => $unique_url));
					} else {
						$this->Session->setFlash(__('DATA_CREATION_FAIL'));
					}
				} else {
					$this->Session->setFlash(__('CAPTCHA_NOT_EMPTY_MAX_CHAR'));
				}
			}
		} else {
			$token = $this->getSecretKey(5);
			$this->set("captcha", $token);
			$this->Session->write("captcha_code", $token);
            $this->setPermission();
		}
	}

	public function groupExpense() {}


	public function messExpense() {}


	public function familyExpense() {}


	public function updateGroupExpense()
	{


		if ($this->request->is('ajax')) {
			Configure::write('debug', 0);

			$this->Expense->setGroupExpenseModifyValidation();

			$this->Expense->set($this->data);


			if ($this->Expense->validates()) {

				//					$fp = fopen("ajit.txt",'a+');
				//		 fwrite($fp,json_encode($this->data['unique_url']));
				//		 fclose($fp);

				$data["id"] = $this->data["Expense"]["expenseid"];
				$data["title"] = $this->data["Expense"]["title"];
				$data["currency"] = $this->data["Expense"]["currency"];
				$data["description"] = $this->data["Expense"]["description"];
				$data["version"] = $this->data["Expense"]["version"];
				//$data["expenseType"] = $this->data["Expense"]["expenseType"];

				if (
					isset($this->data["Expense"]["defaultBreakfast"])
					&& isset($this->data["Expense"]["defaultLunch"])
					&& isset($this->data["Expense"]["defaultDinner"])
				) {

					$defaultBreakfast = 0;
					$defaultLunch = 0;
					$defaultDinner = 0;

					if (trim($this->data["Expense"]["defaultBreakfast"]) != "") {
						$defaultBreakfast = trim($this->data["Expense"]["defaultBreakfast"]);
					}

					if (trim($this->data["Expense"]["defaultLunch"]) != "") {
						$defaultLunch = trim($this->data["Expense"]["defaultLunch"]);
					}

					if (trim($this->data["Expense"]["defaultDinner"]) != "") {
						$defaultDinner = trim($this->data["Expense"]["defaultDinner"]);
					}


					$data["default_meal"] = $defaultBreakfast . "|" . $defaultLunch . "|" . $defaultDinner;
				}


				if ($data["version"] > 999) {
					$data["version"] = 1;
				}

				$message = $this->Expense->modifyExpense($data);

                //insert/update access info
                $access_info["id"] = $this->data["Expense"]["expenseid"];
                $access_info["unique_url"] = $this->data["unique_url"];
                $this->insertAccessInfo($access_info);

				//set cookie for my expenses
				$curExpInfo = $this->Expense->findById($this->data["Expense"]["expenseid"]);
				$dataCookie["title"] = $this->data["Expense"]["title"];
				$dataCookie["create_date"] = $curExpInfo["Expense"]["create_date"];
				$this->setCookie($dataCookie, $this->data['unique_url'], 1);

				//update firebase version
				$this->updateFirebase($this->data['unique_url']);

				if (empty($message)) {
					echo Configure::read('expensecount.form.validation.success');
				} else {
					$errorMsg = "";
					foreach ($message as $key => $value) {
						$errorMsg .= $key . Configure::read('expensecount.form.validation.pipe') . $value . Configure::read('expensecount.form.validation.separator');
					}
					echo $errorMsg;
				}
			} else {

				$errorMsg = "";
				$errorMsgArray =  $this->Expense->invalidFields();

				foreach ($errorMsgArray as $key => $value) {
					$errorMsg .= $key . Configure::read('expensecount.form.validation.pipe') . $value[0] . Configure::read('expensecount.form.validation.separator');
				}

				echo $errorMsg;
			}

			exit;
		}
		exit;
	}






	public function get_captcha()
	{
		$this->autoRender = false;
		App::import('Component', 'Captcha');

		//generate random charcters for captcha
		$random = mt_rand(100, 99999);

		//save characters in session
		$this->Session->write('captcha_code', $random);

		$settings = array(
			'characters' => $random,
			'winHeight' => 70,         // captcha image height
			'winWidth' => 220,		   // captcha image width
			'fontSize' => 25,          // captcha image characters fontsize
			'fontPath' => WWW_ROOT . 'tahomabd.ttf',    // captcha image font
			'noiseColor' => '#ccc',
			'bgColor' => '#fff',
			'noiseLevel' => '100',
			'textColor' => '#000'
		);

		$img = $this->Captcha->ShowImage($settings);
		echo $img;
	}

	public function sendEmail($value)
	{

		exit;
	}

	public function editGroupExpense()
	{

		$data["id"] = 13;
		$data["title"] = __("LBL_TEST_TITLE_MODIFIED");
		$data["currency"] = "BDT";
		$data["description"] = __("LBL_THIS_UPDATE_DESCRIPTION");
		$data["language"] = "bd";
		$data["is_secret"] = "1";
		$data["secret_key"] = "bbb";

		$this->loadModel('Expense');

		$unique_url = $this->Expense->updateGroupexpense($data);
		if ($unique_url != "") {
			echo __("LBL_DATA_MODIFIED");
		}
	}




	public function addParticipant()
	{
		$data["group_expense_id"] = 13;
		$data["name"] = "Rohit";
		$this->loadModel('Participant');

		$result = $this->Participant->addParticipant($data);
		if ($result == "1") {
			echo __("LBL_PARTICIPANT_ADDED");
		}
	}

	public function removeParticipant()
	{
		$data["participant_id"] = 33;
		$this->loadModel('Participant');

		$result = $this->Participant->removeParticipant($data);
		if ($result == "1") {
			echo __("LBL_PARTICIPANT_REMOVED");
		}
	}

    private function addGroupSetting($data)
    {
        $this->loadModel('GroupSetting');
        $request = [
            'is_restricted_mode' => $data['is_restricted_mode'],
            'expense_id' => $data['expense_id'],
            'unique_url' => $data['unique_url']
        ];
        return $this->GroupSetting->saveGroupSetting($request);

    }

    private function setPermission(){
        $this->user_id = $this->Session->read('userData.id');
        $permission_permitted = (!empty($this->user_id) && $this->user_id>0);
        $this->set('permitted', $permission_permitted);
    }

    private function addPermission($request)
    {
        $PermissionTable = ClassRegistry::init('PermissionTable');
        return $PermissionTable->addPermission($request);
    }

    private function insertAccessInfo($data){
        //insert data into the table access_infos
        $accessInfoData["id"] = $data["id"];
        $accessInfoData["unique_url"] = $data["unique_url"];
        $accessInfoData["access_time"] = $this->getSystemCurrentTimeStamp();

        $error = $this->AccessInfo->saveAccessInfo($accessInfoData);
    }

	/*public function updateMultipleParticipant(){
		
		$data = array("30"=>"Frank","31"=>"Sharel");
		$this->loadModel('Participant');
			
		$result= $this->Participant->updateMultipleParticipant($data);
		if($result == "1"){
			echo "Participants have been modified!";		
		}
	}*/
}
