<?php

require_once 'classes/Currency.php';

/**
* @package Reports
*/
class Income_Growth extends Report
{
    var $m_hasgraph = true;

    function process()
    {
        /*
        ************************************************
        *   1.0 Initial Report Released.  - Alberto Vasquez
        ************************************************
        */
        
        //** Monthly Income Report        **//
        $report_version = "1.0";
        //$this->SetDescription("Displays income trends from previous month and year.");
        
        $currency = new Currency($this->user);
        
        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.status=1 "
               ."GROUP BY YEAR(i.billdate), MONTH(i.billdate);";
        
          $result = $this->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 = $currency->format($this->settings->get('Default Currency'), $tAmount, true, false);
        
        		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,$this->AverageInvoicePrice($tCounted,$row['amount']),$tAmount,$this->GetLastMonthDifference($lastMonthAmount,$tMonth,$row['amount']),$this->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) {
        	$this->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;
        		    	}
        		    }
        		  }
        
        		  $this->Add($aYear["array"],$key,array($this->user->lang('Month'),$this->user->lang('Invoices'),$this->user->lang('Avg. Price'),$this->user->lang('Month Total'), "&Delta; ".$this->user->lang('Last Month'),"&Delta; ".$this->user->lang('Last Year')),$groupid,$grouphidden);
        
        		  $aGroup[] = array("--------",$aYear["sumCount"],$currency->format($this->settings->get('Default Currency'), $aYear["sumAmount"], true, false), "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
        		  
        		  $this->Add($aGroup,"$key ".$this->user->lang('Totals'),array("",$this->user->lang('Total Count'),$this->user->lang('Total Amount'),""),$groupid."-totals",$grouphidden);
        		  unset($aGroup);
          }
        
          //Display Report
          echo "<b>".$this->user->lang('Income Growth')." v$report_version</b><br />";
          echo $this->user->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+'&view=".$_REQUEST['view']."&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>".$this->user->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>".$this->user->lang('Income Generated')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
          }else{
          	echo "<option value='income'>".$this->user->lang('Income Generated')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
          }
          if($currentGraph == "avginvoice"){
          	echo "<option value='avginvoice' SELECTED>".$this->user->lang('Average Invoice')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
          }else{
          	echo "<option value='avginvoice'>".$this->user->lang('Average Invoice')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
          }
          if($currentGraph == "month"){
          	echo "<option value='month' SELECTED>".$this->user->lang('Change from Previous Month')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
          }else{
          	echo "<option value='month'>".$this->user->lang('Change from Previous Month')."&nbsp;&nbsp;&nbsp;&nbsp;</option>";
          }
          if($currentGraph == "year"){
          	echo "<option value='year' SELECTED>".$this->user->lang('Change from Previous Year')."</option>";
          }else{
          	echo "<option value='year'>".$this->user->lang('Change from Previous Year')."</option>";
          }
          echo "</select>";
          echo "</td></tr>";
        
          echo "<tr><td align=right><b>".$this->user->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='view' value='".$_REQUEST['view']."' />";
          echo "<input type='hidden' name='type' value='".$_REQUEST['type']."' />";
        
          echo "</form>";
        
          echo "<p><br><img id=graphimage src=\"index.php?graphtype=".$currentGraph."&amp;passedyear=".$currentYear."&amp;view=".$_REQUEST['view']."&amp;fuse=".$_REQUEST['fuse']."&amp;report=".$_REQUEST['report']."&amp;type=".$_REQUEST['type']."&amp;viewimage=1\"></p>";
        
        
          $this->Show();
    }
    
    //*********************************************
    // Custom Function Definitions for this report
    //*********************************************
    function AverageInvoicePrice($invoices,$price){
        $currency = new Currency($this->user);
        $average = ((float)$price) / ((float)$invoices);
        return $currency->format($this->settings->get('Default Currency'), $average, true, false);
    }
    
    function GetLastMonthDifference($lastmonthamount,$month,$amount){
        $currency = new Currency($this->user);
    	if($lastmonthamount == "na") return "<b>na</b>";
    
    	$retValue = (float)$amount - (float)$lastmonthamount;
    
    	if($retValue <= 0){
    		$fontcolor="red";
    		$retValue = "( <font color=red>".$currency->format($this->settings->get('Default Currency'), $retValue, true, false)."</font> )";
    	}else{
    		$retValue = $currency->format($this->settings->get('Default Currency'), $retValue, true, false);
    	}
    	return $retValue;
    }
    
    function GetLastYearDifference($aYears,$month,$year,$amount){
        $currency = new Currency($this->user);
        $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'>".$currency->format($this->settings->get('Default Currency'), $retValue, true, false)."</font> )";
    	    }else{
    		    $retValue = $currency->format($this->settings->get('Default Currency'), $retValue, true, false);
    	    }
    
        }
        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
        
        $aReturn = array();
        
        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( $this->CleanFloat($aMonth[$tstrMonth][$valIndex]) == "na" ){
        		$aReturn[] = "";
        	}else if( ($currentYear==date("Y")) && (date("F")==$tstrMonth) ){
        		return $aReturn;
        	}else{
        		$aReturn[] = $this->CleanFloat($aMonth[$tstrMonth][$valIndex]);
        	}
        
        }
        return $aReturn;
    }
    
    function AllEmpty($yData) {
        if (!is_array($yData)) return true;
        
        $tArray = (array_diff($yData,array("","","","","","","","","","","","")));
        
        if (count($tArray) == 0) {
            return true;
        }
        
        return false;
    }
    
    function ShowGraph($graphType,$aYears){
    
        if (!isset($_REQUEST['passedyear'])){
        	$currentYear = date("Y");
        }else{
        	$currentYear = $_REQUEST['passedyear'];
        }
        
        $yearCount=0;
        $ydata = array();
        foreach($aYears as $key => $aYear){
          if($currentYear==$key){
        	$ydata[] = array($key,$this->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,$this->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($this->user->lang('Income Growth - Change Previous Month'));
        }elseif($graphType=="year"){
        	$graph->title->Set($this->user->lang('Income Growth - Change Previous Year'));
        }elseif($graphType=="avginvoice"){
        	$graph->title->Set($this->user->lang('Average Invoice Price'));
        }else{
        	$graph->title->Set($this->user->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(!$this->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) && $lines > 0) {
            $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,  $this->user->lang('No graphing data available'), $text_color );
        	header ("Content-type: image/png");
        	ImagePng ($im);
        	exit;
        }
    }
}
?>
