<?php
/*
************************************************
*   1.0 Initial Report Released.  - Alberto Vasquez
************************************************
*/

// don't show if not logged in
if (!isset($_SESSION['userId'])) die('Log in first');

//** Monthly Income Report        **//
$report_version = "1.0";
$report = new Report();
//$report->SetDescription("Displays income trends from previous month and year.");

if (!isset($_REQUEST['passedyear'])){
	$currentYear = date("Y");
}else{
	$currentYear = $_REQUEST['passedyear'];
}

if (!isset($_REQUEST['graphtype'])){
	$currentGraph = "income";
}else{
	$currentGraph = $_REQUEST['graphtype'];
}

$thisYear = Date("Y");

//DETERMINE IF THIS IS A GRAPH CALL
if (!get_magic_quotes_gpc()) {
	$viewimage = addslashes(@$_GET['viewimage']);
} else {
	$viewimage = @$_GET['viewimage'];
}

if(!isset($_SESSION['incomegrowthdata'])){

  //SQL to generate the the result set of the report
  $sql ="SELECT MONTH(i.billdate) as month, YEAR(i.billdate) as year, COUNT(*) as counted, SUM(amount) as amount
       FROM invoice i
       WHERE i.paid=1
       GROUP BY YEAR(i.billdate), MONTH(i.billdate);";

  $result = $GLOBALS['db']->query($sql);

  $firstTime = true;
  $sumCount =0;
  $sumAmount = 0;
  $lastMonthAmount = "na";
  $aYear = array();
  $newYear = 0;

  while($row = $result->fetch()){

		$tMonth = date("F", mktime(0, 0, 0, $row['month']+1, 0, 0));

		$tYear = $row['year'];
		if($firstTime){
			$newYear = $tYear;
			$firstTime=false;
		}
		$tAmount = $row['amount'];
		$sumAmount += $tAmount;

		$tCounted = $row['counted'];
		$sumCount += $tCounted;

		$tAmount = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $tAmount);

		if($newYear!=$tYear){
			$aYears[$newYear]["array"] = $aYear;
			$aYears[$newYear]["sumAmount"] = $sumAmount;
			$aYears[$newYear]["sumCount"] = $sumCount;

			$newYear = $tYear;
			unset($aYear);
			$sumCount = 0;
			$sumAmount = 0;
		}

		$aYear[$tMonth] = array($tMonth,$tCounted,AverageInvoicePrice($tCounted,$row['amount']),$tAmount,GetLastMonthDifference($lastMonthAmount,$tMonth,$row['amount']),GetLastYearDifference(@$aYears,$tMonth,$tYear,$row['amount']) );
		$lastMonthAmount = $row['amount'];
  }

  $aYears[$newYear]["array"] = $aYear;
  $aYears[$newYear]["sumAmount"] = $sumAmount;
  $aYears[$newYear]["sumCount"] = $sumCount;

  $_SESSION['incomegrowthdata'] = $aYears;
}else{
  $aYears = $_SESSION['incomegrowthdata'];
}


