<?php
/**********************************************************************
    Copyright (C) FrontAccounting, LLC.
	Released under the terms of the GNU General Public License, GPL, 
	as published by the Free Software Foundation, either version 3 
	of the License, or (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
    See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
***********************************************************************/
$page_security = 'SA_GLANALYTIC';
// ----------------------------------------------------------------
// $ Revision:	2.0 $
// Creator:	Joe Hunt
// date_:	2005-05-19
// Title:	Trial Balance
// ----------------------------------------------------------------
$path_to_root="..";

include_once($path_to_root . "/includes/session.inc");
include_once($path_to_root . "/admin/db/fiscalyears_db.inc");
include_once($path_to_root . "/includes/ui.inc");
include_once($path_to_root . "/includes/date_functions.inc");
include_once($path_to_root . "/includes/data_checks.inc");
include_once($path_to_root . "/gl/includes/gl_db.inc");


function get_balance_rep($account, $dimension, $dimension2, $from, $to, $from_incl=true, $to_incl=true) 
{
	$from_date = date2sql($from);
	$to_date = date2sql($to);

	$sql = "SELECT	SUM(IF(amount >= 0, amount, 0)) as debit, 
					SUM(IF(amount < 0, -amount, 0)) as credit,
					SUM(amount) as balance 
		FROM ".TB_PREF."gl_trans trans,"
			.TB_PREF."chart_master coa,"
			.TB_PREF."chart_types act_type, "
			.TB_PREF."chart_class act_class
		WHERE trans.account=coa.account_code
			AND coa.account_type=act_type.id 
		AND act_type.class_id=act_class.cid"
		//." AND ".($from_incl ? "tran_date >= '$from_date'" : "tran_date > IF(ctype>0 AND ctype<".CL_INCOME.", '0000-00-00', '$from_date')")
		." AND ".($to_incl ? "tran_date <= '$to_date'" : "tran_date < '$to_date'")
		.($account == null ? '' : " AND account=".db_escape($account))
		.($dimension == 0 ? ''  : " AND dimension_id = ".($dimension<0 ? 0 : db_escape($dimension)))
		.($dimension2 == 0 ? '' : " AND dimension2_id = ".($dimension2<0 ? 0 : db_escape($dimension2)));

	$result = db_query($sql,"No general ledger accounts were returned");

	return db_fetch($result);
}


$pdeb = $pcre = $cdeb = $ccre = $tdeb = $tcre = $pbal = $cbal = $tbal =$sdeb = $scre = 0;

//----------------------------------------------------------------------------------------------------

