<?php

//echo $_SERVER['DOCUMENT_ROOT'] . '<br>';
//exit;

date_default_timezone_set('America/New_York');

$logfile =("service_cron_log.txt");
$log = fopen($logfile, "a+");
$now = date("Y-m-d H:i",time());
fwrite($log, "\n----- $now -----\n");

require_once('../globals/config.php');
global $con;
$con = new mysqli($host,$user,$pass,$name);
if ($con->connect_errno) {
    printf("Connect failed: %s\n", $con->connect_error);
    exit();
}
include('../globals/functions.php');

$today = date('Y-m-d');
//$today = date('2013-10-01');
$month = addDays($today, 30);

require_once('../PHPMailer/class.phpmailer.php');	
$sendAddress = 'josh@comocreative.com'; 
$sendName = 'Como Creative'; 
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPDebug  = 0;                     // enables SMTP debug information (for testing)
$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host       = "smtp.gmail.com"; // sets the SMTP server
$mail->Port       = 465;                    // set the SMTP port for the GMAIL server
$mail->Username   = "josh@comocreative.com"; // SMTP account username
$mail->Password   = "illomocJSC3705";        // SMTP account password
$mail->AddAddress($sendAddress, $sendName);
$mail->SetFrom($sendAddress, $sendName);
$mail->AddReplyTo($sendAddress, $sendName);

//echo $month;
//exit;

//$query = 'SELECT *, (ogf.feeAmt * fr.feeRecCalc) as billAmount FROM ongoingFees AS ogf LEFT JOIN clients AS c ON (ogf.clientID = c.clientID) LEFT JOIN feeDesc AS fd ON (ogf.feeDescID = fd.feeDescID) LEFT JOIN feeRec AS fr ON (ogf.feeRecID = fr.feeRecID) ORDER BY feeID';
$query = 'SELECT si.*, c.clientName, c.clientAbbr, c.clientID, c.subClientOf, so.*, st.*, sp.* FROM serviceInfo si LEFT JOIN clients c ON (c.clientID = si.clientID) LEFT JOIN serviceOwner so ON (si.svcOwner = so.ownerID) LEFT JOIN serviceProviders sp ON (si.svcProvider = sp.spID) LEFT JOIN serviceTypes st ON (si.svcType = st.serviceID) WHERE si.display=1 ORDER BY c.subClientOf, c.clientName';
$result = $con->query($query);

$serviceRemindersTODAY = ''; 
$serviceRemindersALL = '';
if ($result) {
	// Update service dates if necessary
	while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
		// If the renewal is due today
		$renewDate = Date::convert($row['svcExpDate'], 'Y-m-d', 'M d, Y');
		if (strtotime($row['svcExpDate']) == strtotime($today)) {
			$billindReminder = '<p><b>' . $row['clientName'] .'</b> is up for renewal on their '. $row['serviceName'] .' for '. $row['domainName'] .'.  Renewal is due TODAY: '. $renewDate .'.</p>';
			$serviceRemindersTODAY .= $billindReminder;
		}
		// Check if any services are expiring up in the next month.
		elseif ((strtotime($row['svcExpDate']) >= strtotime($today)) && (strtotime($row['svcExpDate']) <= strtotime($month))) {
			$billindReminder = '<p><b>' . $row['clientName'] .'</b> is up for renewal on their '. $row['serviceName'] .' for '. $row['domainName'] .'.  Renewal is due on '. $renewDate .'.</p>';
				$serviceRemindersALL .= $billindReminder;
		}
	}
}

if (empty($serviceRemindersTODAY)) {
	$serviceRemindersTODAY = 'No Service Reminders Today'; 
	/*try {
		$mail->Subject = ("No Service Reminders Today"); 
		$mail->AltBody = 'Como Creative'; // optional - MsgHTML will create an alternate automatically
		$mail->MsgHTML("No Service Reminders");
		//$mail->AddAttachment();      // attachment
		$mail->Send();
	} catch (phpmailerException $e) {
		echo $e->errorMessage(); //Pretty error messages from PHPMailer
	} catch (Exception $e) {
		echo $e->getMessage(); //Boring error messages from anything else!
	}*/
}
else {
	try {
		$mail->Subject = ("Today's Service Reminders"); 
		$mail->AltBody = 'Como Creative'; // optional - MsgHTML will create an alternate automatically
		$mail->MsgHTML($serviceRemindersTODAY);
		//$mail->AddAttachment();      // attachment
		$mail->Send();
	} catch (phpmailerException $e) {
		echo $e->errorMessage(); //Pretty error messages from PHPMailer
	} catch (Exception $e) {
		echo $e->getMessage(); //Boring error messages from anything else!
	}
}


if (empty($serviceRemindersALL)) {
	$serviceRemindersALL = 'No Upcoming Service Reminders'; 
	/*try {
		$mail->Subject = ("No Upcoming Service Reminders"); 
		$mail->AltBody = 'Como Creative'; // optional - MsgHTML will create an alternate automatically
		$mail->MsgHTML("No Upcoming Service Reminders");
		//$mail->AddAttachment();      // attachment
		$mail->Send();
	} catch (phpmailerException $e) {
		echo $e->errorMessage(); //Pretty error messages from PHPMailer
	} catch (Exception $e) {
		echo $e->getMessage(); //Boring error messages from anything else!
	}*/
}
else {
	try {
		$mail->Subject = ("Upcoming Service Reminders"); 
		$mail->AltBody = 'Como Creative'; // optional - MsgHTML will create an alternate automatically
		$mail->MsgHTML($serviceRemindersALL);
		//$mail->AddAttachment();      // attachment
		$mail->Send();
	} catch (phpmailerException $e) {
		echo $e->errorMessage(); //Pretty error messages from PHPMailer
	} catch (Exception $e) {
		echo $e->getMessage(); //Boring error messages from anything else!
	}
}
fwrite($log, $serviceRemindersTODAY . "\n");
fwrite($log, $serviceRemindersALL . "\n");
fclose ($log);
echo "service - ok";
?>