<?php
	session_start();
	
	//error_reporting(E_ALL);
	//ini_set('display_errors', 1);
	
	global $ROOT, $PATH, $phpself;
	$ROOT = $_SERVER['DOCUMENT_ROOT'];
	$PATH = '../../';  
	$phpself = basename(__FILE__);
	require_once($PATH . 'globals/globals.php');

	$content = '';
	
	if (!empty($_REQUEST['pclientID'])) {
		$pclientID = $_REQUEST['pclientID'];
		$dateFrom = $_REQUEST['dateFrom'];
		$dateTo = $_REQUEST['dateTo'];
		$prevUnpaid = $_REQUEST['prevUnpaid'];
		if (!empty($_REQUEST['pmtStatus'])) {
			if (is_array($_REQUEST['pmtStatus'])) {
				$pmtStatArray = $_REQUEST['pmtStatus'];
				$pmtStat = implode(",",$_REQUEST['pmtStatus']);
			} else {
				$pmtStatArray = explode(",",$_REQUEST['pmtStatus']);
				$pmtStat = $_REQUEST['pmtStatus'];
			}
		} else {
			$pmtStatArray = array();
			$pmtStat = '';
		}
		
		// Get Parent Client Information
		$query = 'SELECT * FROM clients WHERE clientID=' . $pclientID;
		$result = $con->query($query);
		while ($row=$result->fetch_array(MYSQLI_ASSOC)) {
			global $clientName,$clientAbbr,$clientContact,$clientContact,$ratePercent,$rateHourly; 
			$clientName = $row['clientName'];
			$clientAbbr = $row['clientAbbr'];
			$clientContact = $row['clientContactName'];
			$clientContact = $row['clientContactEmail'];
			$ratePercent = $row['ratePercent'];
			$rateHourly = $row['rateHourly']; 
			$comRate = $row['rateHourly']; 
		}
		$repTotalInv = '';
		$repTotalComish = '';
		$repTitle = 'Summary Billing Report: '. $clientName;
		$repFilters = '';
		if (!empty($dateFrom))
			$repFilters .= 'From: ' . Date::convert($dateFrom, 'Y-m-d', 'm/d/Y');
		if (!empty($dateTo))
			$repFilters .= ' - To: ' . Date::convert($dateTo, 'Y-m-d', 'm/d/Y');

		//require_once($PATH . 'phpExcel/Classes/PHPExcel.php');
		require_once($PATH . 'PHPExcel-1.8/Classes/PHPExcel.php');
		
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		
		// Set properties
		$objPHPExcel->getProperties()->setCreator("Como Creative")
									 ->setLastModifiedBy("Como Creative")
									 ->setTitle("Como Creative Billing Summary Report")
									 ->setSubject("Como Creative Billing Summary Report")
									 ->setDescription("Como Creative Billing Summary Report")
									 ->setKeywords("")
									 ->setCategory("Como Creative Billing Summary Report");
		
		// Set Page Orientation and Scaling
		$objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
		$objPHPExcel->getActiveSheet()->getPageSetup()->setFitToWidth(1);
		$objPHPExcel->getActiveSheet()->getPageSetup()->setFitToHeight(0);
		
		// Set default font
		$objPHPExcel->getDefaultStyle()->getFont()->setName('Arial');
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
		
		// Set Column Widths
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(65);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
		$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
		
		// Styles
		$default_border = array(
			'style' => PHPExcel_Style_Border::BORDER_THIN,
			'color' => array('rgb'=>'CCCCCC')
		);
		$style_repTitle = array(
			'font' => array(
				'bold' => true,
				'size' => 12,
			)
		);
		$style_repFilters = array(
			'font' => array(
				'size' => 8,
				'color' => array('rgb' => '666666'),
			)
		);
		$style_header = array(
			'borders' => array(
				'bottom' => $default_border,
				'left' => $default_border,
				'top' => $default_border,
				'right' => $default_border,
			),
			'fill' => array(
				'type' => PHPExcel_Style_Fill::FILL_SOLID,
				'color' => array('rgb'=>'E1E0F7'),
			),
			'font' => array(
				'bold' => true,
			)
		);
		$style_totals = array(
			'borders' => array(
				'top' => $default_border,
			),
			'font' => array(
				'bold' => true,
			)
		);
		$style_grandTotals = array(
			'font' => array(
				'bold' => true,
				'size' => 11,
				'color' => array('rgb' => '0000FF'),
			)
		);
		
		// Report Title
		$objPHPExcel->getActiveSheet()->mergeCells("A1:F1");
		$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray( $style_repTitle );
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->setCellValue('A1', $repTitle);
		
		// Repiort Filters
		$objPHPExcel->getActiveSheet()->mergeCells("A2:F2");
		$objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray( $style_repFilters );
		$objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->setCellValue('A2', $repFilters);
		
		$excelRow = '4'; 
		
		// Get Contract Project Information	
		$comishPercent = $ratePercent;
		include('../inc/export/exportProjects.php');
		
		// Get Sub-Client Hourly Project Information
		$comishPercent = $ratePercent;
		include('../inc/export/summaryHourly.php');
		
		// Get Parent-Client Hourly Project Information
		$comishPercent = 1;
		include('../inc/export/summaryParentClient.php');
		
		// Get Recurring Fee Information
		$comishPercent = $ratePercent;
		include('../inc/export/summaryRecurring.php');
		
		// Get Expense Information
		$comishPercent = 1;
		include('../inc/export/summaryExpenses.php');
		
		$objPHPExcel->getActiveSheet()->getStyle('B'. $excelRow .'')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
		$objPHPExcel->getActiveSheet()->setCellValue('B'. $excelRow .'', 'Total Invoiced: ');
		$objPHPExcel->getActiveSheet()->getCell('C'. $excelRow .'')->setValueExplicit(number_format($repTotalInv, 2,'.',''), PHPExcel_Cell_DataType::TYPE_NUMERIC);
		$objPHPExcel->getActiveSheet()->getStyle('C'. $excelRow .'')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
		$objPHPExcel->getActiveSheet()->getStyle('E'. $excelRow .'')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
		$objPHPExcel->getActiveSheet()->setCellValue('E'. $excelRow .'', 'Total Commission:');
		$objPHPExcel->getActiveSheet()->getCell('F'. $excelRow .'')->setValueExplicit(number_format($repTotalComish, 2,'.',''), PHPExcel_Cell_DataType::TYPE_NUMERIC);
		$objPHPExcel->getActiveSheet()->getStyle('F'. $excelRow .'')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
		$objPHPExcel->getActiveSheet()->getStyle('A'. $excelRow .':F'. $excelRow .'')->applyFromArray( $style_grandTotals );
		
		// Rename sheet
		$objPHPExcel->getActiveSheet()->setTitle('Datatypes');
		
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
		
		// Customize App Name
		$timestamp = str_replace(" ", "", $today);
		$applicantName = str_replace(" ", "", $clientAbbr);
		
		if ((!empty($dateFrom))&&(!empty($dateTo))) { 
			$dtFrom = str_replace("-", "", $dateFrom);
			$dtTo = str_replace("-", "", $dateTo);
			$appName = $applicantName . "_" . $dtFrom . "-" . $dtTo;
		} else
			$appName = $applicantName . "_" . $timestamp;
		
		// Save Excel 2007 file
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$newReport = str_replace('1111', $appName, __FILE__);
		$newReport = str_replace('.php', '.xlsx', $newReport);
		$objWriter->save($newReport);
		
		if ($_REQUEST['excelOP'] == "export") {
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: no-store, no-cache, must-revalidate");
			header("Cache-Control: post-check=0, pre-check=0", false);
			header("Pragma: no-cache");
			header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
			header('Content-Disposition: attachment;filename="Report.xlsx"');
			$objWriter->save('php://output');
		} elseif ($_REQUEST['excelOP'] == "email") {
	
			if (!empty($_REQUEST['emailFrom']))
				$emailFrom = $_REQUEST['emailFrom'];
			else
				$emailFrom = 'josh@comocreative.com';
			if (!empty($_REQUEST['emailFromName']))
				$emailFromName = $_REQUEST['emailFromName'];
			else
				$emailFromName = 'Como Creative';
				
			if (!empty($_REQUEST['emailTo']))
				$emailTo = $_REQUEST['emailTo'];
			else
				$emailTo = 'josh@comocreative.com';
			if (!empty($_REQUEST['emailToName']))
				$emailToName = $_REQUEST['emailToName'];
			else
				$emailToName = 'Como Creative';
			
			if (!empty($_REQUEST['emailCC']))
				$emailCC = $_REQUEST['emailCC'];
			else
				$emailCC = '';
			if (!empty($_REQUEST['emailCCname']))
				$emailCCname = $_REQUEST['emailCCname'];
			else
				$emailCCname = '';
			if (!empty($_REQUEST['emailBCC']))
				$emailBCC = $_REQUEST['emailBCC'];
			else
				$emailBCC = 'josh@comocreative.com';
			if (!empty($_REQUEST['emailSubject']))
				$emailSubject = $_REQUEST['emailSubject'];
			else
				$emailSubject = 'Como Creative Billing Report - '. $clientName .' '. Date::convert($dateFrom, 'Y-m-d', 'm/d/Y') .' - '. Date::convert($dateTo, 'Y-m-d', 'm/d/Y'); 
			
			if (!empty($_REQUEST['emailMessage']))
				$emailMessage = $_REQUEST['emailMessage'];
			else
				$emailMessage = '<p>Como Creative Billing Report Attached</p><p>'. $clientName .'</p><p>'. Date::convert($dateFrom, 'Y-m-d', 'm/d/Y') .' - '. Date::convert($dateTo, 'Y-m-d', 'm/d/Y') .'</p>';
				
			// Email Form
			require_once($PATH .'/PHPMailer/class.phpmailer.php');
			$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
			
			try {
				  $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($emailTo, $emailToName);
				  $mail->SetFrom($emailFrom, $emailFromName);
				  $mail->AddReplyTo($emailFrom, $emailFromName);
				  if (!empty($emailCC))
				  	$mail->AddCC($emailCC, $emailCCname);
				  if (!empty($emailBCC))	
				  	$mail->AddBCC($emailBCC);
				  $mail->Subject = $emailSubject; 
				  $mail->AltBody = 'Como Creative'; // optional - MsgHTML will create an alternate automatically
				  $mail->MsgHTML($emailMessage);
				  $mail->AddAttachment($newReport);      // 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!
			}
		
			/* Redirect browser */
			//header("Location: http://billing.tangiblelearning.com/reports/close.php");
			echo '<script type="text/javascript">
				//parent.location.reload();
				//parent.Shadowbox.close();
			</script>';
			/* Make sure that code below does not get executed when we redirect. */
		}
		exit;
	} 
	
?>