#!/usr/bin/php
<?

/*/
	© 2007-2018 by Windshields To Go USA - All rights reserved.
	File:  scripts/nsCreateLogSummary.php
	Purpose: Compost the NAGS System Log into a quick summary
	Note:  
	Created: 9/6/2007 - Jeremy (www.gravical.com)
	Modification History:
		· 05/27/2008 - Nathan - added some sleep times between RunRange calls
		· 10/15/2009 - Nathan - only allow this to run at certain times of day
		· 02/01/2018 - Nathan - php5, now using usleep; reformatting (& explant for re-log)
		· mm/dd/yyyy - [who] - [what]
	Link: (the w2g summary report) https://www.autoglasshosting.com/admin/affiliateNagsReports.php?affiliateID=108
	CLI help: ./nsCreateLogSummary.php --help
	cron CLI (auto mode, no args): ./nsCreateLogSummary.php
	CLI w/args: ./nsCreateLogSummary.php '2018-02-01' '2018-02-02' '2018-02-03'
/*/

	// toolbox
	//header('Content-type: ');  // remove fail
	$g_BasePath = "/home/auto11/public_html/";
	require $g_BasePath."inc/localsettings.php";
	require $g_BasePath."inc/php-mysql.php";
	error_reporting( E_ERROR | E_WARNING | E_PARSE | E_NOTICE );  // E_ALL & ~E_DEPRECATED
	//error_reporting( E_ALL );  // E_ALL & ~E_DEPRECATED
	$g_TotalRuns = 0;  // debugging (for early exit)
	
	// get db
	$db = mysql_connect( $gblMySqlHost, $gblMySqlUser, $gblMySqlPass, true );
	mysql_select_db( $gblMySqlDb, $db );

	// load all affiliate ids that are using the NAGS system
	$sql = "SELECT `aff` FROM `affiliate` WHERE `useNagsSystem` = 'Y'";
	$result = mysql_query( $sql, $db );
	$affiliates = array();
	while( $data = mysql_fetch_array( $result ) ) {
		$affiliates[] = $data[0];
	}
	mysql_free_result( $result );
	mysql_close( $db );
    print_r($affiliates);
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
    echo "test";
    exit();
	// settings
	$openings = array('','WS','DR','QT','VN','BK');  // hard-code. quicker than loading; these don't change
	$rest_microseconds = 7351;  // ~0.007s [NL:2018-02-01] microseconds for usleep()

	// check
	if( count($affiliates) < 1 ) {
		echo "[nsCreateLogSummary] Notice: No affiliates loaded - summarization process aborted.\n";
	}

	/* OPERATION MODE: specific or regular */
	if( isset($argv) && count($argv) > 1 ) { // specific date(s)
		if( HelpInfo($argv) ) {
			exit;
		}
		$date_list = ExtractArgumentDates( $argv );
		$rest_microseconds = 55; // way shorter in manual mode
		foreach( $date_list as $whendate ) {
			ProcessDate( $whendate, $rest_microseconds, $affiliates, $openings );
		}
	} else { // regular (cron)
		$days_back = 2;
		RegularDailyOperation( $days_back, $affiliates, $openings, $rest_microseconds );
	}
	
	// done
	exit;


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/


//-------------------------------------------------------------------------
// Show usage information.
//-------------------------------------------------------------------------
function HelpInfo( $ArgList ) {
	
	$helpstrings = array( "--help", "-help", "-h", "-?" );
	if( in_array( trim(strtolower($ArgList[1])), $helpstrings ) ) {
		echo "Usage: nsCreateLogSummary ['YYYY-MM-DD' ['YYYY-MM-DD' [...]]]\n\n";
		echo "This utility summarizes the `nsLog` table into `nsLogSummary`.\n";
		echo "Without parameters, default regular operation is today and previous 2 days.\n";
		echo "Parameters formatted as YYYY-MM-DD will [re]summarize specific dates.\n\n";
		exit;
		return true;
	}
	return false;
	
} // HelpInfo()


