<?php
/*********************************************************************************
 * TimeTrex is a Payroll and Time Management program developed by
 * TimeTrex Payroll Services Copyright (C) 2003 - 2011 TimeTrex Payroll Services.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY TIMETREX, TIMETREX DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact TimeTrex headquarters at Unit 22 - 2475 Dobbin Rd. Suite
 * #292 Westbank, BC V4T 2E9, Canada or at email address info@timetrex.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by TimeTrex" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by TimeTrex".
 ********************************************************************************/
/*
 * $Revision: 12 $
 * $Id: UserCount.php 12 2006-08-10 18:43:12Z ipso $
 * $Date: 2006-08-10 11:43:12 -0700 (Thu, 10 Aug 2006) $
 */
/*
 * Counts the total active/inactive/deleted users for each company once a day.
 *
 */
require_once( dirname(__FILE__) . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'global.inc.php');
require_once( dirname(__FILE__) . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'includes'. DIRECTORY_SEPARATOR .'CLI.inc.php');

//Debug::setVerbosity( 11 );

//Arg1: report_schedule_id of timeclock to sync
//Arg2: background_process lock file name
if ( isset($argv[1]) AND $argv[1] != '' AND isset($argv[2]) AND $argv[2] != '') {
	set_time_limit( 600 ); //15mins, as this does not include time running outside calls, and likely not time streaming data.

	if ( function_exists('proc_nice') ) {
		proc_nice(19); //Low priority.
	}

	$report_schedule_id = (int)$argv[1];
	$background_process_lock_file_name = $argv[2];

	//Create lock file for background pooling.
	$bg_lock_file = new LockFile( $background_process_lock_file_name );
	$bg_lock_file->create();

	//Create lock file so the same clock isn't being synchronized more then once at a time.
	$lock_file = new LockFile( $config_vars['cache']['dir'] . DIRECTORY_SEPARATOR . 'ScheduledReport_'. $report_schedule_id.'.lock' );

	Debug::text('Attempting to process scheduled report ID: '. $report_schedule_id .' Background Lock File Name: '. $background_process_lock_file_name, __FILE__, __LINE__, __METHOD__, 10);

	if ( $lock_file->exists() == FALSE ) {
		if ( $lock_file->create() == TRUE ) {

			$rslf = new ReportScheduleListFactory();
			$rslf->getById( $report_schedule_id );
			if ( $rslf->getRecordCount() == 1 ) {
				foreach( $rslf as $rs_obj ) {
					Debug::text('Processing Scheduled Report: '. $rs_obj->getID() .'...', __FILE__, __LINE__, __METHOD__, 10);
					if ( PRODUCTION == FALSE ) {
						Debug::text('  NOT IN PRODUCTION MODE, SKIPPING...', __FILE__, __LINE__, __METHOD__, 10);
						continue;
					}

					//Set timezone to system default before we handle any clock data.
					TTDate::setTimeZone();

					try {
						$rs_obj->Execute();
					} catch ( Exception $e ) {
						Debug::text('Caught Exception: '. $e->getMessage(), __FILE__, __LINE__, __METHOD__, 10);
					}
				}
			}
		} else {
			Debug::text('Skipping... Scheduled Report ID: '. $report_schedule_id .' unable to create lock file...', __FILE__, __LINE__, __METHOD__, 10);
		}
		$lock_file->delete();
	} else {
		Debug::text('Skipping... Scheduled Report ID: '. $user_report_id .' lock file exists...', __FILE__, __LINE__, __METHOD__, 10);
	}

	//Delete background pool lock file.
	$bg_lock_file->delete();

	Debug::text('Done Processing Scheduled Report...', __FILE__, __LINE__, __METHOD__, 10);
} else {
	$bp = new BackgroundProcess();
	if ( !isset($config_vars['other']['max_processes']) ) {
		$config_vars['other']['max_processes'] = 2;
	}
	$bp->setMaxProcesses( $config_vars['other']['max_processes'] );
	$bp->setLockFileDirectory( $config_vars['cache']['dir'] );
	$bp->setLockFilePrefix( 'ScheduledReport' );

	$clf = new CompanyListFactory();
	$clf->getAll();
	if ( $clf->getRecordCount() > 0 ) {
		foreach ( $clf as $c_obj ) {
			if ( $c_obj->getStatus() != 30 ) {
				$rslf = new ReportScheduleListFactory();
				$rslf->getPendingByCompanyIDAndStateIDAndStatusID( $c_obj->getID(), 10, 10 );
				if ( $rslf->getRecordCount() > 0 ) {
					Debug::text('Found: '. $rslf->getRecordCount() .' Scheduled Reports that need processed for: '. $c_obj->getName(), __FILE__, __LINE__, __METHOD__, 10);
					foreach( $rslf as $rs_obj ) {
						if ( $rs_obj->isScheduledToRun() == TRUE ) {
							Debug::text('Launching Scheduled Report generation for: '. $rs_obj->getID() .' Name: '. $rs_obj->getName() .'...', __FILE__, __LINE__, __METHOD__, 10);

							//Execute self to generate each report in its own process.
							$command = '"'. $config_vars['path']['php_cli'] .'" "'. __FILE__ .'" '. $rs_obj->getId() .' #lock_file#';
							if ( OPERATING_SYSTEM == 'WIN' ) {
								//Windows requires quotes around the entire command, and each individual section with that might have spaces.
								$command = '"'. $command .'"';
							}
							Debug::text('Command: '. $command, __FILE__, __LINE__, __METHOD__, 10);
							$bp->run( $command );
						} else {
							Debug::text('Skipping Scheduled Report, not scheduled to run yet: '. $rs_obj->getID(), __FILE__, __LINE__, __METHOD__, 10);
						}
					}
				}
			}
		}
	}
	Debug::text('Done Checking Scheduled Reports...', __FILE__, __LINE__, __METHOD__, 10);
}

Debug::writeToLog();
//Debug::Display();
?>