<?php
class FamilyExpense extends AppModel
{
	var $name='FamilyExpense';
//1 = Input data format is not correct
//2 = participant in this expense is deleted by other user or not available

	
	
	private function validateAddExpense($data,$source){
		 
		$errorCode = "";
		
		$checkParticipantList = array();
		
		$form = $this->getFormDataByData($data);	
			
		//check expense ID
		$expenseIdArray = explode("-",$form["id"]);
		if(count($expenseIdArray) != 3 ){
			$errorCode = "1";
		} 
		
		if($errorCode == "" && $source == "1"){
			//check expense id already exist in db or not			 
			$data = $this->find('first', array('conditions' => array('FamilyExpense.id' =>$form["id"]), 'fields'=>array('id'))); 
		
			if(!empty($data)){
				$errorCode = "34";
			}
		}
		return $errorCode;
	}
	  
	
	private function validateEditExpense($data){
		$errorCode= $this->validateAddExpense($data,2);
		
		if(empty($errorCode)){
			//check the expense is in DB or not			
			
		}
		
		return $errorCode;
		
	}
	
 
	
	
	
	 
	 public function addFamilyExpense($data){
	
	 	
	 	$result = null;
	 	//check the any of the involves participant(s) has been deleted or not
	 	//check account is closed already or not
	 	//update participant's balance
	 	//22 = Data not saved successfully in Database
	 	
	 	$errorCode = $this->validateAddExpense($data,1);
	 	
	 	
		if(empty($errorCode)){
		 	
		 	$form = $this->getFormDataByData($data);
		 	
		 	
		 	
		 	$fileds = array('id','expense_type','expense_id','record_type','what','category','expense_date','expense_date_new','create_date'.'update_date','amount','is_reimbursement','type','version','images');
		 	$data["FamilyExpense"] = $form;
		 	
		 		
		 	if(!$this->save($data,false,$fileds)){
		 		$result["22"] = __("LBL_FAMILY_EXPENSE_NOT_SAVED");
		 	} 
	 	} else {
	 		$result[$errorCode] = __("LBL_ADD_FAMILY_EXPENSE_FAIL");
	 	} 
	 	
	 	
	 	
	 	return $result;
	 	 
	 }
	 
	 public function addMultipleFamilyExpense($FinalFamilyExpenseArray,$expense_id){
	 	 
	 	$error = "";
	 	//check the any of the involves participant(s) has been deleted or not
	 	//check account is closed already or not
	 	//update participant's balance
	 	//22 = Data not saved successfully in Database

	 	$i = 0;
	 	if(!empty($FinalFamilyExpenseArray)){
		 	foreach( $FinalFamilyExpenseArray as $key=>$value){
		 		$value["source"] = "2"; //2=mobile
		 		$value["expense_id"] = $expense_id;
		 		$form["FamilyExpense"][$i] =  $this->getFormDataByData($value);
		 		 
		 		$i = $i + 1;
		 	}
		 		
		   	if(!$this->saveMany($form["FamilyExpense"])){
	 			$error = "22";
	 		}	 	  
 		
	 	}
	 	 
	 	return $error;	 
	 }
	 