//-------------------------------------------------------------------------
// Extract string date(s) from the arguments and process each.
//-------------------------------------------------------------------------
function ExtractArgumentDates( $ArgList ) {

	// go through args and create date numbers from mktime()
	$dates = array();
	for( $i=1; $i < count($ArgList); $i++ ) {
		$year = intval(substr($ArgList[$i],0,4));
		$month = intval(substr($ArgList[$i],5,2));
		$day = intval(substr($ArgList[$i],8,2));
		//echo $i.": ".$ArgList[$i]." = ".$year." / ".$month." / ".$day."\n";
		if( $year < 1900 || $year > 3000 || $month < 1 || $month > 13 || $day < 1 || $day > 31 ) {
			echo "[nsCreateLogSummary] Invalid parameter #".$i.": \"".$ArgList[$i]."\". YYYY-MM-DD format required.\n\n";
			exit;
		}
		$dates[] = mktime(0, 0, 0, $month, $day, $year);
		$year = date('Y', $dates[count($dates)-1]);
		$month = date('m', $dates[count($dates)-1]);
		$day = date('d', $dates[count($dates)-1]);
		//echo "*ExtractArgumentDates() Parameter #".$i.": ".$month."/".$day."/".$year."\n";
	}
	return $dates;
	
} // ExtractArgumentDates()


//-------------------------------------------------------------------------
// Run log summarization for a date from mktime(). Rest = ~7351 micro-secs!
//-------------------------------------------------------------------------
function RegularDailyOperation( $DaysBack, $AffiliateList, $OpeningList, $RestingMicro ) {

	// loop through today and previous $days_back: ~32.5s uslept per day (150 aff * 6 opening * 4 types)
	for( $iDateMinus = 0; $iDateMinus <= $DaysBack; $iDateMinus++ ) {
		
		// compute the date and process it
		$whendate = mktime(0, 0, 0, date('m'), date('d') - $iDateMinus, date('Y'));
		ProcessDate( $whendate, $RestingMicro, $AffiliateList, $OpeningList );
	}
	
} // RegularDailyOperation()


//-------------------------------------------------------------------------
// Run log summarization for a date from mktime(). Rest = ~7351 micro-secs!
//-------------------------------------------------------------------------
function ProcessDate( $DateNumber, $RestingMicro, $AffiliateList, $OpeningList ) {

	// extract components
	$year = date('Y', $DateNumber);
	$month = date('m', $DateNumber);
	$day = date('d', $DateNumber);
	echo "[nsCreateLogSummary] ProcessDate: ".date('Y-m-d', $DateNumber)."\n";
	//echo "[nsCreateLogSummary] ProcessDate: ".$month."/".$day."/".$year."\n";

	// loop all affiliates on the system
	foreach( $AffiliateList as $affcode ) {

		// establish the week
		$start_of_week = GetStartOfWeek( $year, $month, $day );
		$weekstartyear = date('Y', $start_of_week);
		$weekstartmonth = date('m', $start_of_week);
		$weekstartday = date('d', $start_of_week);

		// loop all opening types
		foreach( $OpeningList as $opening ) {
			// run the current year, month, day, then week
			RunRange( $affcode, $opening, 'year', $year, 0, 0 );
			usleep( $RestingMicro );  // ~0.01s
			RunRange( $affcode, $opening, 'month', $year, $month, 0 );
			usleep( $RestingMicro );
			RunRange( $affcode, $opening, 'day', $year, $month, $day );
			usleep( $RestingMicro );
			// week handling
			RunRange( $affcode, $opening, 'week', $weekstartyear, $weekstartmonth, $weekstartday );
			usleep( $RestingMicro );
		}
		usleep( $RestingMicro * 5 );  // ~0.03s
	}
	usleep( $RestingMicro * 73 );  // ~0.5s

} // ProcessDate()


