<?php

include ('includes/session.php');
$Title = _('Profit and Loss');
include('includes/SQL_CommonFunctions.php');
include('includes/AccountSectionsDef.php'); // This loads the $Sections variable

$ViewTopic= 'GeneralLedger';
$BookMark = 'ProfitAndLoss';

$SectionTypes = array("1" => "after Operations", "2" => "before Tax", "3" => "after Tax");

if(isset($_GET['section']) || isset($_GET['group']))
{
	$_POST['FromPeriod'] = $_GET['from'];
	$_POST['ToPeriod'] = $_GET['to'];
	if($_GET['nonzero']==1)
	{
		$_POST['nonZeroRecordsOnly'] = $_GET['nonzero'];
	}
	else
	{
		unset($_POST['nonZeroRecordsOnly']);
	}
	
}

if (isset($_POST['FromPeriod']) and ($_POST['FromPeriod'] > $_POST['ToPeriod'])){
	prnMsg(_('The selected period from is actually after the period to') . '! ' . _('Please reselect the reporting period'),'error');
	$_POST['SelectADifferentPeriod']='Select A Different Period';
}

if ((!isset($_POST['FromPeriod'])
    AND !isset($_POST['ToPeriod']))
    OR isset($_POST['SelectADifferentPeriod'])){
    
	include('includes/header.php');

	echo '<p class="page_title_text">
		<img src="'.$RootPath.'/css/'.$Theme.'/images/printer.png" title="' . _('Print') . '" alt="" />' . ' ' . _('Print Profit and Loss Report') . '
		</p>';
	echo '<div class="page_help_text">' . _('Profit and loss statement (P&amp;L), also called an Income Statement, or Statement of Operations, this is the statement that indicates how the revenue (money received from the sale of products and services before expenses are taken out, also known as the "top line") is transformed into the net income (the result after all revenues and expenses have been accounted for, also known as the "bottom line").') .
		'<br />'
		. _('The purpose of the income statement is to show whether the company made or lost money during the period being reported.') . '<br />'
		. _('The P&amp;L represents a period of time. This contrasts with the Balance Sheet, which represents a single moment in time.') . '<br />'
		. _('EMP is an "accrual" based system (not a "cash based" system).  Accrual systems include items when they are invoiced to the customer, and when expenses are owed based on the supplier invoice date.') . '</div>';

	echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	echo '<div>';
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	
	if (Date('m') > $_SESSION['YearEnd']){
		/*Dates in SQL format */
		$DefaultFromDate = Date ('Y-m-d', Mktime(0,0,0,$_SESSION['YearEnd'] + 2,0,Date('Y')));
		$FromDate = Date($_SESSION['DefaultDateFormat'], Mktime(0,0,0,$_SESSION['YearEnd'] + 2,0,Date('Y')));
	} else {
		$DefaultFromDate = Date ('Y-m-d', Mktime(0,0,0,$_SESSION['YearEnd'] + 2,0,Date('Y')-1));
		$FromDate = Date($_SESSION['DefaultDateFormat'], Mktime(0,0,0,$_SESSION['YearEnd'] + 2,0,Date('Y')-1));
	}
	$period=GetPeriod($FromDate);
	
	/*Show a form to allow input of criteria for profit and loss to show */
	echo '<br /><table class="selection">
		<tr><td>' . _('Select Period From') . ':</td>
		<td><select name="FromPeriod">';
	    
	$sql = "SELECT periodno,
		lastdate_in_period
		FROM periods
		ORDER BY periodno DESC";
	$Periods = DB_query($sql);
	
	while ($myrow=DB_fetch_array($Periods)){
		if(isset($_POST['FromPeriod']) AND $_POST['FromPeriod']!=''){
			if( $_POST['FromPeriod']== $myrow['periodno']){
				echo '<option selected="selected" value="' . $myrow['periodno'] . '">' .MonthAndYearFromSQLDate($myrow['lastdate_in_period']) . '</option>';
			} else {
				echo '<option value="' . $myrow['periodno'] . '">' . MonthAndYearFromSQLDate($myrow['lastdate_in_period']) . '</option>';
			}
		} else {
			if($myrow['lastdate_in_period']==$DefaultFromDate){
				echo '<option selected="selected" value="' . $myrow['periodno'] . '">' . MonthAndYearFromSQLDate($myrow['lastdate_in_period']) . '</option>';
			} else {
				echo '<option value="' . $myrow['periodno'] . '">' . MonthAndYearFromSQLDate($myrow['lastdate_in_period']) . '</option>';
			}
		}
	}
	
	echo '</select></td>
		</tr>';
	if (!isset($_POST['ToPeriod']) OR $_POST['ToPeriod']==''){
		$LastDate = date('Y-m-d',mktime(0,0,0,Date('m')+1,0,Date('Y')));
		$sql = "SELECT periodno FROM periods where lastdate_in_period = '" . $LastDate . "'";
		$MaxPrd = DB_query($sql);
		$MaxPrdrow = DB_fetch_row($MaxPrd);
		$DefaultToPeriod = (int) ($MaxPrdrow[0]);
	} else {
		$DefaultToPeriod = $_POST['ToPeriod'];
	}
	
	echo '<tr>
		<td>' . _('Select Period To') . ':</td>
		<td><select name="ToPeriod">';
		
	$RetResult = DB_data_seek($Periods,0);
	
	while ($myrow=DB_fetch_array($Periods)){
		if($myrow['periodno']==$DefaultToPeriod){
			echo '<option selected="selected" value="' . $myrow['periodno'] . '">' . MonthAndYearFromSQLDate($myrow['lastdate_in_period']) . '</option>';
		} else {
			echo '<option value="' . $myrow['periodno'] . '">' . MonthAndYearFromSQLDate($myrow['lastdate_in_period']) . '</option>';
		}
	}
	echo '</select></td></tr>';
	
	echo '<tr>
			<td>Display non-zero records only</td>
			<td><input type="checkbox" name="nonZeroRecordsOnly" /></td>
		</tr>';
	
	echo '</table>
		<br />
		<div class="centre">
			<input type="submit" name="ShowPL" value="' ._('Show on Screen (HTML)') . '" />
		</div>
		<br />';
	
	echo '<div class="centre">
			<p>
			Report Title : <input type="text" name="PDFTitle" />
			<input type="checkbox" name="overwritePRDTitle" />
			</p>
			<p>Tick checkbox to overwrite default title</p>
			<br />
			<input type="submit" name="PrintPDF" value="'._('Produce PDF Report').'" />
		</div>';
	
	/*Now do the posting while the user is thinking about the period to select */
	include ('includes/GLPostings.php');
}
else if(isset($_POST['PrintPDF']))
{
	$NumberOfMonths = $_POST['ToPeriod'] - $_POST['FromPeriod'] + 1;

	if ($NumberOfMonths >12){
		
		include('includes/header.php');
		echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
		echo '<div>';
		echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
				<input type="hidden" name="FromPeriod" value="' . $_POST['FromPeriod'] . '" />
				<input type="hidden" name="ToPeriod" value="' . $_POST['ToPeriod'] . '" />';
		echo '<br />';
		prnMsg(_('A period up to 12 months in duration can be specified') . ' - ' . _('the system automatically shows a comparative for the same period from the previous year') . ' - ' . _('it cannot do this if a period of more than 12 months is specified') . '. ' . _('Please select an alternative period range'),'error');
		include('includes/footer.php');
		exit;
	}
	
	require_once('includes/tcpdf/config/tcpdf_config.php');
	require_once('includes/tcpdf/tcpdf.php');
	
	// create new PDF document
	$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
	
	// set margins
	$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
	$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
	$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
	
	// set auto page breaks
	$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
	
	// set some language-dependent strings (optional)
	if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
	    require_once(dirname(__FILE__).'/lang/eng.php');
	    $pdf->setLanguageArray($l);
	}

	// set font
	// $pdf->SetFont('dejavusans', '', 10);
	
	// add a page
	$pdf->AddPage();
	
	$sql = "SELECT lastdate_in_period FROM periods WHERE periodno='" . $_POST['ToPeriod'] . "'";
	$PrdResult = DB_query($sql);
	$myrow = DB_fetch_row($PrdResult);
	$PeriodToDate = MonthAndYearFromSQLDate($myrow[0]);
	
	/*summary */
	$TableHeader = '<tr>
				<th colspan="2"></th>
				<th colspan="2" style="text-align:right">' . _('Period Actual') .'</th>
				<th colspan="2" style="text-align:right">' . _('Period Budget') . '</th>
				<th colspan="2" style="text-align:right">' . _('Last Year') . '</th>
			</tr>';
	
	$j=0;
		
	$Section='';
	$SectionPrdActual= 0;
	$SectionPrdLY 	 = 0;
	$SectionPrdBudget= 0;
	
	$SectionType = '';
	
	$PeriodProfitLoss = 0;
	$PeriodProfitLoss = 0;
	$PeriodLYProfitLoss = 0;
	$PeriodBudgetProfitLoss = 0;
	
	$TotalIncome=0;
	$TotalBudgetIncome=0;
	$TotalLYIncome=0;
	
	$AccountPeriodActual = 0;
	$AccountPeriodLY = 0;
	$AccountPeriodBudget = 0;

	$SQL = "SELECT accountgroups.sectioninaccounts,
				accountgroups.parentgroupname,
				accountgroups.groupname,
				chartdetails.accountcode,
				chartmaster.accountname,
				emp_accountsection.type,
				SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwd ELSE 0 END) AS firstprdbfwd,
				SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwdbudget ELSE 0 END) AS firstprdbudgetbfwd,
				SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lastprdcfwd,
				SUM(CASE WHEN chartdetails.period='" . ($_POST['FromPeriod'] - 12) . "' THEN chartdetails.bfwd ELSE 0 END) AS lyfirstprdbfwd,
				SUM(CASE WHEN chartdetails.period='" . ($_POST['ToPeriod']-12) . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lylastprdcfwd,
				SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwdbudget + chartdetails.budget ELSE 0 END) AS lastprdbudgetcfwd
		FROM accountgroups LEFT JOIN chartmaster
		ON chartmaster.group_ = accountgroups.groupname LEFT JOIN chartdetails
		ON chartmaster.accountcode = chartdetails.accountcode LEFT JOIN emp_accountsection
		ON accountgroups.sectioninaccounts = emp_accountsection.sectionid
		WHERE accountgroups.pandl=1
		GROUP BY accountgroups.sectioninaccounts
		ORDER BY emp_accountsection.type, accountgroups.sectioninaccounts";
	
	$AccountsResult = DB_query($SQL,_('No general ledger accounts were returned by the SQL because'),_('The SQL that failed was'));
	
	$html = "<h2>" . stripslashes($_SESSION['CompanyRecord']['coyname']) . "</h2>";
	
	if(isset($_POST['overwritePRDTitle']))
	{
		$html = $html . "<p>" . $_POST['PDFTitle'] . "</p>";
	}
	else
	{
		$html = $html . '<p>'. _('Statement of Profit and Loss for the') . ' ' . $NumberOfMonths . ' ' . _('months to') . ' and including ' . $PeriodToDate . '</p>';
	}
	
	$html = $html . '<table>';
	
	while ($myrow=DB_fetch_array($AccountsResult)) {
		
		if(($Section!=1) AND ($Section!=2) AND $SectionType != $myrow['type'] AND $SectionType != '' AND $SectionType > 0)
		{
			$html = $html . sprintf('<tr style="background-color:#ffffff">
						<td colspan="2"><b>'._('Profit / (Loss)'). ' ' . $SectionTypes[$SectionType] .'</b></td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
					</tr>',
					locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']) );
			
			$html = $html . sprintf('<tr style="background-color:#ffffff">
						<td colspan="2"><i>'._('Profit/(Loss) Margin').' ' . $SectionTypes[$SectionType] .'</i></td>
						<td colspan="2" style="text-align:right"><i>%s</i></td>
						<td colspan="2" style="text-align:right"><i>%s</i></td>
						<td colspan="2" style="text-align:right"><i>%s</i></td>
						</tr><tr><td colspan="6"> </td>
					</tr>',
					locale_number_format($PrdNPPercent,1) . '%',
					locale_number_format($BudgetNPPercent,1) . '%',
					locale_number_format($LYNPPercent,1). '%');
		}
		
		$Section = $myrow['sectioninaccounts'];
		
		$SectionType = $myrow['type'];
		
		$SectionPrdLY = $myrow['lylastprdcfwd'] - $myrow['lyfirstprdbfwd'];
		$SectionPrdActual = $myrow['lastprdcfwd'] - $myrow['firstprdbfwd'];
		$SectionPrdBudget = $myrow['lastprdbudgetcfwd'] - $myrow['firstprdbudgetbfwd'];
		
		if(isset($_POST['nonZeroRecordsOnly']) AND $SectionPrdLY==0 AND $SectionPrdActual==0 AND $SectionPrdBudget==0)
		{
			continue;
		}
		
		$PeriodProfitLoss += $SectionPrdActual;
		$PeriodLYProfitLoss += $SectionPrdLY;
		$PeriodBudgetProfitLoss += $SectionPrdBudget;
		
		if($j==0)
		{
			$html = $html . $TableHeader;
			$j++;
		}
		
		if ($Section==1) { /*Income*/
			$html = $html . sprintf('<tr style="background-color:#ffffff">
						<td colspan="2"><b>%s</b></td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						</tr>',
						$Sections[$Section],
						locale_number_format(-$SectionPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format(-$SectionPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format(-$SectionPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
			
			$TotalIncome = -$SectionPrdActual;
			$TotalBudgetIncome = -$SectionPrdBudget;
			$TotalLYIncome = -$SectionPrdLY;
		}
		else {
			$html = $html . sprintf('<tr>
						<td colspan="2"><b>%s</b></td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						</tr>',
						$Sections[$Section],
						locale_number_format($SectionPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format($SectionPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format($SectionPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
		}
		
		if ($Section==2){ /*Cost of Sales - need sub total for Gross Profit*/
			$html = $html . sprintf('<tr style="background-color:#ffffff">
						<td colspan="2"><b>'._('Gross Profit').'</b></td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						<td colspan="2" style="text-align:right">%s</td>
						</tr>',
						locale_number_format($TotalIncome - $SectionPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format($TotalBudgetIncome - $SectionPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format($TotalLYIncome - $SectionPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
			
			if ($TotalIncome !=0){
				$PrdGPPercent = 100*($TotalIncome - $SectionPrdActual)/$TotalIncome;
			} else {
				$PrdGPPercent =0;
			}
			if ($TotalBudgetIncome !=0){
				$BudgetGPPercent = 100*($TotalBudgetIncome - $SectionPrdBudget)/$TotalBudgetIncome;
			} else {
				$BudgetGPPercent =0;
			}
			if ($TotalLYIncome !=0){
				$LYGPPercent = 100*($TotalLYIncome - $SectionPrdLY)/$TotalLYIncome;
			} else {
				$LYGPPercent = 0;
			}
			
			$html = $html . sprintf('<tr style="background-color:#ffffff">
						<td colspan="2"><i>'._('Gross Profit Margin').'</i></td>
						<td colspan="2" style="text-align:right"><i>%s</i></td>
						<td colspan="2" style="text-align:right"><i>%s</i></td>
						<td colspan="2" style="text-align:right"><i>%s</i></td>
						</tr><tr><td colspan="6"> </td></tr>',
						locale_number_format($PrdGPPercent,1) . '%',
						locale_number_format($BudgetGPPercent,1) . '%',
						locale_number_format($LYGPPercent,1). '%');
		}
		
		if (($Section!=1) AND ($Section!=2)){
			
			if ($TotalIncome !=0){
				$PrdNPPercent = 100*(-$PeriodProfitLoss)/$TotalIncome;
			} else {
				$PrdNPPercent =0;
			}
			if ($TotalBudgetIncome !=0){
				$BudgetNPPercent=100*(-$PeriodBudgetProfitLoss)/$TotalBudgetIncome;
			} else {
				$BudgetNPPercent=0;
			}
			if ($TotalLYIncome !=0){
				$LYNPPercent = 100*(-$PeriodLYProfitLoss)/$TotalLYIncome;
			} else {
				$LYNPPercent = 0;
			}
		}
	}
	
	if($SectionType != '' && $SectionType > 0)
	{
		$html = $html . sprintf('<tr style="background-color:#ffffff">
					<td colspan="2"><b>'._('Profit / (Loss)'). ' ' . $SectionTypes[$SectionType] .'</b></td>
					<td colspan="2" style="text-align:right">%s</td>
					<td colspan="2" style="text-align:right">%s</td>
					<td colspan="2" style="text-align:right">%s</td>
				</tr>',
				locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
				locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
				locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']) );
		
		$html = $html . sprintf('<tr style="background-color:#ffffff">
					<td colspan="2"><i>'._('Profit/(Loss) Margin').' ' . $SectionTypes[$SectionType] .'</i></td>
					<td colspan="2" style="text-align:right"><i>%s</i></td>
					<td colspan="2" style="text-align:right"><i>%s</i></td>
					<td colspan="2" style="text-align:right"><i>%s</i></td>
					</tr><tr><td colspan="6"> </td>
				</tr>',
				locale_number_format($PrdNPPercent,1) . '%',
				locale_number_format($BudgetNPPercent,1) . '%',
				locale_number_format($LYNPPercent,1). '%');
	}
	
	$html = $html . sprintf('<tr style="background-color:#ffffff">
			<td colspan="2"><b>'._('Profit / (Loss)').'</b></td>
			<td colspan="2" style="text-align:right">%s</td>
			<td colspan="2" style="text-align:right">%s</td>
			<td colspan="2" style="text-align:right">%s</td>
		</tr>',
		locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
		locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
		locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']) );
	
	$html = $html . sprintf('<tr style="background-color:#ffffff">
			<td colspan="2"><i>'._('Net Profit Margin').'</i></td>
			<td colspan="2" style="text-align:right"><i>%s</i></td>
			<td colspan="2" style="text-align:right"><i>%s</i></td>
			<td colspan="2" style="text-align:right"><i>%s</i></td>
			</tr><tr><td colspan="6"> </td>
		</tr>',
		locale_number_format($PrdNPPercent,1) . '%',
		locale_number_format($BudgetNPPercent,1) . '%',
		locale_number_format($LYNPPercent,1). '%');
	
	$html = $html . "</table>";
	
	//echo $html;
	
	$pdf->writeHTML($html, true, false, true, false, '');
	// output the HTML content
	$pdf->Output('example_006.pdf', 'I');
	exit;
}
else {
	
	include('includes/header.php');
	echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8') . '">';
	echo '<div>';
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />
			<input type="hidden" name="FromPeriod" value="' . $_POST['FromPeriod'] . '" />
			<input type="hidden" name="ToPeriod" value="' . $_POST['ToPeriod'] . '" />';

	$NumberOfMonths = $_POST['ToPeriod'] - $_POST['FromPeriod'] + 1;

	if ($NumberOfMonths >12){
		echo '<br />';
		prnMsg(_('A period up to 12 months in duration can be specified') . ' - ' . _('the system automatically shows a comparative for the same period from the previous year') . ' - ' . _('it cannot do this if a period of more than 12 months is specified') . '. ' . _('Please select an alternative period range'),'error');
		include('includes/footer.php');
		exit;
	}
	
	$sql = "SELECT lastdate_in_period FROM periods WHERE periodno='" . $_POST['ToPeriod'] . "'";
	$PrdResult = DB_query($sql);
	$myrow = DB_fetch_row($PrdResult);
	$PeriodToDate = MonthAndYearFromSQLDate($myrow[0]);
	
	
	/*summary */
	$TableHeader = '<tr>
				<th colspan="2"></th>
				<th colspan="2">' . _('Period Actual') .'</th>
				<th colspan="2">' . _('Period Budget') . '</th>
				<th colspan="2">' . _('Last Year') . '</th>
			</tr>';
	
	$j=0;
		
	$Section='';
	$SectionPrdActual= 0;
	$SectionPrdLY 	 = 0;
	$SectionPrdBudget= 0;
	
	$SectionType = '';
	
	$PeriodProfitLoss = 0;
	$PeriodProfitLoss = 0;
	$PeriodLYProfitLoss = 0;
	$PeriodBudgetProfitLoss = 0;
	
	$TotalIncome=0;
	$TotalBudgetIncome=0;
	$TotalLYIncome=0;
	
	$AccountPeriodActual = 0;
	$AccountPeriodLY = 0;
	$AccountPeriodBudget = 0;
	
	if(isset($_POST['ShowPL']))
	{
		$SQL = "SELECT accountgroups.sectioninaccounts,
					accountgroups.parentgroupname,
					accountgroups.groupname,
					chartdetails.accountcode,
					chartmaster.accountname,
					emp_accountsection.type,
					SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwd ELSE 0 END) AS firstprdbfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwdbudget ELSE 0 END) AS firstprdbudgetbfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lastprdcfwd,
					SUM(CASE WHEN chartdetails.period='" . ($_POST['FromPeriod'] - 12) . "' THEN chartdetails.bfwd ELSE 0 END) AS lyfirstprdbfwd,
					SUM(CASE WHEN chartdetails.period='" . ($_POST['ToPeriod']-12) . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lylastprdcfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwdbudget + chartdetails.budget ELSE 0 END) AS lastprdbudgetcfwd
			FROM accountgroups LEFT JOIN chartmaster
			ON chartmaster.group_ = accountgroups.groupname LEFT JOIN chartdetails
			ON chartmaster.accountcode = chartdetails.accountcode LEFT JOIN emp_accountsection
			ON accountgroups.sectioninaccounts = emp_accountsection.sectionid
			WHERE accountgroups.pandl=1
			GROUP BY accountgroups.sectioninaccounts
			ORDER BY emp_accountsection.type, accountgroups.sectioninaccounts";
		
		$AccountsResult = DB_query($SQL,_('No general ledger accounts were returned by the SQL because'),_('The SQL that failed was'));
		
		echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('General Ledger Profit Loss Inquiry') . '" alt="" />' . ' ' . _('Statement of Profit and Loss for the') . ' ' . $NumberOfMonths . ' ' . _('months to') . ' and including ' . $PeriodToDate . '</p>';
		echo '<table class="selection">';
		
		while ($myrow=DB_fetch_array($AccountsResult)) {
			
			if(($Section!=1) AND ($Section!=2) AND $SectionType != $myrow['type'] AND $SectionType != '' AND $SectionType > 0)
			{
				printf('<tr style="background-color:#ffffff">
							<td colspan="2"><b>'._('Profit / (Loss)'). ' ' . $SectionTypes[$SectionType] .'</b></td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
						</tr>',
						locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']) );
				
				
				printf('<tr style="background-color:#ffffff">
							<td colspan="2"><i>'._('Profit/(Loss) Margin').' ' . $SectionTypes[$SectionType] .'</i></td>
							<td colspan="2" class="number"><i>%s</i></td>
							<td colspan="2" class="number"><i>%s</i></td>
							<td colspan="2" class="number"><i>%s</i></td>
							</tr><tr><td colspan="6"> </td>
						</tr>',
						locale_number_format($PrdNPPercent,1) . '%',
						locale_number_format($BudgetNPPercent,1) . '%',
						locale_number_format($LYNPPercent,1). '%');
			}
			
			$Section = $myrow['sectioninaccounts'];
			
			$SectionType = $myrow['type'];
			
			$SectionPrdLY = $myrow['lylastprdcfwd'] - $myrow['lyfirstprdbfwd'];
			$SectionPrdActual = $myrow['lastprdcfwd'] - $myrow['firstprdbfwd'];
			$SectionPrdBudget = $myrow['lastprdbudgetcfwd'] - $myrow['firstprdbudgetbfwd'];
			
			if(isset($_POST['nonZeroRecordsOnly']) AND $SectionPrdLY==0 AND $SectionPrdActual==0 AND $SectionPrdBudget==0)
			{
				continue;
			}
			
			$PeriodProfitLoss += $SectionPrdActual;
			$PeriodLYProfitLoss += $SectionPrdLY;
			$PeriodBudgetProfitLoss += $SectionPrdBudget;
			
			if($j==0)
			{
				echo $TableHeader;
				$j++;
			}
			
			if ($Section==1) { /*Income*/
				printf('<tr style="background-color:#ffffff">
							<td colspan="2"><a href="%s?from=%s&to=%s&section=%s&nonzero=%s"><b>%s</b></a></td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2"class="number">%s</td>
							</tr>',
							$_SERVER["PHP_SELF"],
							$_POST['FromPeriod'],
							$_POST['ToPeriod'],
							1,
							isset($_POST['nonZeroRecordsOnly'])?1:0,
							$Sections[$Section],
							locale_number_format(-$SectionPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format(-$SectionPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format(-$SectionPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
							
				$TotalIncome = -$SectionPrdActual;
				$TotalBudgetIncome = -$SectionPrdBudget;
				$TotalLYIncome = -$SectionPrdLY;
			}
			else {
				printf('<tr>
							<td colspan="2"><a href="%s?from=%s&to=%s&section=%s&nonzero=%s"><b>%s</b></a></td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							</tr>',
							$_SERVER["PHP_SELF"],
							$_POST['FromPeriod'],
							$_POST['ToPeriod'],
							$Section,
							isset($_POST['nonZeroRecordsOnly'])?1:0,
							$Sections[$Section],
							locale_number_format($SectionPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format($SectionPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format($SectionPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
			}
			
			if ($Section==2){ /*Cost of Sales - need sub total for Gross Profit*/
				printf('<tr style="background-color:#ffffff">
							<td colspan="2"><b>'._('Gross Profit').'</b></td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							</tr>',
							locale_number_format($TotalIncome - $SectionPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format($TotalBudgetIncome - $SectionPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format($TotalLYIncome - $SectionPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
				
				if ($TotalIncome !=0){
					$PrdGPPercent = 100*($TotalIncome - $SectionPrdActual)/$TotalIncome;
				} else {
					$PrdGPPercent =0;
				}
				if ($TotalBudgetIncome !=0){
					$BudgetGPPercent = 100*($TotalBudgetIncome - $SectionPrdBudget)/$TotalBudgetIncome;
				} else {
					$BudgetGPPercent =0;
				}
				if ($TotalLYIncome !=0){
					$LYGPPercent = 100*($TotalLYIncome - $SectionPrdLY)/$TotalLYIncome;
				} else {
					$LYGPPercent = 0;
				}
				
				printf('<tr style="background-color:#ffffff">
							<td colspan="2"><i>'._('Gross Profit Margin').'</i></td>
							<td colspan="2" class="number"><i>%s</i></td>
							<td colspan="2" class="number"><i>%s</i></td>
							<td colspan="2" class="number"><i>%s</i></td>
							</tr><tr><td colspan="6"> </td></tr>',
							locale_number_format($PrdGPPercent,1) . '%',
							locale_number_format($BudgetGPPercent,1) . '%',
							locale_number_format($LYGPPercent,1). '%');
			}
			
			if (($Section!=1) AND ($Section!=2)){
				
				if ($TotalIncome !=0){
					$PrdNPPercent = 100*(-$PeriodProfitLoss)/$TotalIncome;
				} else {
					$PrdNPPercent =0;
				}
				if ($TotalBudgetIncome !=0){
					$BudgetNPPercent=100*(-$PeriodBudgetProfitLoss)/$TotalBudgetIncome;
				} else {
					$BudgetNPPercent=0;
				}
				if ($TotalLYIncome !=0){
					$LYNPPercent = 100*(-$PeriodLYProfitLoss)/$TotalLYIncome;
				} else {
					$LYNPPercent = 0;
				}
			}
		}
		
		if($SectionType != '' && $SectionType > 0)
		{
			printf('<tr style="background-color:#ffffff">
						<td colspan="2"><b>'._('Profit / (Loss)'). '  ' . $SectionTypes[$SectionType] .'</b></td>
						<td colspan="2" class="number">%s</td>
						<td colspan="2" class="number">%s</td>
						<td colspan="2" class="number">%s</td>
					</tr>',
					locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']) );
			
			
			printf('<tr style="background-color:#ffffff">
						<td colspan="2"><i>'._('Profit/(Loss) Margin').' ' . $SectionTypes[$SectionType] .'</i></td>
						<td colspan="2" class="number"><i>%s</i></td>
						<td colspan="2" class="number"><i>%s</i></td>
						<td colspan="2" class="number"><i>%s</i></td>
						</tr><tr><td colspan="6"> </td>
					</tr>',
					locale_number_format($PrdNPPercent,1) . '%',
					locale_number_format($BudgetNPPercent,1) . '%',
					locale_number_format($LYNPPercent,1). '%');
		}
		
		printf('<tr style="background-color:#ffffff">
				<td colspan="2"><b>'._('Profit / (Loss)').'</b></td>
				<td colspan="2" class="number">%s</td>
				<td colspan="2" class="number">%s</td>
				<td colspan="2" class="number">%s</td>
			</tr>',
			locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
			locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
			locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']) );
		
		printf('<tr style="background-color:#ffffff">
				<td colspan="2"><i>'._('Net Profit Margin').'</i></td>
				<td colspan="2" class="number"><i>%s</i></td>
				<td colspan="2" class="number"><i>%s</i></td>
				<td colspan="2" class="number"><i>%s</i></td>
				</tr><tr><td colspan="6"> </td>
			</tr>',
			locale_number_format($PrdNPPercent,1) . '%',
			locale_number_format($BudgetNPPercent,1) . '%',
			locale_number_format($LYNPPercent,1). '%');
		
	}
	else if(isset($_GET['section']))
	{
		$SQL = "SELECT accountgroups.sectioninaccounts,
					accountgroups.parentgroupname,
					accountgroups.groupname,
					chartdetails.accountcode,
					chartmaster.accountname,
					SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwd ELSE 0 END) AS firstprdbfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwdbudget ELSE 0 END) AS firstprdbudgetbfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lastprdcfwd,
					SUM(CASE WHEN chartdetails.period='" . ($_POST['FromPeriod'] - 12) . "' THEN chartdetails.bfwd ELSE 0 END) AS lyfirstprdbfwd,
					SUM(CASE WHEN chartdetails.period='" . ($_POST['ToPeriod']-12) . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lylastprdcfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwdbudget + chartdetails.budget ELSE 0 END) AS lastprdbudgetcfwd
			FROM accountgroups LEFT JOIN chartmaster
			ON chartmaster.group_ = accountgroups.groupname LEFT JOIN chartdetails
			ON chartmaster.accountcode = chartdetails.accountcode
			WHERE accountgroups.pandl=1 AND accountgroups.sectioninaccounts = '".$_GET['section']."' AND accountgroups.parentgroupname = ''
			GROUP BY accountgroups.groupname
			ORDER BY accountgroups.sequenceintb,
				accountgroups.groupname";
				
		$AccountsResult = DB_query($SQL,_('No general ledger accounts were returned by the SQL because'),_('The SQL that failed was'));
		
		echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('General Ledger Profit Loss Inquiry') . '" alt="" />' . ' ' . _('Statement of Profit and Loss for the') . ' ' . $NumberOfMonths . ' ' . _('months to') . ' and including ' . $PeriodToDate . '</p>';
		echo '<table class="selection">';
		
		while ($myrow=DB_fetch_array($AccountsResult)) {
			
			$AccountPeriodActual = 0;
			$AccountPeriodLY = 0;
			$AccountPeriodBudget = 0;
			
			$data = getChildGroups ($db, $myrow['groupname']);
			
			$AccountPeriodActual = $data[0];
			$AccountPeriodLY = $data[1];
			$AccountPeriodBudget = $data[2];
			
			$GrpPrdActual = $myrow['lastprdcfwd'] - $myrow['firstprdbfwd'] + $AccountPeriodActual;
			$GrpPrdBudget = $myrow['lastprdbudgetcfwd'] - $myrow['firstprdbudgetbfwd'] + $AccountPeriodBudget;
			$GrpPrdLY = $myrow['lylastprdcfwd'] - $myrow['lyfirstprdbfwd'] + $AccountPeriodLY;
			
			if(isset($_POST['nonZeroRecordsOnly']) AND $GrpPrdActual==0 AND $GrpPrdBudget==0 AND $GrpPrdLY==0)
			{
				continue;
			}
			
			$PeriodProfitLoss += $GrpPrdActual;
			$PeriodLYProfitLoss += $GrpPrdLY;
			$PeriodBudgetProfitLoss += $GrpPrdBudget;
			
			if($j==0)
			{
				echo $TableHeader;
				$j++;
			}
			
			$ActGrpLabel = $myrow['groupname'];
			$Section = $myrow['sectioninaccounts'];
			
			if ($Section ==1){ //Income
				printf('<tr>
						<td colspan="2"><a href="%s?from=%s&to=%s&group=%s&nonzero=%s"><i>%s</i></a></td>
						<td></td>
						<td class="number">%s</td>
						<td></td>
						<td class="number">%s</td>
						<td></td>
						<td class="number">%s</td>
						</tr>',
						$_SERVER["PHP_SELF"],
						$_POST['FromPeriod'],
						$_POST['ToPeriod'],
						$ActGrpLabel,
						isset($_POST['nonZeroRecordsOnly'])?1:0,
						$ActGrpLabel,
						locale_number_format(-$GrpPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format(-$GrpPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format(-$GrpPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
			} else { //Costs
				printf('<tr>
						<td colspan="2"><a href="%s?from=%s&to=%s&group=%s&nonzero=%s"><i>%s</i></a></td>
						<td class="number">%s</td>
						<td></td>
						<td class="number">%s</td>
						<td></td>
						<td class="number">%s</td>
						<td></td>
						</tr>',
						$_SERVER["PHP_SELF"],
						$_POST['FromPeriod'],
						$_POST['ToPeriod'],
						$ActGrpLabel,
						isset($_POST['nonZeroRecordsOnly'])?1:0,
						$ActGrpLabel,
						locale_number_format($GrpPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format($GrpPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
						locale_number_format($GrpPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
			}
		}
		
		if($Section == 1)
		{
			printf('<tr style="background-color:#ffffff">
				<td colspan="2"><b>%s</b></td>
				<td colspan="2" class="number">%s</td>
				<td colspan="2" class="number">%s</td>
				<td colspan="2" class="number">%s</td>
				</tr>',
				$Sections[$Section] . ' ' . _('Total'),
				locale_number_format(-$PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
				locale_number_format(-$PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
				locale_number_format(-$PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']));
		}
		else
		{
			printf('<tr style="background-color:#ffffff">
				<td colspan="2"><b>%s</b></td>
				<td colspan="2" class="number">%s</td>
				<td colspan="2" class="number">%s</td>
				<td colspan="2" class="number">%s</td>
				</tr>',
				$Sections[$Section] . ' ' . _('Total'),
				locale_number_format($PeriodProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
				locale_number_format($PeriodBudgetProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']),
				locale_number_format($PeriodLYProfitLoss,$_SESSION['CompanyRecord']['decimalplaces']));
		}
	}
	else if (isset($_GET['group']))
	{
		$SQL = "SELECT accountgroups.sectioninaccounts,
					accountgroups.parentgroupname,
					accountgroups.groupname,
					chartdetails.accountcode,
					chartmaster.accountname,
					SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwd ELSE 0 END) AS firstprdbfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwdbudget ELSE 0 END) AS firstprdbudgetbfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lastprdcfwd,
					SUM(CASE WHEN chartdetails.period='" . ($_POST['FromPeriod'] - 12) . "' THEN chartdetails.bfwd ELSE 0 END) AS lyfirstprdbfwd,
					SUM(CASE WHEN chartdetails.period='" . ($_POST['ToPeriod']-12) . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lylastprdcfwd,
					SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwdbudget + chartdetails.budget ELSE 0 END) AS lastprdbudgetcfwd
			FROM accountgroups LEFT JOIN chartmaster
			ON chartmaster.group_ = accountgroups.groupname LEFT JOIN chartdetails
			ON chartmaster.accountcode = chartdetails.accountcode
			WHERE accountgroups.pandl=1 AND accountgroups.groupname = '".$_GET['group']."'
			GROUP BY chartdetails.accountcode
			ORDER BY accountgroups.parentgroupname,
				accountgroups.sequenceintb,
				accountgroups.groupname";
				
		$AccountsResult = DB_query($SQL,_('No general ledger accounts were returned by the SQL because'),_('The SQL that failed was'));
		
		echo '<p class="page_title_text"><img src="'.$RootPath.'/css/'.$Theme.'/images/transactions.png" title="' . _('General Ledger Profit Loss Inquiry') . '" alt="" />' . ' ' . _('Statement of Profit and Loss for the') . ' ' . $NumberOfMonths . ' ' . _('months to') . ' and including ' . $PeriodToDate . '</p>';
		echo '<table class="selection">';
		
		while ($myrow=DB_fetch_array($AccountsResult)) {
			
			$Section = $myrow['sectioninaccounts'];
			
			if($myrow['accountcode'] == '')
			{
				$TableHeader = '<tr>
							<th colspan="2"></th>
							<th colspan="2">' . _('Period Actual') .'</th>
							<th colspan="2">' . _('Period Budget') . '</th>
							<th colspan="2">' . _('Last Year') . '</th>
						</tr>';
						
				if($z==0)
				{
					echo $TableHeader;
					$z++;
				}
				
				$data = getChild ($db, $myrow['groupname']);
				
				$AccountPeriodActual = $data[0];
				$AccountPeriodLY = $data[1];
				$AccountPeriodBudget = $data[2];
				
				$PeriodProfitLoss += $AccountPeriodActual;
				$PeriodLYProfitLoss += $AccountPeriodLY;
				$PeriodBudgetProfitLoss += $AccountPeriodBudget;
			}
			else
			{
				$TableHeader = '<tr>
							<th>' . _('Account') . '</th>
							<th>'._('Account Name') .'</th>
							<th colspan="2">' . _('Period Actual') .'</th>
							<th colspan="2">' . _('Period Budget') .'</th>
							<th colspan="2">' . _('Last Year') . '</th>
						</tr>';
						
				
				
				$AccountPeriodActual = $myrow['lastprdcfwd'] - $myrow['firstprdbfwd'];
				$AccountPeriodLY = $myrow['lylastprdcfwd'] - $myrow['lyfirstprdbfwd'];
				$AccountPeriodBudget = $myrow['lastprdbudgetcfwd'] - $myrow['firstprdbudgetbfwd'];
				
				if(isset($_POST['nonZeroRecordsOnly']) AND $AccountPeriodActual==0 AND $AccountPeriodLY==0 AND $AccountPeriodBudget==0)
				{
					continue;
				}
				
				if($x==0)
				{
					echo $TableHeader;
					$x++;
				}
				
				if ($k==1){
					echo '<tr class="EvenTableRows">';
					$k=0;
				} else {
					echo '<tr class="OddTableRows">';
					$k++;
				}
	
				$ActEnquiryURL = '<a href="' . $RootPath . '/GLAccountInquiry.php?Period=' . $_POST['ToPeriod'] . '&amp;Account=' . $myrow['accountcode'] . '&amp;Show=Yes">' . $myrow['accountcode'] . '</a>';
	
				if ($Section == 1){
					 printf('<td>%s</td>
							<td>%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							</tr>',
							$ActEnquiryURL,
							htmlspecialchars($myrow['accountname'], ENT_QUOTES,'UTF-8', false),
							locale_number_format(-$AccountPeriodActual,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format(-$AccountPeriodBudget,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format(-$AccountPeriodLY,$_SESSION['CompanyRecord']['decimalplaces']));
				} else {
					printf('<td>%s</td>
							<td>%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							<td colspan="2" class="number">%s</td>
							</tr>',
							$ActEnquiryURL,
							htmlspecialchars($myrow['accountname'], ENT_QUOTES,'UTF-8', false),
							locale_number_format($AccountPeriodActual,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format($AccountPeriodBudget,$_SESSION['CompanyRecord']['decimalplaces']),
							locale_number_format($AccountPeriodLY,$_SESSION['CompanyRecord']['decimalplaces']));
				}
			}
		}
	}
	
	
	echo '</table>';
	echo '<br /><div class="centre"><input type="submit" name="SelectADifferentPeriod" value="' . _('Select A Different Period') . '" /></div>';
}

echo '</div>';
echo '</form>';
include('includes/footer.php');

function getChildGroups ($db, $ActGrp)
{
	$AccountPeriodActual = 0;
	$AccountPeriodLY = 0;
	$AccountPeriodBudget = 0;
		
	$SQL = "SELECT accountgroups.sectioninaccounts,
							accountgroups.parentgroupname,
							accountgroups.groupname,
							chartdetails.accountcode,
							chartmaster.accountname,
							SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwd ELSE 0 END) AS firstprdbfwd,
							SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwdbudget ELSE 0 END) AS firstprdbudgetbfwd,
							SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lastprdcfwd,
							SUM(CASE WHEN chartdetails.period='" . ($_POST['FromPeriod'] - 12) . "' THEN chartdetails.bfwd ELSE 0 END) AS lyfirstprdbfwd,
							SUM(CASE WHEN chartdetails.period='" . ($_POST['ToPeriod']-12) . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lylastprdcfwd,
							SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwdbudget + chartdetails.budget ELSE 0 END) AS lastprdbudgetcfwd
						FROM accountgroups LEFT JOIN chartmaster
						ON chartmaster.group_ = accountgroups.groupname LEFT JOIN chartdetails
						ON chartmaster.accountcode = chartdetails.accountcode
						WHERE accountgroups.pandl=1 AND accountgroups.parentgroupname = '".$ActGrp."'
						GROUP BY accountgroups.sectioninaccounts,
							accountgroups.parentgroupname,
							accountgroups.groupname,
							chartdetails.accountcode,
							chartmaster.accountname
						ORDER BY accountgroups.sectioninaccounts,
							accountgroups.sequenceintb,
							accountgroups.groupname,
							chartdetails.accountcode";
							
	$Result = DB_query($SQL,_('No general ledger accounts were returned by the SQL because'),_('The SQL that failed was'));
	while ($myrow=DB_fetch_array($Result))
	{
		$AccountPeriodActual += ($myrow['lastprdcfwd'] - $myrow['firstprdbfwd']);
		$AccountPeriodLY += ($myrow['lylastprdcfwd'] - $myrow['lyfirstprdbfwd']);
		$AccountPeriodBudget += ($myrow['lastprdbudgetcfwd'] - $myrow['firstprdbudgetbfwd']);
		
		if($myrow['groupname'] != "")
		{
			$data = getChildGroups ($db, $myrow['groupname']);
			
			$AccountPeriodActual += $data[0];
			$AccountPeriodLY += $data[1];
			$AccountPeriodBudget += $data[2];
		}
	}

	return array($AccountPeriodActual, $AccountPeriodLY, $AccountPeriodBudget);
}

function getChild ($db, $ActGrp)
{
	
	$SQL = "SELECT accountgroups.sectioninaccounts,
				accountgroups.parentgroupname,
				accountgroups.groupname,
				chartdetails.accountcode,
				chartmaster.accountname,
				SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwd ELSE 0 END) AS firstprdbfwd,
				SUM(CASE WHEN chartdetails.period='" . $_POST['FromPeriod'] . "' THEN chartdetails.bfwdbudget ELSE 0 END) AS firstprdbudgetbfwd,
				SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lastprdcfwd,
				SUM(CASE WHEN chartdetails.period='" . ($_POST['FromPeriod'] - 12) . "' THEN chartdetails.bfwd ELSE 0 END) AS lyfirstprdbfwd,
				SUM(CASE WHEN chartdetails.period='" . ($_POST['ToPeriod']-12) . "' THEN chartdetails.bfwd + chartdetails.actual ELSE 0 END) AS lylastprdcfwd,
				SUM(CASE WHEN chartdetails.period='" . $_POST['ToPeriod'] . "' THEN chartdetails.bfwdbudget + chartdetails.budget ELSE 0 END) AS lastprdbudgetcfwd
		FROM accountgroups LEFT JOIN chartmaster
		ON chartmaster.group_ = accountgroups.groupname LEFT JOIN chartdetails
		ON chartmaster.accountcode = chartdetails.accountcode
		WHERE accountgroups.pandl=1 AND accountgroups.parentgroupname = '".$ActGrp."'
		GROUP BY accountgroups.groupname
		ORDER BY accountgroups.sequenceintb,
			accountgroups.groupname";
			
	$AccountsResult = DB_query($SQL,_('No general ledger accounts were returned by the SQL because'),_('The SQL that failed was'));
	
	while ($myrow=DB_fetch_array($AccountsResult)) {
		
		$AccountPeriodActual = 0;
		$AccountPeriodLY = 0;
		$AccountPeriodBudget = 0;
		
		$data = getChildGroups ($db, $myrow['groupname']);
		
		$AccountPeriodActual = $data[0];
		$AccountPeriodLY = $data[1];
		$AccountPeriodBudget = $data[2];
		
		$GrpPrdActual = $myrow['lastprdcfwd'] - $myrow['firstprdbfwd'] + $AccountPeriodActual;
		$GrpPrdBudget = $myrow['lastprdbudgetcfwd'] - $myrow['firstprdbudgetbfwd'] + $AccountPeriodBudget;
		$GrpPrdLY = $myrow['lylastprdcfwd'] - $myrow['lyfirstprdbfwd'] + $AccountPeriodLY;
		
		if(isset($_POST['nonZeroRecordsOnly']) AND $GrpPrdActual==0 AND $GrpPrdBudget==0 AND $GrpPrdLY==0)
		{
			continue;
		}
		
		$PeriodProfitLoss += $GrpPrdActual;
		$PeriodLYProfitLoss += $GrpPrdLY;
		$PeriodBudgetProfitLoss += $GrpPrdBudget;
		
		$ActGrpLabel = $myrow['groupname'];
		
		$Section = $myrow['sectioninaccounts'];
		
		if ($Section ==1){ //Income
			printf('<tr>
					<td colspan="2"><a href="%s?from=%s&to=%s&group=%s&nonzero=%s"><i>%s </i></a></td>
					<td></td>
					<td class="number">%s</td>
					<td></td>
					<td class="number">%s</td>
					<td></td>
					<td class="number">%s</td>
					</tr>',
					$_SERVER["PHP_SELF"],
					$_POST['FromPeriod'],
					$_POST['ToPeriod'],
					$ActGrpLabel,
					isset($_POST['nonZeroRecordsOnly'])?1:0,
					$ActGrpLabel,
					locale_number_format(-$GrpPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format(-$GrpPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format(-$GrpPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
		} else { //Costs
			printf('<tr>
					<td colspan="2"><a href="%s?from=%s&to=%s&group=%s&nonzero=%s"><i>%s </i></a></td>
					<td class="number">%s</td>
					<td></td>
					<td class="number">%s</td>
					<td></td>
					<td class="number">%s</td>
					<td></td>
					</tr>',
					$_SERVER["PHP_SELF"],
					$_POST['FromPeriod'],
					$_POST['ToPeriod'],
					$ActGrpLabel,
					isset($_POST['nonZeroRecordsOnly'])?1:0,
					$ActGrpLabel,
					locale_number_format($GrpPrdActual,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format($GrpPrdBudget,$_SESSION['CompanyRecord']['decimalplaces']),
					locale_number_format($GrpPrdLY,$_SESSION['CompanyRecord']['decimalplaces']));
		}
	}
	
	return array($PeriodProfitLoss, $PeriodLYProfitLoss, $PeriodBudgetProfitLoss);
}