function display_type ($type, $typename, &$dec, &$rep, $from, $to, $zero, $balances, $dimension, $dimension2,$hide_grp=0)
{
	global $pdeb, $pcre, $cdeb, $ccre, $tdeb, $tcre, $pbal, $cbal, $tbal, $SysPrefs,$sdeb,$scre;
	
	$printtitle = 0; //Flag for printing type name	
	
	//Get Accounts directly under this group/type
	$accounts = get_gl_accounts(null, null, $type);	
	
	// $begin = get_fiscalyear_begin_for_date($from);
	// if (date1_greater_date2($begin, $from))
		$begin = $from;
                if(!$hide_grp){

				$rep->row -= 4;
				$rep->TextCol(0, 8, _("Group")." - ".$type ." - ".$typename);	
				$printtitle = 1;
				$rep->row -= 4;
				$rep->Line($rep->row);
				$rep->NewLine();		
                }


	// $begin = add_days($begin, -1);
	while ($account=db_fetch($accounts))
	{
		// $rep->Font('B');
		//Print Type Title if it has atleast one non-zero account	
		// if (!$printtitle)
		// {	
		// 	$rep->row -= 4;
		// 	$rep->TextCol(0, 8, _("Group")." - ".$type ." - ".$typename);	
		// 	$printtitle = 1;
		// 	$rep->row -= 4;
		// 	$rep->Line($rep->row);
		// 	$rep->NewLine();			
		// }
		
		// FA doesn't really clear the closed year, therefore the brought forward balance includes all the transactions from the past, even though the balance is null.
		// If we want to remove the balanced part for the past years, this option removes the common part from from the prev and tot figures.
		// if (@$SysPrefs->clear_trial_balance_opening)
		// {
		// 	$open = get_balance($account["account_code"], $dimension, $dimension2, $begin,  $begin, false, true);
		// 	$offset = min($open['debit'], $open['credit']);
		// } else
			$offset = 0;

		$prev = get_balance_rep($account["account_code"], $dimension, $dimension2, $begin, $from, false, false);
		$curr = get_balance_rep($account["account_code"], $dimension, $dimension2, $begin, $to, true, true);
		$tot = get_balance_rep($account["account_code"], $dimension, $dimension2, $begin, $to, false, true);
// 		display_error($account['account_name']." = ".abs($tot['balance']));

		if (!$tot['balance'] || abs($tot['balance']) < 0.9999999999999999 )
			continue;

        if(!$hide_grp){

		$rep->TextCol(0, 1, substr($account['account_code'], -4) );
		$rep->TextCol(1, 2,	$account['account_name']);
        }
		if (!$balances)
		{
			// if ($prev['balance'] >= 0.0)
			// 	$rep->AmountCol(2, 3, $prev['balance'], $dec);
			// else
			// 	$rep->AmountCol(3, 4, abs($prev['balance']), $dec);
			// if ($curr['balance'] >= 0.0)
			// 	$rep->AmountCol(4, 5, $curr['balance'], $dec);
			// else
			// 	$rep->AmountCol(6, 7, abs($curr['balance']), $dec);
			if ($tot['balance'] >= 0.0){
				 if(!$hide_grp){
				$rep->AmountCol(4, 5, $tot['balance'], $dec);
				$rep->AmountCol(6, 7,0, $dec);
			    }
				$tdeb += $tot['balance'];//-$offset;
				$sdeb+= $tot['balance'];
			}
			else{
				 if(!$hide_grp){
               $rep->AmountCol(4, 5, 0, $dec);
				$rep->AmountCol(6, 7, abs($tot['balance']), $dec);
			  }
				$tcre += abs($tot['balance']);//-$offset;
				$scre += abs($tot['balance']);
			}


			// $pdeb += $prev['debit']-$offset;
			// $pcre += $prev['credit']-$offset;
			// $cdeb += $curr['debit'];
			// $ccre += $curr['credit'];
			// $tdeb += $tot['debit']-$offset;
			// $tcre += $tot['credit']-$offset;
		}
		// else
		// {
		// 	// $rep->AmountCol(2, 3, $prev['debit']-$offset, $dec);
		// 	// $rep->AmountCol(3, 4, $prev['credit']-$offset, $dec);
		// 	// $rep->AmountCol(4, 5, $curr['debit'], $dec);
		// 	// $rep->AmountCol(6, 7, $curr['credit'], $dec);
		// 	$rep->AmountCol(4, 5, $tot['debit']-$offset, $dec);
		// 	$rep->AmountCol(6, 7, $tot['credit']-$offset, $dec);
		// 	$pdeb += $prev['debit']-$offset;
		// 	$pcre += $prev['credit']-$offset;
		// 	$cdeb += $curr['debit'];
		// 	$ccre += $curr['credit'];
		// 	$tdeb += $tot['debit']-$offset;
		// 	$tcre += $tot['credit']-$offset;
		// }	

		$pbal += $prev['balance'];
		$cbal += $curr['balance'];
		$tbal += $tot['balance'];
		 if(!$hide_grp)
		$rep->NewLine();

		if ($rep->row < $rep->bottomMargin + $rep->lineHeight+10)
		{
			$rep->Line($rep->row - 2);
			$rep->NewPage();
		}
	}
		
	//Get Account groups/types under this group/type
	$result = get_account_types(false, false, $type);
	while ($accounttype=db_fetch($result))
	{
		//Print Type Title if has sub types and not previously printed

		      if(!$hide_grp)
			   $rep->Font('bold');
			if( $sdeb>0 ||  $scre>0 )
			{

			     if(!$hide_grp)
				$rep->TextCol(0, 3, _("Total ".$typename));
			     else
			      $rep->TextCol(0, 3, _($typename));
			       if($hide_grp)
			   $rep->Font('bold');
				$rep->AmountCol(4, 5, $sdeb, $dec);
				$rep->AmountCol(6, 7, $scre, $dec);
				$sdeb=$scre=0;
				$rep->Font();
		       $rep->NewLine();
			}


		if (!$printtitle)
		{
			$rep->row -= 4;
			 if(!$hide_grp)
			$rep->Font('B');
			$rep->TextCol(0, 8, _("Group")." - ".$type ." - ".$typename);	
			$printtitle = 1;
			$rep->row -= 4;
			$rep->Font('');
			$rep->Line($rep->row);
			$rep->NewLine();		
		}
			$rep->Font();
		//$accounttype["name"].' ('.$typename.')'
		display_type($accounttype["id"], $accounttype["name"], $dec, $rep, $from, $to, $zero, $balances, $dimension, $dimension2,$hide_grp);

	}


               if(!$hide_grp)
			   $rep->Font('bold');
			if( $sdeb>0 ||  $scre>0 )
			{

			     if(!$hide_grp)
				$rep->TextCol(0, 3, _("Total ".$typename));
			     else
			      $rep->TextCol(0, 3, _($typename));
			       if($hide_grp)
			   $rep->Font('bold');
				$rep->AmountCol(4, 5, $sdeb, $dec);
				$rep->AmountCol(6, 7, $scre, $dec);
				$sdeb=$scre=0;
				$rep->Font();
		       $rep->NewLine();
			}
}

