<?php
  //** Total Income to Date Report  **//
  //** Written By: Bart Wegrzyn     **//
  //** Written For: ClientExec v1.1 **//

// don't show if not logged in
if (!isset($_SESSION['userId'])) die('Log in first');
  
  //GLOBALs available to you
  $report = new Report();
  $report->SetDescription(lang('Displays all paid invoices to date, with total income.'));
  //SQL to generate the the result set of the report
  $reportSQL = "SELECT id, description, amount, datepaid, paid, tax FROM `invoice` WHERE paid='1' ORDER BY id";
  $result = $GLOBALS['db']->query($reportSQL);

  //initialize
  $TotalIncome = 0;
  $TotalInvoices = 0;
  $totalTaxCharged = 0;
  while (list($tInvoiceId,$tDescription,$tAmount,$tDatePaid,$tPaid,$tTaxRate) = $result->fetch()){
         $sql = "SELECT SUM(`price`) FROM `invoiceentry` WHERE `invoiceid`=?";
         $result2 = $GLOBALS['db']->query($sql,$tInvoiceId);
         $taxrow = $result2->fetch();
         $tInvoiceAmount = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $tAmount);
         $TotalIncome += $tAmount;
         $TotalInvoices += 1;
         $taxCharged = ($tAmount - $taxrow[0]);
         $totalTaxCharged += $taxCharged;
         $aGroup[] = array($tDescription,$tDatePaid,$tInvoiceAmount, ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $taxCharged));
  }

  //Add 'Invoices' groud
  $report->Add($aGroup,lang('Invoices'),array(lang('Invoice #'),lang('Date Paid'),lang('Invoice Amount'), lang('Tax Charged')));
  unset($aGroup);

  $totalIncomeMinusTax = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f",($TotalIncome - $totalTaxCharged));
  $TotalIncome = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f",$TotalIncome);
  $totalTaxCharged = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f",$totalTaxCharged);
  $aGroup[] = array($TotalInvoices,$TotalIncome, $totalTaxCharged, "<b>" .$totalIncomeMinusTax. "</b>");
  $report->Add($aGroup,lang('Totals'),array(lang('Total Paid Invoices'),lang('Gross Income'), lang('Total Taxes'), lang('Real Income')));

  //Display Report
  $report->Show();

  //*********************************************
  // Custom Function Definitions for this report
  //*********************************************

  // No custom functions used.

?>