if ($viewimage) {
	ShowGraph($currentGraph,$aYears);
	exit;
}


  $yearCount=0;
  foreach($aYears as $key => $aYear){
  		  $yearCount++;
		  $grouphidden=true;
  		  $groupid="id-".$key;

  		  if($currentYear==$key){
  		  	$grouphidden=false;
		  }else{
		    if( substr($currentYear,0,4)=="Last"){
		    	$tYears = substr($currentYear,4);
		    	for($y=0;$y<$tYears;$y++){
		    		if ($key==date("Y")-$y) $grouphidden = false;
		    	}
		    }
		  }
		  
          $report->Add($aYear["array"],$key,array(lang('Month'),lang('Invoices'),lang('Avg. Price'),lang('Month Total'), "&Delta; ".lang('Last Month'),"&Delta; ".lang('Last Year')),$groupid,$grouphidden);
		  
		  $aGroup[] = array("--------",$aYear["sumCount"],ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $aYear["sumAmount"],"","&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));
		  $report->Add($aGroup,"$key ".lang('Totals'),array("",lang('Total Count'),lang('Total Amount'),""),$groupid."-totals",$grouphidden);
		  unset($aGroup);
  }

  //Display Report
  echo "<b>".lang('Income Growth')." v$report_version</b><br />";
  echo lang('Displays income trends from previous month and year.')."<br /><br />";
  echo "\n\n<script type='text/javascript'>";

  echo "\n\n";
  echo "function ShowYears(obj){";
  echo "	var strYear = obj.value;\n";
  //Loop the last 4 years
  for($x=0;$x<4;$x++){
	  $xYear = $thisYear - $x;
	  echo  "if($('id-$xYear') != null) {\n";
	  echo 	    "$('id-$xYear').style.display='none';\n";
	  echo  "}\n";
	  echo  "if($('id-$xYear-totals') != null) {\n";
	  echo 	    "$('id-$xYear-totals').style.display='none';\n";
	  echo  "}\n";
  }
  echo  "   if(strYear.substring(0,4)==\"Last\"){\n";
  echo  "     	yearsback = strYear.substring(4);\n";
  echo  "       for(x=0;x<yearsback;x++){ \n";
  echo  "          if($('id-'+(".$thisYear."-x)) != null){\n";
  echo 	"            $('id-'+(".$thisYear."-x)).style.display='';\n";
  echo  "          };\n";
  echo  "          if($('id-'+(".$thisYear."-x)+'-totals') != null){\n";
  echo 	"            $('id-'+(".$thisYear."-x)+'-totals').style.display='';\n";
  echo  "          };\n";
  echo 	"       }\n";
  echo  "   }else{\n";
  echo  "       if($('id-'+obj.value) != null){\n";
  echo 	"           $('id-'+obj.value).style.display='';\n";
  echo  "       };\n";
  echo  "       if($('id-'+obj.value+'-totals') != null){\n";
  echo 	"           $('id-'+obj.value+'-totals').style.display='';\n";
  echo  "       };\n";
  echo  "   }\n";

  echo  "	ChangeGraph($('graphtype').value,obj.value);\n";

  echo "}";
  echo "\n\n";

  echo "function ChangeGraph(strGraph,strYear){\n";
  echo "   $('graphimage').src='index.php?graphtype='+strGraph+'&passedyear='+strYear+'&action=".$_REQUEST['action']."&fuse=".$_REQUEST['fuse']."&report=".urlencode($_REQUEST['report'])."&type=".$_REQUEST['type']."&viewimage=1';";
  echo "}";
  echo "\n\n";





  echo "</script>";
  echo "\n\n";

  echo "<form id='reportdropdown' method='GET'>";
  echo "<table border=0 cellpadding=2 cellspacing=0 width=454>";
  echo "<tr><td align=right>";
  echo "<b>".lang('Select Graph Type')."</b>:&nbsp;&nbsp;";
  echo "<select id='graphtype' name='graphtype' onChange=\"ChangeGraph(this.value,$('passedyear').value);\">";
  if($currentGraph == "income"){
  	echo "<option value='income' SELECTED>".lang('Income Generated')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  }else{
  	echo "<option value='income'>".lang('Income Generated')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  }
  if($currentGraph == "avginvoice"){
  	echo "<option value='avginvoice' SELECTED>".lang('Average Invoice')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  }else{
  	echo "<option value='avginvoice'>".lang('Average Invoice')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  }
  if($currentGraph == "month"){
  	echo "<option value='month' SELECTED>".lang('Change from Previous Month')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  }else{
  	echo "<option value='month'>".lang('Change from Previous Month')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  }
  if($currentGraph == "year"){
  	echo "<option value='year' SELECTED>".lang('Change from Previous Year')."</option>";
  }else{
  	echo "<option value='year'>".lang('Change from Previous Year')."</option>";
  }
  echo "</select>";
  echo "</td></tr>";

  echo "<tr><td align=right><b>".lang('Select Year Range')."</b>:&nbsp;&nbsp;";
  echo "<select id='passedyear' name='passedyear' onChange='ShowYears(this);'>";

  //Loop the last 4 years
  for($x=0;$x<4;$x++){
  	  $xYear = $thisYear - $x;
	  if($currentYear == $xYear){
		echo "<option value='".$xYear."' SELECTED>".$xYear."</option>";
	  }else{
		echo "<option value='".$xYear."'>".$xYear."</option>";
	  }
  }

  //Create based on number of years of data available
  for($x=1;$x<$yearCount;$x++){
      $value=$x+1;
	  if($currentYear == "Last$value"){
		echo "<option value='Last$value' SELECTED>Last $value Years&nbsp;&nbsp;&nbsp;</option>";
	  }else{
		echo "<option value='Last$value'>Last $value Years&nbsp;&nbsp;&nbsp;</option>";
	  }
  }

  echo "</select></td></tr></table>";
  echo "<input type='hidden' name='fuse' value='".$_REQUEST['fuse']."' />";
  echo "<input type='hidden' name='report' value='".$_REQUEST['report']."' />";
  echo "<input type='hidden' name='action' value='".$_REQUEST['action']."' />";
  echo "<input type='hidden' name='type' value='".$_REQUEST['type']."' />";

  echo "</form>";

  echo "<p><br><img id=graphimage src=\"index.php?graphtype=".$currentGraph."&passedyear=".$currentYear."&action=".$_REQUEST['action']."&fuse=".$_REQUEST['fuse']."&report=".$_REQUEST['report']."&type=".$_REQUEST['type']."&viewimage=1\"></p>";


  $report->Show();

  //*********************************************
  // Custom Function Definitions for this report
  //*********************************************
  function AverageInvoicePrice($invoices,$price){
      $average = ((float)$price) / ((float)$invoices);
	  return ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $average);
  }

  function GetLastMonthDifference($lastmonthamount,$month,$amount){
		if($lastmonthamount == "na") return "<b>na</b>";

		$retValue = (float)$amount - (float)$lastmonthamount;

		if($retValue <= 0){
			$fontcolor="red";
			$retValue = "( <font color=red>".ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $retValue)."</font> )";
		}else{
			$retValue = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $retValue);
		}
		return $retValue;
  }

  function GetLastYearDifference($aYears,$month,$year,$amount){
	$retValue = "<b>na</b>";
	if(isset($aYears[$year-1]["array"][$month])){
		$aMonth = $aYears[$year-1]["array"][$month];

		$lastYearPrice = substr($aMonth[3], 1);
		$retValue = (float)$amount - (float)$lastYearPrice;
		if($retValue <= 0){
			$fontcolor="red";
			$retValue = "( <font color='$fontcolor'>".ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $retValue)."</font> )";
		}else{
			$retValue = ShowCurrencySymbol($GLOBALS['gSettingsArray']['Default Currency'],false).sprintf("%01.2f", $retValue);
		}

	}
	return $retValue;
  }

  function CleanFloat($strFormattedAmount){
  	//remove formatting
  	$strFormattedAmount = strip_tags($strFormattedAmount);
  	$strFormattedAmount = str_replace(array("(",")"), array('', ''), $strFormattedAmount);
    if(preg_match("/^(\D)+\d+/", $strFormattedAmount, $oldCurrencySymbol)) {
        $strFormattedAmount = str_replace($oldCurrencySymbol[1], '', $strFormattedAmount);
    }

  	return (float)$strFormattedAmount;
  }

  function ReturnMonthsArray($aMonth,$graphType,$currentYear){
    //Get all months values
	//Loop through 12 months using long date description and determine
	//if aMonth contains that month.  If not return 0.0

	for($x=1;$x<=12;$x++){
		$tstrMonth = date("F", mktime(0, 0, 0, $x+1, 0, 0));

		switch($graphType){
			case "year":
				$valIndex = 5;
				break;
			case "month":
				$valIndex = 4;
				break;
			case "avginvoice":
				$valIndex = 2;
				break;
			default:
				$valIndex = 3;
				break;
		}



		if(!isset($aMonth[$tstrMonth])){
			$aReturn[] = "";
		}else if( CleanFloat($aMonth[$tstrMonth][$valIndex]) == "na" ){
			$aReturn[] = "";
		}else if( ($currentYear==date("Y")) && (date("F")==$tstrMonth) ){
			return $aReturn;
		}else{
			$aReturn[] = CleanFloat($aMonth[$tstrMonth][$valIndex]);
		}

	}
	return $aReturn;
  }

  function AllEmpty($yData){
  	 $tArray = (array_diff($yData,array("","","","","","","","","","","","")));
	 //echo count($tArray)."<br>";

	 if(count($tArray)==0){
	 	return true;
	 }

 	 return false;

  }

  function ShowGraph($graphType,$aYears){

	$currentYear = $_REQUEST['passedyear'];

	$yearCount=0;
    $ydata = array();
	foreach($aYears as $key => $aYear){
	  if($currentYear==$key){
		$ydata[] = array($key,ReturnMonthsArray($aYear["array"],$graphType,$key));
	  }else{
		if( substr($currentYear,0,4)=="Last"){
			$tYears = substr($currentYear,4);
			for($y=0;$y<$tYears;$y++){
				if ($key==date("Y")-$y){
					$ydata[] = array($key,ReturnMonthsArray($aYear["array"],$graphType,$key));
				}
			}
		}
	  }
	  $yearCount++;
	}

	//Show GD Report
	require_once 'classes/jpgraph/src/jpgraph.php';
	require_once 'classes/jpgraph/src/jpgraph_line.php';
	require_once 'classes/jpgraph/src/jpgraph_scatter.php';

	// Create the graph. These two calls are always required
	$graph  = new Graph(500, 350,"auto");
	$graph->SetScale("intlin");

	if($graphType=="month"){
    	$graph->title->Set(lang('Income Growth - Change Previous Month'));
    }elseif($graphType=="year"){
    	$graph->title->Set(lang('Income Growth - Change Previous Year'));
    }elseif($graphType=="avginvoice"){
    	$graph->title->Set(lang('Average Invoice Price'));
    }else{
    	$graph->title->Set(lang('Income Generated'));
    }
    //$graph->title->SetFont(FF_ARIAL,FS_NORMAL,12);
    $graph->subtitle->Set('(Control points shown in red)');
    $graph->subtitle->SetColor('darkred');

    $graph->SetMarginColor('white');
    $graph->SetFrame(false);
    $graph->SetMargin(40,50,30,30);

    $graph->ygrid->SetFill(true,'#EFEFEF@0.5','#BBCCFF@0.5');
    $graph->xgrid->Show();

	$graph->xaxis->SetTickLabels(array("Jan","Feb","Mar","April","May","June","July","Aug","Sept","Oct","Nov","Dec"));
	$graph->xaxis->SetPos("min");

	// Add mark graph with static lines
	$line = new PlotLine(HORIZONTAL,0,"black",2);
	$graph->AddLine($line);

	// Create the linear plot
	$arrayColors = array("blue","orange","red","green");
	$tIndex=1;
	arsort($ydata);
	$lines = 0;
	foreach($ydata as $y){

		//check if all ys are ""
		//if so then just continue and skip year
		if(!AllEmpty($y[1])){
		    $lines++;
			switch($tIndex){
				case 1:
					$lineplot1 =new LinePlot($y[1]);
					$lineplot1->SetColor($arrayColors[$tIndex-1]);
					$lineplot1->SetWeight(4);
					$lineplot1->SetLegend ($y[0]);
					$graph->Add( $lineplot1);
					break;
				case 2:
					$lineplot2 =new LinePlot($y[1]);
					$lineplot2->SetColor($arrayColors[$tIndex-1]);
					$lineplot2->SetWeight(2);
					$lineplot2->SetLegend ($y[0]);
					$graph->Add( $lineplot2);
					break;
				case 3:
					$lineplot3 =new LinePlot($y[1]);
					$lineplot3->SetColor($arrayColors[$tIndex-1]);
					$lineplot3->SetWeight(2);
					$lineplot3->SetLegend ($y[0]);
					$graph->Add( $lineplot3);
					break;
				case 4:
					$lineplot4 =new LinePlot($y[1]);
					$lineplot4->SetColor($arrayColors[$tIndex-1]);
					$lineplot4->SetWeight(2);
					$lineplot4->SetLegend ($y[0]);
					$graph->Add( $lineplot4);
					break;
			}
		}
		$tIndex++;
	}

	//Create a new impuls type scatter plot
    if (count($ydata)) {
        $sp1 = new ScatterPlot($ydata[count($ydata)-1][1]);
        $sp1->mark->SetType(MARK_SQUARE);
        $sp1->mark->SetFillColor("red");
        $sp1->mark->SetWidth(4);
        $graph->Add($sp1);
    }


    $graph->legend->SetShadow('gray@0.4',5);
    $graph->legend->SetPos(0.1,0.1,'right','top');

	// Display the graph
	if($lines>0) $graph->Stroke();
	else{
  	    $im = @ ImageCreate ( 220, 45);
		$background_color  = ImageColorAllocate  ($im, 255,  255, 255);
		$text_color  = ImageColorAllocate  ($im, 219, 112, 147);
		ImageString  ($im, 3,  0, 10,  lang('No graphing data available'), $text_color );
		header ("Content-type: image/png");
		ImagePng ($im);
		exit;
	}
  }

?>
