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

	
	
	private function validateAddExpense($data){
		 
		$errorCode = "";
		
		$checkParticipantList = array();
		
		$form = $this->getFormDataByData($data);	
			
		//check expense ID
		$expenseIdArray = explode("-",$form["id"]);
		if(count($expenseIdArray) != 3 ||  $expenseIdArray[0] == ""){
			$errorCode = "1";
		} else {
			array_push($checkParticipantList,$expenseIdArray[0]);			 
		} 

		
		//check the participant involes in the expense are available or not
		if($errorCode == "" ){
			array_push($checkParticipantList,$form["paid_by_participant_id"]);
			
			if(!empty($form["participant_amount"])){
				$participantAmtStrArray = explode(",",$form["participant_amount"]);
				foreach($participantAmtStrArray as $key=>$value){
					$parts = explode("|",$value);
					array_push($checkParticipantList,$parts[0]);
				}
			}
			
			//make array unique
			$checkParticipantList = array_unique($checkParticipantList);

			//retrieve participant from DB 
			$dbParticipantList = $this->getParticipantIdListByExpId($form['expense_id']); 

			//retrieve participants from DB
			 //print_r($checkParticipantList);exit;
			 
			/* $Str = "";
			foreach($checkParticipantList as $key=>$value){
				$Str .= "{". $key."=>".$value."}";
			}
				
			$fp = fopen("rajib.txt","w+");
			fwrite($fp, $Str);
			fclose($fp); */

			 foreach($checkParticipantList as $index=>$item){
			 	if (!in_array($item, $dbParticipantList)) {

			 		$errorCode = "2";
			 	}
			 } 
		}
		
		
		return $errorCode;
	}
	  
	
	private function validateEditExpense($data){
		$errorCode= $this->validateAddExpense($data);
		
		if(empty($errorCode)){
			//check the expense is in DB or not			
			
		}
		
		return $errorCode;
		
	}
	
	public function getGroupExpenseLog($data){
	
		$expense_id = $data["expense_id"];
		$frommDate = $data["fromDate"]." 00:00:00";
		/* $date = new DateTime($frommDate);
		$frommDate = $date->format('Y-m-d'); */
		
		$toDate = date("Y-m-d", strtotime("+1 day", strtotime($data["toDate"])));
		/* $date = new DateTime($toDate);
		$toDate = $date->format('Y-m-d'); */
		
		App::import('model','Log');
		$log = new Log();
		$result =  $log->find('all', array('conditions' => array(
				'Log.expense_id' =>$expense_id,
				'Log.create_date >= ' => $frommDate,
				'Log.create_date <= ' => $toDate
		),
		'order' => 'Log.create_date DESC'));  
		// $log = $this->getDataSource()->getLog(false, false);
		//  $fp = fopen("testResult.txt","a+");
		// fwrite($fp,$frommDate."=".$toDate);
		 // debug($log);
			 
		return $result;
	}
	
	
	
	private function getParticipantIdListByExpId($expense_id){
		App::import('model','Participant');
		$participant = new Participant();
		$dbParticipantIdList = array();
		$data = $participant->find('all',
				array('conditions' =>
						array('Participant.expense_id =' => $expense_id)));
		foreach($data as $index=>$object){
			array_push($dbParticipantIdList,$object["Participant"]["participant_id"]);		
		}
		
		return $dbParticipantIdList;
	}
	
	 public function addGroupExpense($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);

		if(empty($errorCode)){
		 	
		 	$form = $this->getFormDataByData($data);
		 	
			if($form["expense_type"] != "1"){	 		 
		 		$form["participant_amount"] = "";
		 	}
		 	
		 	
		 	
		 	
		 	$fileds = array('id','expense_type','expense_id','what','expense_date','expense_date_new','create_date','update_date','amount','paid_by_participant_id','is_reimbursement','participant_amount','isDetails','type','version', 'extras','images');
		 	$data["GroupExpense"] = $form;
		 	if(!$this->save($data,false,$fileds)){
		 		$result["22"] = __("LBL_GROUP_EXPENSE_NOT_SAVED");
		 	} 
	 	} else {
	 		$result[$errorCode] = __("LBL_ADD_EXPENSE_FAILS");
	 	} 
	 	

	 	return $result;
	 	 
	 }
	 
	 public function addMultipleGroupExpense($expenseList,$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($expenseList)){
	 	
		 	foreach( $expenseList as $key=>$value){
		 		$value["source"] = "2"; //2=mobile
		 		$value["expense_id"] = $expense_id;
		 		
			 	if($value["expense_type"] != "1"){	 		 
			 		$value["participant_amount"] = "";
			 	}
		 	
		 		$form["GroupExpense"][$i] =  $this->getFormDataByData($value);
		 		 
		 		$i = $i + 1;
		 	}
		 	
		 
		 		
		   	if(!$this->saveMany($form["GroupExpense"])){
	 			$error = "22";
	 		}	 	  
	 	 
	 	}
	 	return $error;	 
	 }
	 
	 private function getFormDataByData($data){

	 	$form = array();
	 	$form["id"] = $data["id"];
	 	if(isset($data["expense_type"])){
	 		$form["expense_type"] = $data["expense_type"];
	 	} else {
	 		$form["expense_type"] = "1"; //1=group expense,2 = mess expense
	 	}
	 	$form["expense_id"] = $data["expense_id"];
	 	$form["what"] = $data["what"];
	 	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["paid_by_participant_id"] =  $data["paid_by_participant_id"];
	 	$form["isDetails"] = $data["isDetails"];
	 	
	 	$form["type"] = $data["type"]; // 1=normal expense,2=balance expense	
	 	
	 	if(isset($data["is_reimbursement"])){
	 		$form["is_reimbursement"] = $data["is_reimbursement"];
	 	}
	 	
	 	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"] = date('Y-m-d H:i:s');
	 	    
	 	}

	 	$form["participant_amount"] = $data["participant_amount"];
	 	if(isset($data["previous_desc"])){
	 		$form["previous_desc"] = $data["previous_desc"];
	 	}
	 	if(isset($data["new_desc"])){
	 		$form["new_desc"] = $data["new_desc"];
	 	}
	 	
	 	if(isset($data["previous_paid_by"])){
	 		$form["previous_paid_by"] = $data["previous_paid_by"];
	 	}
	 	
	 	if(isset($data["syn_add_unique_id"])){
	 		$form["syn_add_unique_id"] = $data["syn_add_unique_id"];
	 	}
	 	 
	 	
	 	$form["version"] = 0;	 	

	 	$form["update_date"] = $this->getSystemCurrentIntTime();

	 	//Make extras more accurately
        $result = $this->checkExtraGroupExpense($data['extras'], $data['what']);
        if($result != 99) {
            $data["extras"] = substr_replace($data["extras"], $result, 0, 1);
        }

	 	// assign data to form
        $form["extras"] = $data['extras'];


		// ## 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 modifyMultipleGroupExpense($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;
	 	
	 	foreach( $expenseList as $key=>$value){	 	
	 		$value["expense_id"] = 	$expenseId; 
	 		$version = $value["version"];
	 		
	 		if($value["expense_type"] != "1"){	 		 
			 	$value["participant_amount"] = "";
			}
			 	
	 		$form["GroupExpense"][$i] =  $this->getFormDataByData($value);
	 		$form["GroupExpense"][$i]['version'] = ($version)+1;	 

	 		//set log List
	 		$logList["Log"][$i]['expense_id'] = $form["GroupExpense"][$i]["expense_id"];
	 		$logList["Log"][$i]['previous_desc'] = $form["GroupExpense"][$i]["previous_desc"];
	 		$logList["Log"][$i]['new_desc'] = $form["GroupExpense"][$i]["new_desc"];
	 		$logList["Log"][$i]['previous_paid_by'] = $form["GroupExpense"][$i]["previous_paid_by"];  
	 		
	 		$i++;
	 	}
	 		

	 	App::import('model','Log');
 		$log = new Log();
	 	
	 	 
	 	//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
	 	 
 		//increase number of version	 		 
 		
 		
 		//check similar like Add expense
 		//$errorCode = $this->validateEditExpense($data);
	 		 
 		 
 		if(!$this->saveMany($form["GroupExpense"])){
 			//data modify fails
 			$error = "22";
 		} else {
 			//data modify successfull.hence insert logs
 
 			if(!$log->saveMany($logList["Log"])){
 				//data modify fails
 				$error = "23";
 			}
 		} 		 
	 	 
		
		return $error;
	 
	 }
	 
	 
	 public function modifyGroupExpense($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('all',
	 			array('conditions' =>
	 					array('GroupExpense.id =' => $form["id"])));
	 	
	 	
	 	
	 	if(empty($dbExpense)){
	 		//if expense not available in DB
	 		$result["3"] = __("LBL_GROUP_EXPENSE_NOT_AVAILABLE");
	 	} else {
	 		
	 		//increase number of version	 		 
	 		$form['version'] = ($dbExpense["0"]["GroupExpense"]["version"])+1;
	 		
	 		//check similar like Add expense
	 		//$data["expense_date"] = $this->data["date"];
	 		
	 		$errorCode = $this->validateEditExpense($data);

	 		if(empty($errorCode)){ 
	 			
	 			if($form["expense_type"] != "1"){	 		 
			 		$form["participant_amount"] = "";
			 	}
	 		
	 			$fileds = array('id','expense_type','expense_id','what','expense_date','expense_date_new','create_date','update_date','amount','paid_by_participant_id','is_reimbursement','participant_amount','isDetails','version', 'extras','images');
	 			$data["GroupExpense"] = $form;
	 		
	 			if(!$this->save($data,false,$fileds)){
	 				//data modify fails
	 				$result["22"] = __("LBL_DATA_SAVED_SUCCESSFULLY_DATABASE");
	 			} else {
	 				//data modify successfull.hence insert logs
 					App::import('model','Log');
 					$log = new Log();
 					
 					$fileds = array('expense_id','previous_paid_by','changed_by','previous_desc','new_desc');
 					$logData['Log'] = $this->getEditLogData($form);
 					if(!$log->save($logData,false,$fileds)){
 						//data modify fails
 						$result["23"] = __("LBL_LOG_INSERTATION_FAIL");
 					}
		 		}
	 		} else {
	 			//Found error
	 			$result[$errorCode] = __("LBL_EDIT_EXPENSE_FAILS");
	 		} 
	 	}
	 	 
		
		return $result;
	 }
	 
	 
	 private function getEditLogData($form){
	 	$result = array();
	  
	 	$result['expense_id'] = $form['expense_id'];
	 	$result['previous_desc'] = $form['previous_desc'];
	 	$result['new_desc'] = $form['new_desc'];
	 	$result['previous_paid_by'] = $form['previous_paid_by'];
	 	$result['changed_by'] = $form['changed_by'];

	 	
	 	return $result;	 	
	 }
	 
	 
	 public function deleteMultipleGroupExpense($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;
	 	
	 	foreach( $expenseList as $key=>$value){	 	
	 		$groupExpenseIdList[] = $value["id"];
	 		//set log List
	 		$logList["Log"][$i]['expense_id'] = $expenseId;
	 		$logList["Log"][$i]['previous_desc'] = $value["previous_desc"];
	 		$logList["Log"][$i]['new_desc'] = $value["new_desc"];
	 		$logList["Log"][$i]['previous_paid_by'] = $value["previous_paid_by"];  
	 		
	 		$i++;
	 	}
	 		

	 	App::import('model','Log');
 		$log = new Log();
	 	
	 	 
	 	//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
	 	 
 		//increase number of version	 		 
 		
 		
 		//check similar like Add expense
 		//$errorCode = $this->validateEditExpense($data);
	 		 
 		 
 		if(!$this->deleteAll(array('GroupExpense.id' => $groupExpenseIdList))){
 			//data modify fails
 			$error = "22";
 		} else {
 			//data modify successfull.hence insert logs
 
 			if(!$log->saveMany($logList["Log"])){
 				//data modify fails
 				$error = "23";
 			}
 		} 		 
	 	 
		
		return $error;
	 
	 }
	 
	 public function deleteGroupExpense($data){
	 	 
	 	$result = null;
	 	$form = $this->getFormDataByData($data);
	 	
	 	//retrieve the existing expense from DB
	 	 
	 	$dbExpense = $this->find('all',
	 			array('conditions' =>
	 					array('GroupExpense.id =' => $form["id"])));
	 	 
	 	 
	 	 
	 	if(empty($dbExpense)){
	 		//if expense not available in DB
	 		$result["3"] = __("LBL_GROUP_EXPENSE_NOT_AVAILABLE");
	 	} else {

		 	if(!$this->delete(array('id'=>$form["id"]))){
		 		 
		    	//data modify fails
		 		$result["22"] = __("LBL_GROUP_EXPENSE_NOT_DELETED_SUCCESSFULLY");
		 	} else {
	
		 		//data modify successfull.hence insert logs
		 		App::import('model','Log');
		 		$log = new Log();
		 		
		 		$fileds = array('expense_id','previous_paid_by','changed_by','previous_desc','new_desc');
		 		$logData['Log'] = $this->getEditLogData($form);
		 		if(!$log->save($logData,false,$fileds)){
		 			//data modify fails
		 			$result["23"] = __("LBL_LOG_INSERTATION_FAIL");
		 		}
		 		 
		 	}
	 	 
	 	}
	 	
	 	return $result;
	 }

     public function getImagesById($id){
         return $this->find('first',array(
             'fields' => array('GroupExpense.id', 'GroupExpense.images'),
             'conditions' => array('GroupExpense.id =' => $id)));
     }
	 
	 
	 private function isValidTimeStamp($timestamp)
	 
	 {
	     
	     return ((string) (int) $timestamp === $timestamp)
	     
	     && ($timestamp <= PHP_INT_MAX)
	     
	     && ($timestamp >= ~PHP_INT_MAX);
	     
	 }

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