<?php
App::uses('ConnectionManager', 'Model');

class FiltersController extends AppController
{ 
	var $uses = array('AccessInfo','ExpiredRecord');
	
	//public $components = array('RequestHandler');
	
	public function beforeRender() {
		parent::beforeRender();	
		
	} 
	
	//Run daily once
	//shift the ids from access_infos to the table expired_records. 
	public function findExpiredRecords(){
		
		//retrieve all expried records
        $object = $this->request->input('json_decode');
        if(!empty($object)){
            $data = $this->objectToArray($object);
        }
        if(!empty($data['month'])) {
            $result = $this->AccessInfo->getExpiredExpenses($data['month']);
            if (!empty($result)) {
                $currentDate = $this->getSystemCurrentTimeStamp();
                foreach ($result as $key => $value) {
                    $deleteList[] = $value["AccessInfo"]["id"];
                    $data["ExpiredRecord"][$key]["id"] = $value["AccessInfo"]["id"];
                    $data["ExpiredRecord"][$key]["unique_url"] = $value["AccessInfo"]["unique_url"];
                    $data["ExpiredRecord"][$key]["inserted_on"] = $currentDate;
                }

                $error = $this->ExpiredRecord->saveAllExpiredRecords($data);
                if (empty($error)) {
                    //delete all records from AccessInfo table
                    $this->AccessInfo->deleteAllExpiredExpenses($deleteList);
                }
            }
        }
		
		exit;
		//echo "<pre>";
		//print_r($result);exit;
		
		//insert multiple record into the table Expired_Records
		//check the case whether the record insertion successful or not for multi insertion when pk already exist
		
	
	}
	
	
	// Run it in every hour once; 
	//Retrieve 100 records and process.Insert records into the backup tables as well as delete original records 
	public function backupAndRemoveOriginalRecords(){
		
		$backup_mode = Configure::read('expensecount.backup.mode');
		$limit = 100;
		
		if($backup_mode == true){
			
			//retrieve 100 records from the table expired_records 
			$query = "select id,unique_url from expired_records limit 0,".$limit;
			$db = ConnectionManager::getDataSource('default');
			$expiredRecordList = $db->query($query);
			 
			if(!empty($expiredRecordList)){
				
				//get all the expense_id
				foreach($expiredRecordList as $key=>$value){
					$expenseIdList[] = $value["expired_records"]["id"];
					$expenseType = substr($value["expired_records"]["unique_url"], 0, 1);
					
					if($expenseType == "1" || $expenseType == "2"){
						$groupAndMessExpenseList[] = $value["expired_records"]["id"];
					} else if($expenseType == "3" ){
						$familyExpenseList[] = $value["expired_records"]["id"];
					}
					
					if($expenseType == "2"){
						$messExpenseList[] = $value["expired_records"]["id"];
					}
					
				}
				
				$expenseIds = implode(",",$expenseIdList);
						
				try{
				   
				    //delete   records  from  backup_expenses  in case any previous  records avilable
				    $db->query("delete from backup_expenses where id in(".$expenseIds.")"); // delete from expenses
					//process to shift expenses table to backup_expenses table
					$db->query("insert into backup_expenses select * from expenses where id in(".$expenseIds.")");
				} catch(Exception $ex){
					
				}
				
				try{
					//delete from expenses
					$db->query("delete from expenses where id in(".$expenseIds.")"); // delete from expenses
				} catch(Exception $ex){
						
				}
				
				try{
				    //delete   records  from  backup_expense_emails  in case any previous  records avilable
				    $db->query("delete from backup_expense_emails where id in(".$expenseIds.")"); // delete from expenses
					//process to shift expense_emails table to backup_expense_emails table
					$db->query("insert into backup_expense_emails select * from expense_emails where id in(".$expenseIds.")");
				} catch(Exception $ex){
						
				}
				
				try{
					// delete from expense_emails
					$db->query("delete from expense_emails where id in(".$expenseIds.")"); // delete from participants
				} catch(Exception $ex){
						
				}
				
				
				
				if(!empty($groupAndMessExpenseList)){
					
					$groupExpenseIds = implode(",",$groupAndMessExpenseList);
					
					try{
					    //delete   records  from  backup_group_expenses  in case any previous  records avilable
					    $db->query("delete from backup_group_expenses where expense_id in(".$groupExpenseIds.")");  
						//process to shift group_expenses table to backup_group_expenses table
						$db->query("insert into backup_group_expenses select * from group_expenses where expense_id in(".$groupExpenseIds.")");
					} catch(Exception $ex){
							
					}
					
					try{
						// delete from group_expenses
						$db->query("delete from group_expenses where expense_id in(".$groupExpenseIds.")"); // delete from group_expenses
					} catch(Exception $ex){
							
					}
					
					try{
					    //delete   records  from  backup_participants  in case any previous  records avilable
					    $db->query("delete from backup_participants where expense_id in(".$groupExpenseIds.")");  
						//process to shift participants table to backup_participants table
						$db->query("insert into backup_participants select * from participants where expense_id in(".$groupExpenseIds.")");
					} catch(Exception $ex){
							
					}
					
					try{
						// delete from participants
						$db->query("delete from participants where expense_id in(".$groupExpenseIds.")"); // delete from participants
					} catch(Exception $ex){
							
					}
					
					
					
				}
				 
					
				//For  mess expense specially
				if(!empty($messExpenseList)){
					
					$messExpenseIds = implode(",",$messExpenseList);
					
					try{
					    //delete   records  from  backup_meals  in case any previous  records avilable
					    $db->query("delete from backup_meals where expense_id in(".$messExpenseIds.")");  
						//process to shift meals table to backup_meal table
						$db->query("insert into backup_meals select * from meals where expense_id in(".$messExpenseIds.")");
					} catch(Exception $ex){
							
					}
					
					try{
						//delete from meals
						$db->query("delete from meals where expense_id in(".$messExpenseIds.")"); // delete from meals
					} catch(Exception $ex){
							
					}
				}
				    
				
				//if it is family expense
				if(!empty($familyExpenseList)){
					
					$familyExpenseIds = implode(",",$familyExpenseList);
					try{
					    
					    //delete   records  from  backup_family_expenses  in case any previous  records avilable
					    $db->query("delete from backup_family_expenses where expense_id in(".$familyExpenseIds.")");  
						//process to shift family_expenses table to backup_family_expenses table
						$db->query("insert into backup_family_expenses select * from family_expenses where expense_id in(".$familyExpenseIds.")");
     				} catch(Exception $ex){
							
					}
					
					try{
						//delete from family_expenses
						$db->query("delete from family_expenses where expense_id in(".$familyExpenseIds.")"); // delete from family_expenses
					} catch(Exception $ex){
							
					}
					
				} 
				
				try{
				    //delete   records  from  backup_family_expenses  in case any previous  records avilable
				    $db->query("delete from backup_logs where expense_id in(".$expenseIds.")");  
					//process to shift logs table to backup_logs table
					$db->query("insert into backup_logs select * from logs where expense_id in(".$expenseIds.")");
				} catch(Exception $ex){
						
				}
				
				try{
					//delete from logs
					$db->query("delete from logs where expense_id in(".$expenseIds.")"); // delete from logs
				} catch(Exception $ex){
						
				}

				try{
				    //delete   records  from  backup_family_expenses  in case any previous  records avilable
				    $db->query("delete from backup_email_histories where expense_id in(".$expenseIds.")");
					//process to shift logs table to backup_logs table
					$db->query("insert into backup_email_histories select * from email_histories where expense_id in(".$expenseIds.")");
				} catch(Exception $ex){

				}

				try{
					//delete from logs
					$db->query("delete from email_histories where expense_id in(".$expenseIds.")"); // delete from logs
				} catch(Exception $ex){

				}
				 
				try{
					//process to delete records from table expired_records
					$db->query("delete from expired_records where id in(".$expenseIds.")"); // delete from expired_records
				} catch(Exception $ex){
						
				}
			} 

		}		
		
		exit;		
	}
	
	
	
	
	// Run Manually	 
	public function mergeBackupData(){	 
 
		$db = ConnectionManager::getDataSource('default');
		 
		// expense

			try{
				//process to shift backup_expenses table to expenses table
				$db->query("insert into expenses select * from backup_expenses");
			} catch(Exception $ex){
					
			}

			try{
				//delete from backup_expenses
				$db->query("delete from backup_expenses");  
			} catch(Exception $ex){

			}
			
			
			
			// group_expenses			
			try{
				//process to shift backup_expenses table to expenses table
				$db->query("insert into group_expenses select * from backup_group_expenses");
			} catch(Exception $ex){
					
			}
			
			try{
				//delete from backup_expenses
				$db->query("delete from backup_group_expenses");
			} catch(Exception $ex){
			
			}
			
			
			//family_expenses
			try{
				//process to shift backup_expenses table to expenses table
				$db->query("insert into family_expenses select * from backup_family_expenses");
			} catch(Exception $ex){
					
			}
				
			try{
				//delete from backup_expenses
				$db->query("delete from backup_family_expenses");
			} catch(Exception $ex){
					
			}
			
			
			// meals
			try{
				//process to shift backup_expenses table to expenses table
				$db->query("insert into meals select * from backup_meals");
			} catch(Exception $ex){
					
			}
			
			try{
				//delete from backup_expenses
				$db->query("delete from backup_meals");
			} catch(Exception $ex){
					
			}

			
			//participants
			try{
				//process to shift backup_expenses table to expenses table
				$db->query("insert into participants select * from backup_participants");
			} catch(Exception $ex){
					
			}
				
			try{
				//delete from backup_expenses
				$db->query("delete from backup_participants");
			} catch(Exception $ex){
					
			}
			
			
			
			//logs
			try{
				//process to shift backup_expenses table to expenses table
				$db->query("insert into logs select * from backup_logs");
			} catch(Exception $ex){
					
			}
			
			try{
				//delete from backup_expenses
				$db->query("delete from backup_logs");
			} catch(Exception $ex){
					
			}
			
			//backup_expense_emails
			try{
				//process to shift backup_expense_emails table to expense_emails table
				$db->query("insert into expense_emails select * from backup_expense_emails");
			} catch(Exception $ex){
					
			}
			
			try{
				//delete from backup_expense_emails
				$db->query("delete from backup_expense_emails");
			} catch(Exception $ex){
					
			}
			 
	
		exit;
	}