//-------------------------------------------------------------------------
// Find the start of this week by checking backwards.
//-------------------------------------------------------------------------
function GetStartOfWeek( $year, $month, $day ) {

	// loop backwards; compute each and return the time when day is found
	for( $i = 0; $i < 7; $i++) {
		$stamp = mktime(0, 0, 0, $month, $day - $i, $year);
		if( date('w', $stamp) == 1 ) { // only on Mondays
			return $stamp;
		}
	}

	// this should never happen
	return 0;

} // GetStartOfWeek()


//-------------------------------------------------------------------------
// Run a summary on a range of dates.
//-------------------------------------------------------------------------
function RunRange( $AffiliateCode, $OpeningCode, $PeriodType, $YearNum, $MonthNum, $DayNum ) {
	
	global $g_TotalRuns;
	// DEBUG: echo "[RR] "; return; // skipped/short-circuit
	// DEBUG: if( $PeriodType != "day" ) return; if( $OpeningCode != "WS" ) return;

	// determine the range for this period type
	if( $PeriodType == 'year' ) {
		$date_start = mktime(0, 0, 0, 1, 1, $YearNum);
		$date_final = mktime(0, 0, 0, 1, 1, date("Y", $date_start) + 1);
	} elseif( $PeriodType == 'month' ) {
		$date_start = mktime(0, 0, 0, $MonthNum, 1, $YearNum);
		$date_final = mktime(0, 0, 0, date("m", $date_start) + 1, 1, date("Y", $date_start));
	} elseif( $PeriodType == 'week' ) {
		$date_start = mktime(0, 0, 0, $MonthNum, $DayNum, $YearNum);
		$date_final = mktime(0, 0, 0, date("m", $date_start), date("d", $date_start) + 7, date("Y", $date_start));
	} elseif( $PeriodType == 'day' ) {
		$date_start = mktime(0, 0, 0, $MonthNum, $DayNum, $YearNum);
		$date_final = mktime(0, 0, 0, date("m", $date_start), date("d", $date_start) + 1, date("Y", $date_start));
	}

	// load the count via db query
	$sql = "SELECT COUNT(*) FROM `nsLog`"
		." WHERE `aff` = '".SQLEncode($AffiliateCode)."'"
		."   AND `stamp` >= '".SQLEncode(date('Y-m-d', $date_start))."'"
		."   AND `stamp` < '".SQLEncode(date('Y-m-d', $date_final))."'"
		."   AND `step` = 'quote'"
	;
	if( $OpeningCode != '' ) {
		$sql .= " AND `opening` = '".SQLEncode($OpeningCode)."'";
	}
	$number = SelectScalar( $sql );

	// create an id
	// [NL:2018-02-01] check for collisions? (it's bigint20), but 10+ years... lots of data!
	$hashkey = crc32( $AffiliateCode.":".$PeriodType.":".date("Y-m-d", $date_start).":".$OpeningCode );

	// insert the info
	$sql = "INSERT IGNORE INTO `nsLogSummary` SET"
		." `hash` = '".SQLEncode($hashkey)."',"
		." `affiliate` = '".SQLEncode($AffiliateCode)."',"
		." `type` = '".SQLEncode($PeriodType)."',"
		." `start` = '".SQLEncode(date("Y-m-d", $date_start))."',"
		." `opening` = '".SQLEncode($OpeningCode)."',"
		." `count` = '".SQLEncode($number)."'"
	;
	$result = SqlInsert($sql);
	$bInserted = (SqlInsert($sql) > 0);
	/*DEBUGGING
	if( $number > 0 ) {
		//echo $number ." == \"".$sql."\"\n\n";
		echo $hashkey." - ".$result." - ".$number."\n".$sql."\n\n";
		if( ++$g_TotalRuns > 25 ) {
			exit;
		}
	}/**/

	// when nothing was inserted, update instead
	if( !$bInserted ) {
		$sql = "UPDATE `nsLogSummary` SET"
			." `count` = '".SQLEncode($number)."'"
			." WHERE `hash` = '".SQLEncode($hashkey)."'"
		;
		SqlExecute( $sql );
	}
	
} // RunRange()
	

?>
