<?php

/*/
	© 2002-2020 Windshields To Go USA
	License:  Authorized for use on the AutoGlassHosting.com website.
	File:  cal.phi
	Purpose:  Export invoice administration and calendaring system routines.
	Created:  6/2002 - Matt @ dmtech
	Modification History:
		· 07/30/2004 - Nathan - adapted for the new AGH master administrator; massive code cleanup
		· 04/06/2020 - Nathan - hide hidden invoices from the calendar dates
		· mm/dd/yyyy - [name] - [comment]
/*/
	

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


///-------------------------------------------------------------------------
function dbConnect( $site = "localhost" ) {

	$result = mysql_connect( "localhost" /*"localhost"*/, "windshi_winddb", "parker" );
	$db = "windshi_main";
	mysql_select_db($db, $result);
	return $result;

} // dbConnect()


///-------------------------------------------------------------------------
function makeCal( $month, $year, $targetFrame="", $affiliateID=0, $bgcolor="#E8E8E8", $textcolor="#484848", $linkcolor="#0000CC", $inactivetext="#B8B8B8", $flatcolor="#D0D0D0", $bordercolor="#6078A0") {

	global $PHP_SELF, $g_oNDB, $dateSort;
	
	/// initz...
	$dSort = (!isset($dateSort) || $dateSort=="") ? "purchaseDate" : $dateSort;
	if( $targetFrame ) {
		$targetParam = "target='".$targetFrame."'";
	}
	$leap = is_leap_year($year);
	$days = days_in_month($month, $leap);
	$firstDay = first_day_of_month($month, $year);
	$displayMonth = date("F", mktime(0,0,0,$month,1,$year));
	if( $flatcolor=="" ) {
		$flatcolor = $bgcolor;
	}

	/// day of the week, numeric, i.e. "2" (Sunday) to "6" (Saturday) 
	$dayNum = date("w");
	$month = sprintf("%02d", intval($month));
	$timeStart = microtime_float();
	echo "<table bgcolor=\"".$bordercolor."\" cellpadding=3 cellspacing=1 border=0 bordercolor=\"".$bordercolor."\" style=\"border: $bordercolor 1px solid;\"><tr bgcolor=\"".$flatcolor."\">";
	//$arrow_prev = "&larr;";
	//$arrow_next = "&rarr;";
	$arrow_prev = "&#x226A;";
	$arrow_next = "&#x226B;";
	echo "<td style=\"text-align: center;\"><a href=\"$PHP_SELF?A=P&month=" . sprintf("%02d", intval($month)-1) . "&year=$year&dateSort=$dSort&affiliateID=$affiliateID\" style= \"text-decoration: none;\"><font face=\"Tahoma, Calibri, Arial\" color=\"$linkcolor\"><span class=\"fa fa-angle-double-left\">"."</span></font></a></td>";
	echo "<td colspan=5 style=\"text-align: center;\"><a $targetParam onClick=\"this.blur(); return true;\" href=\"invoices.php?A=CAL&month=".$month."&year=$year&dateSort=$dSort&affiliateID=$affiliateID&showTotals=1\" style=\"text-decoration: none\"><font face=arial size=-1 color=\"$linkcolor\"><b>$displayMonth</a>&nbsp;&nbsp;<a $targetParam onClick=\"this.blur(); return true;\" href=\"invoices.php?A=CAL&year=$year&dateSort=$dSort&affiliateID=$affiliateID&showTotals=1\" style=\"text-decoration: none\"><font face=arial size=-1 color=\"$linkcolor\">$year</b></a></font></td>";
	echo "<td style=\"text-align: center;\"><a href=\"$PHP_SELF?A=N&month=" . sprintf("%02d", intval($month)+1) . "&year=$year&dateSort=$dSort&affiliateID=$affiliateID\" style= \"text-decoration: none;\"><font face=\"Tahoma, Calibri, Arial\" color=\"$linkcolor\"><span class=\"fa fa-angle-double-right\">"."</span></font></a></td>";
	echo "</tr><tr bgcolor=\"".$flatcolor."\" align=center><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>Su</b></font></td><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>M</b></font></td><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>Tu</b></font></td><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>W</b></font></td><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>Th</b></font></td><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>F</b></font></td><td style='text-align: center;'><font face=verdana size=-2 color=\"$textcolor\"><b>Sa</b></font></td></tr><tr>";
	for( $blankDay = 1; $blankDay <= $firstDay; $blankDay++ ) {
		echo "<td bgcolor=".$flatcolor.">&nbsp;</td>";
	}
	
	/// collect counts for all the dates in this month...
	$sqls = array(); // keep for debug below
	if( $affiliateID === "COMBINED" ) {  // w2gcsr + wsnet + agnet + w2g totaled together
		$affClause = "(invoice.affiliateID IN (308,168,108) OR invoice.orderCode='W2G')";
	} elseif( intval($affiliateID) == 163 ) {  // agnet isn't reliably tagged with affiliateID=163
		$affClause = "invoice.orderCode='W2G'";
	} elseif( intval($affiliateID) == 0 ) {  // "All / Direct": every isJoined or isW2G account, not literally affiliateID=0
		$rJoinedAffs = $g_oNDB->getColumn( 0, "SELECT ID FROM affiliate WHERE isJoined='Y' OR isW2G='Y'", "-1" );
		$rJoinedAffs[] = "0";
		$JoinedAffs = join(",", $rJoinedAffs);
		$affClause = "invoice.affiliateID IN (".$JoinedAffs.")";
	} else {
		$affClause = "invoice.affiliateID=".intval($affiliateID);
	}
	$requirePaidCal = ( $affiliateID === "COMBINED" || intval($affiliateID) > 0 );  // only require Paid for a specific account (or Combined); "All / Direct" shows every job regardless of paid status
	$paidClause = $requirePaidCal ? " AND paid='Y'" : "";
	$paidClauseInv = $requirePaidCal ? " AND invoice.paid='Y'" : "";
	for( $i = 0; $i < $days; $i++ ) {
		if( ($blankDay + ($day - 1)) % 7 == 0 && $day != 0 ) {
			$cellNum = 1;
			echo "</tr><tr>";
		}
		$day++;
		echo "<td onMouseOver=\"this.style.background='#FCFCE0';\" onMouseOut=\"this.style.background='".$bgcolor."';\" align=right width=10 bgcolor=\"".$bgcolor."\" align=center style='text-align: center;'>";
		echo "<a $targetParam onClick=\"this.blur(); return true;\" href=\"invoices.php?site=".$site."&A=CAL&day=".$day."&month=".$month."&year=".$year."&dateSort=".$dSort."&affiliateID=".$affiliateID."\" style=\"text-decoration: none\">";
		if( $dSort=="purchaseDate" ) {  // purchase date
			$SQL = "SELECT Count(*) FROM invoice WHERE ".$affClause." AND purchaseDate LIKE '".$year."-".$month."-".sprintf("%02d",$day)."%' AND hidden='N'".$paidClause;
			$num = intval( $g_oNDB->getField(0, $SQL, 0) );
			if( $num > 0 ) {
				$style = "color: ".$linkcolor."; font-style: normal; font-weight: bold";
			} else {
				$style = "color: ".$inactivetext."; font-style: normal; font-weight: normal;";
			}
			$sqls[] = $SQL;
		} elseif( $dSort=="s_InstallDate" ) { // installation date: method 1 = ~3.6s
			$SQL = "SELECT Count(*) FROM invoice LEFT JOIN checkout ON invoice.checkoutID=checkout.ID WHERE ".$affClause." AND s_InstallDate LIKE '".sprintf("%02d",$day)." ".$displayMonth."%' AND s_InstallYear='$year' AND hidden='N'".$paidClauseInv;  // echo $SQL."<br>";
			$num = intval( $g_oNDB->getField(0, $SQL, 0) );
			if( $num > 0 ) {
				$style = "color: ".$linkcolor."; font-style: normal; font-weight: bold";
			} else {
				$style = "color: ".$inactivetext."; font-style: normal; font-weight: normal;";
			}
			$sqls[] = $SQL;
		} elseif( $dSort=="s_InstallDateX2" ) { // installation date: method 2 = ~2.7s
			/* disabled until î can find a faster method */
			$IDs = $g_oNDB->getColumn("select ID from checkout WHERE s_InstallYear='$year' AND s_InstallDate LIKE '".sprintf("%02d",$day)." ".$displayMonth."%'");
			if( count($IDs)>0 ) {
				$SQL = "SELECT Count(*) FROM invoice WHERE ".$affClause.$paidClauseInv." AND invoice.checkoutID IN (".implode(",",$IDs).")";  // echo $SQL."<br>";
				$num = intval( $g_oNDB->getField(0, $SQL, 0) );
				$sqls[] = $SQL;
			} else {
				$num = 0;
			}
			if( $num > 0 ) {
				$style = "color: ".$linkcolor."; font-style: normal; font-weight: bold";
			} else {
				$style = "color: ".$inactivetext."; font-style: normal; font-weight: normal;";
			}
		} else { // otherwise
			$style = "color: ".$linkcolor.";";
		}
		echo "<span style=\"font-family: verdana; font-size: 10px; ".$style."\">".$day."</span></a></td>";
		$cellNum++;
	}
	
	/// tie off the row & table...
	while( $cellNum++ <= 7 ) {
		echo "<td bgcolor=".$flatcolor.">&nbsp;</td>";
	}
	echo "</tr></table>\n\n";
	
	/// troubleshooting; show time on text select/highlight...
	echo "<font color=".( $PHP_SELF=="/admin/invoices/menu.php" ? "#A8C8C0" : $flatcolor).">".sprintf("%.3f", microtime_float()-$timeStart) . " seconds</font><br>";
	// echo "<pre>$dSort\n";
	// print_r( $sqls );
	
	/// [NL:2020-04-06] troubleshooting; added checkout indexes and was already greatly improved - implement this later
	// example query from menu.php: [0] => SELECT Count(*) FROM invoice LEFT JOIN checkout ON invoice.checkoutID=checkout.ID WHERE invoice.affiliateID=0 AND s_InstallDate LIKE '01 April%' AND s_InstallYear='2020' AND hidden='N'
	/* !! modify to adjust month name and length: (updated)
			SELECT Mid(s_InstallDate, 1, 8) `day`, Count(*) `num`
			FROM invoice LEFT JOIN checkout ON invoice.checkoutID = checkout.ID 
			WHERE invoice.affiliateID = 0 AND Mid(s_InstallDate, 4, 5) = 'April' AND s_InstallYear='2020' AND hidden='N' 
			GROUP BY Mid(s_InstallDate, 1, 8)
	*/

} // makeCal()


///-------------------------------------------------------------------------
function days_in_month( $month, $leap ) {

	switch( $month ) {
		case 2: return $leap ? 29 : 28;
		case 4: case 6: case 9: case 11: return 30;
		default: return 31;
	}

} // days_in_month()


//-------------------------------------------------------------------------
// is_leap_year:  Just returns true if the specified year is a leap year.
//-------------------------------------------------------------------------
function is_leap_year( $year ) {

	return ($year % 4 == 0) ? 1 : 0;

} // is_leap_year()


//-------------------------------------------------------------------------
// first_day_of_month: returns the numeric day of the week,  "0" (Sunday) to "6" (Saturday) 
//-------------------------------------------------------------------------
function first_day_of_month( $month, $year ) {

	$firstDay = date("w" ,mktime(0,0,0,$month,1,$year));
	return $firstDay;

} // first_day_of_month()


//-------------------------------------------------------------------------
// microtime_float:  Simple function to replicate PHP 5 behaviour.
//-------------------------------------------------------------------------
function microtime_float() { 

	list($usec, $sec) = explode(" ", microtime()); 
	return ((float)$usec + (float)$sec); 

} // microtime_float()