    /*
	 * Command : console\cake Backup backupSingleExpense
	 *  This method shifts and backup single expense from live tables to backup tables in the production database.
	 */
    public function backupSingleExpense($unique_url)
    {
        $db = ConnectionManager::getDataSource('default');
        try {
            $backup_expense = $db->query("select * from backup_expenses where unique_url='".$unique_url."'");
        } catch (Exception $ex) {
        }
        if (empty($backup_expense)) {
            $expense = $db->query("select * from expenses where unique_url= '".$unique_url."'");
            if(!empty($expense)) {

                $this->loadModel('Backup');
                $this->Backup->processBackupAndRemove($expense);

            } else {
                echo "Expense is not found in production  database. Could not perform backup!";
                exit;
            }
        } else {
            echo "Expense is already in backup database. Could not perform backup!";
            exit;
        }
        
        echo "Backup Process Completed!";
        exit;
    }

    /*
	 * command:  console\cake Backup archieveSingleItem
	 * Run it to archieve a sinle expense
	 *
	 * This method shifts one single expense from backup tables(live db) to archieve database
	 *
	 */
    public function archieveSingleItem($unique_url)
    {
        $this->loadModel('Backup');
        $this->Backup->archieveSingleExpense($unique_url);
        echo "Restore Process Completed!";
        exit;
    }

    /*
     * Command: console\cake Restore restore
     * For restoring a single item
     *
     * This methods first tries to restore single expense  from backup tables to live tables. If there
     * is no such expense in backup table, it tries to restore from archieve  database to live database.
     * If the expense is already exist in live tables, it does not do anything.
     *
     *
     */
    public function restoreSingleExpense($unique_url)
    {
        $this->loadModel("Backup");
        $this->Backup->restore($unique_url);
        echo "Restore Process Completed!";
        exit;
    }
	

}
	
?>