//----------------------------------------------------------------------------------------------------

print_trial_balance();

//----------------------------------------------------------------------------------------------------

function print_trial_balance()
{
	global $path_to_root;
	global $pdeb, $pcre, $cdeb, $ccre, $tdeb, $tcre, $pbal, $cbal, $tbal;

	$dim = get_company_pref('use_dimension');
	$dimension = $dimension2 = 0;

	$from = $_POST['PARAM_0'];
	$to = $_POST['PARAM_1'];
	$hide_grp = $_POST['PARAM_2'];
	// $balances = $_POST['PARAM_2'];
	// display_error($dim ."  sami");
	// if ($dim == 2)
	// {
		// $dimension = $_POST['PARAM_3'];
		// $dimension2 = $_POST['PARAM_4'];
		// $comments = $_POST['PARAM_5'];
		$orientation = $_POST['PARAM_3'];
		$destination = $_POST['PARAM_4'];
	// }
	// else if ($dim == 1)
	// {
	// 	$dimension = $_POST['PARAM_4'];
	// 	$comments = $_POST['PARAM_5'];
	// 	$orientation = $_POST['PARAM_6'];
	// 	$destination = $_POST['PARAM_7'];
	// }
	// else
	// {
		// $comments = $_POST['PARAM_4'];
		// $orientation = $_POST['PARAM_5'];
		// $destination = $_POST['PARAM_8'];
	// display_error($destination );
	// }

	if ($destination)
		include_once($path_to_root . "/reporting/includes/excel_report.inc");
	else
		include_once($path_to_root . "/reporting/includes/pdf_report.inc");
	$orientation = ($orientation ? 'L' : 'P');
	$dec = user_price_dec();

	// $cols2 = array(0, 50, 190, 310, 430, 530);
	// //-------------0--1---2----3----4----5--

	// $headers2 = array('', '', _(''),	_('This Period'), _(''));

	// $aligns2 = array('left', 'left', 'left', 'left', 'left');

	$cols = array(0, 50, 220, 250, 270,	350, 390, 480, 510,	570);
	//------------0--1---2----3----4----5----6----7----8--

	$headers = array(_('Account'), _('Account Name'), _(''), _(''), _('Debit'),
		_(''), _('Credit'), _(''));

	$aligns = array('left',	'left',	'right', 'right', 'right', 'right',	'right', 'right');

    if ($dim == 2)
    {
    	$params =   array( 	0 => $comments,
    				    1 => array('text' => _('Period'),'from' => 'all', 'to' => $to),
                    	2 => array('text' => _('Dimension')." 1",
                            'from' => get_dimension_string($dimension), 'to' => ''),
                    	3 => array('text' => _('Dimension')." 2",
                            'from' => get_dimension_string($dimension2), 'to' => ''));
    }
    elseif ($dim == 1)
    {
    	$params =   array( 	0 => $comments,
    				    1 => array('text' => _('Period'),'from' => $from, 'to' => $to),
                    	2 => array('text' => _('Dimension'),
                            'from' => get_dimension_string($dimension), 'to' => ''));
    }
    else
    {
    	$params =   array( 	0 => $comments,
    				    1 => array('text' => _('End Date'),'from' => $to, 'to' => $to));
    }

	$rep = new FrontReport(_('Trial Balance'), "TrialBalance", user_pagesize(), 9, $orientation);
    if ($orientation == 'L')
    {
    	recalculate_cols($cols);
    	recalculate_cols($cols2);
	}

	$rep->Font();
	$rep->Info($params, $cols, $headers, $aligns, $cols2, $headers2, $aligns2);
	$rep->NewPage();

	$classresult = get_account_classes(false);
	while ($class = db_fetch($classresult))
	{
		$rep->Font('bold');
		$rep->fontSize += 1;
		$rep->TextCol(0, 1, $class['cid']);
		$rep->TextCol(1, 4, $class['class_name']);
	    $rep->fontSize -= 1;
		$rep->Font();
		$rep->NewLine();

		//Get Account groups/types under this group/type with no parents
		$typeresult = get_account_types(false, $class['cid'], -1);
		while ($accounttype=db_fetch($typeresult))
		{
			display_type($accounttype["id"], $accounttype["name"], $dec, $rep, $from, $to,	$zero, $balances, $dimension, $dimension2,$hide_grp);
			// 	$rep->NewLine();
			// 	$rep->Font('bold');
			// 	$rep->TextCol(0, 2, _("Total"));
			// 	$rep->AmountCol(4, 5, $tdeb, $dec);
			// 	$rep->AmountCol(6, 7, $tcre, $dec);
			// 	$rep->Font();
		    // $rep->NewLine();
		}
		$rep->NewLine();
	}
	$rep->Line($rep->row);
	$rep->NewLine();
	$rep->Font('bold');

	if ($balances == 0)
	{
		$rep->TextCol(0, 2, _("Total"));
		// $rep->AmountCol(2, 3, $pdeb, $dec);
		// $rep->AmountCol(3, 4, $pcre, $dec);
		// $rep->AmountCol(4, 5, $cdeb, $dec);
		// $rep->AmountCol(6, 7, $ccre, $dec);
		$rep->AmountCol(4, 5, $tdeb, $dec);
		$rep->AmountCol(6, 7, $tcre, $dec);
		$rep->NewLine();
	}	
	// $rep->TextCol(0, 2, _("Ending Balance"));

	// if ($pbal >= 0.0)
	// 	$rep->AmountCol(2, 3, $pbal, $dec);
	// else
	// 	$rep->AmountCol(3, 4, abs($pbal), $dec);

	// if ($cbal >= 0.0)
	// 	$rep->AmountCol(4, 5, $cbal, $dec);
	// else
	// 	$rep->AmountCol(6, 7, abs($cbal), $dec);
	
	// if ($tbal >= 0.0)
	// 	$rep->AmountCol(4, 5, $tbal, $dec);
	// else
	// 	$rep->AmountCol(6, 7, abs($tbal), $dec);

	$rep->NewLine();

	$rep->Line($rep->row + 10);
	// if (($pbal = round2($pbal, $dec)) != 0.0 && $dimension == 0 && $dimension2 == 0)
	// {
	// 	$rep->NewLine(2);
	// 	$rep->Font();
	// 	$rep->TextCol(0, 8, _("The Opening Balance is not in balance, probably due to a non closed Previous Fiscalyear."));
	// }	
	$rep->End();
}