	 private function getFormDataByData($data){
	 	$form = array();
	 	$form["id"] = $data["id"];
	 	 
	 	$form["expense_id"] = $data["expense_id"];
	 	$form["record_type"] = $data["record_type"]; // 1= expense,2=income
	 	$form["what"] = $data["what"];
	 	$form["category"] = $data["category"];
	 	
	 	if(isset($data["expense_date_old"])){
	 		$form["expense_date"] = $data["expense_date_old"];
	 	}
	 	
	 	$form["expense_date_new"] = $data["expense_date"];
	 	$form["amount"] = $data["amount"];	
	 	$form["category"] = $data["category"];	 
	 	$form["type"] = "1"; // 1=normal expense,2=balance expense	

	 	$form["version"] = 0;	 	
	 	
	 	if(isset($data["is_reimbursement"])){
			$form["is_reimbursement"] = $data["is_reimbursement"];
	 	}
	 	
	 	if(isset($data["syn_add_unique_id"])){
	 		$form["syn_add_unique_id"] = $data["syn_add_unique_id"];
	 	}
	 	
	 	
	 	if(isset($data["create_date"]) && $this->isValidTimeStamp($data["create_date"]) ){
	 	    
	 	    $form["create_date"] = $data["create_date"];
	 	    $form["create_date"] = date('Y-m-d H:i:s',  $form["create_date"]);
	 	    
	 	} else if(isset($data["create_date"]) && !empty($data["create_date"])){
	 	    $form["create_date"] = $data["create_date"];
	 	    
	 	} else {
	 	    $form["create_date"] = $this->getSystemCurrentIntTime();
	 	}
	 	
	 	$form["update_date"] = $this->getSystemCurrentIntTime();

		// ## New features
		if(isset($data["category_id"]) && !empty($data["category_id"])) {
			$form["category_id"] = $data["category_id"];
		}

		if(isset($data["custom_categories"]) && !empty($data["custom_categories"])) {
			$form["custom_categories"] = $data["custom_categories"];
		}

		if(isset($data["receipts"]) && !empty($data["receipts"])) {
			$form["receipts"] = $data["receipts"];
		}

		if(isset($data["changed_by"]) && !empty($data["changed_by"])) {
			$form["changed_by"] = $data["changed_by"];
		} else {
			$form["changed_by"] = null;
		}

         $form['images'] = empty($data['images']) ? null : $data['images'];

		// ##
	 	
	 	return $form;
	 }
	 
	 
 	public function modifyMultipleFamilyExpense($expenseList,$expenseId){
	 	 
	 	$error = "";
	 	//check the any of the involves participant(s) has been deleted or not
	 	//check account is closed already or not
	 	//update participant's balance
	 	//22 = Data not saved successfully in Database

	 	$i = 0;
	 	
	 	if(!empty($expenseList)){
		 	foreach( $expenseList as $key=>$value){	 	
		 		$value["expense_id"] = 	$expenseId; 
		 		$version = $value["version"];
		 		$form["FamilyExpense"][$i] =  $this->getFormDataByData($value);
		 		$form["FamilyExpense"][$i]['version'] = ($version)+1;	 
	 	 		$i++;
		 	}
	  
	 		if(!$this->saveMany($form["FamilyExpense"])){
	 			//data modify fails
	 			$error = "22";
	 		} 		 
 		}
	 	 
		
		return $error;
	 
	 }
	 
	 
	 public function modifyFamilyExpense($data){
	 	 
	 	//check the any of the involves participant(s) has been deleted or not
	 	//check account is closed already or not
	 	//update participant's balance
	 	//3 = group expense not available in database;
	 	//22 = Data not saved successfully in Database
	 	//23 = Log insertion fail
	 	
	 	$result = null;
	 	$form = $this->getFormDataByData($data);
	 	
	 	//retrieve the existing expense from DB 
	 	$dbExpense = $this->find('first', array('conditions' => array('FamilyExpense.id' =>$form["id"]), 'fields'=>array('version'))); 
	 	
	 	/*$dbExpense = $this->find('all',
	 			array('conditions' =>
	 					array('FamilyExpense.id =' => $form["id"]))); */
	 	
	 	
	 	
	 	if(empty($dbExpense)){
	 		//if expense not available in DB
	 		$result["3"] = __("LBL_FAMILY_EXPENSE_NOT_AVAILABLE");
	 	} else {
	 		
	 		//increase number of version	 		 
	 		$form['version'] = ($dbExpense["FamilyExpense"]["version"])+1;
	 		
	 		//check similar like Add expense
	 		$errorCode = $this->validateEditExpense($data);
	 		 
	 		if(empty($errorCode)){ 
	 		
	 			$fileds = array('id','expense_id','what','expense_date','expense_date_new','update_date','amount','category','is_reimbursement','version','images');
	 			$data["FamilyExpense"] = $form;
	 		
	 			if(!$this->save($data,false,$fileds)){
	 				//data modify fails
	 				$result["22"] = __("LBL_DATA_SAVED_SUCCESSFULLY_DATABASE");
	 			}  
	 		} else {
	 			//Found error
	 			$result[$errorCode] = __("LBL_EDIT_FAMILY_EXPENSE_FAIL");
	 		} 
	 	}
	 	 
		
		return $result;
	 }
	 
	 
	 
	 public function deleteMultipleFamilyExpense($expenseList,$expenseId){
	 	 
	 	$error = "";
	 	//check the any of the involves participant(s) has been deleted or not
	 	//check account is closed already or not
	 	//update participant's balance
	 	//22 = Data not saved successfully in Database

	 	$i = 0;
	 	
	 	if(!empty($expenseList)){
		 	foreach( $expenseList as $key=>$value){	 	
		 		$groupExpenseIdList[] = $value["id"]; 
		 		$i++;
		 	}
		  
	 		if(!$this->deleteAll(array('FamilyExpense.id' => $groupExpenseIdList))){
	 			//data modify fails
	 			$error = "22";
	 		}  
 		
	 	}
		
		return $error;
	 
	 }
	 
	 public function deleteFamilyExpense($data){
	 	 
	 	$result = null;
	 	$form = $this->getFormDataByData($data);
	 	
	 	//retrieve the existing expense from DB
	 	 
	 	/*$dbExpense = $this->find('all',
	 			array('conditions' =>
	 					array('FamilyExpense.id =' => $form["id"])));*/
	 	$dbExpense = $this->find('first', array('conditions' => array('FamilyExpense.id' =>$form["id"]), 'fields'=>array('id'))); 
	 	 
	 	 
	 	 
	 	if(empty($dbExpense)){
	 		//if expense not available in DB
	 		$result["3"] = __("LBL_FAMILY_EXPENSE_NOT_AVAILABLE");
	 	} else {
	 	
		 	if(!$this->delete(array('id'=>$form["id"]))){
		 		 
		    	//data modify fails
		 		$result["22"] = __("LBL_FAMILY_EXPENSE_NOT_DELETED");
		 	}  
	 	 
	 	}
	 	
	 	return $result;
	 } 
	 
	 
	 private function isValidTimeStamp($timestamp)
	 
	 {
	     
	     return ((string) (int) $timestamp === $timestamp)
	     
	     && ($timestamp <= PHP_INT_MAX)
	     
	     && ($timestamp >= ~PHP_INT_MAX);
	     
	 }

    public function getImagesById($id){
        return $this->find('first',array(
            'fields' => array('FamilyExpense.id', 'FamilyExpense.images'),
            'conditions' => array('FamilyExpense.id =' => $id)));
    }

    private function getSystemCurrentIntTime(){
        date_default_timezone_set("UTC");
        return time();
    }

}