<?php 
require_once 'classes/user.php';

/**
* @package Reports
*/
class New_Customers extends Report
{
    var $m_hasgraph = true;
    var $friendlyName = 'New Customers';
    var $colorArray = array('#6699FF','#DFC329','#CC9933','#CC0033','#000099','#990033','#006600','#FFFF99','#FF6699');

    function process()
    {   

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

        //DETERMINE IF THIS IS A GRAPH CALL
        if (!get_magic_quotes_gpc()) {
            $graphdata = addslashes(@$_GET['graphdata']);
        } else {
            $graphdata = @$_GET['graphdata'];    
        }         
                
        $sql = "SELECT COUNT(id) as count, MONTH(dateActivated) as monthactivated, YEAR(dateActivated) yearactivated FROM users ";
        $sql .= " WHERE groupid=".ROLE_CUSTOMER." GROUP BY yearactivated, monthactivated ORDER BY yearactivated DESC";
        $result = $this->db->query($sql);
        
        $firstTime = true;
        $sumCount =0;
        $aYear = array();
        $newYear = 0;
        $lastMonthCount = 0;
        
        while($row = $result->fetch()){
            
            $tMonth = date("F", mktime(0, 0, 0, $row['monthactivated']+1, 0, 0));
            
            $tYear = $row['yearactivated'];
            
            if($firstTime){
                $newYear = $tYear;
                $firstTime=false;
            }
            $tCount = $row['count'];
            $sumCount += $tCount;
            
            if($newYear!=$tYear){
                $aYears[$newYear]["array"] = $aYear;
                $aYears[$newYear]["sumCount"] = $sumCount;
                
                $newYear = $tYear;
                unset($aYear);
                $sumCount = 0;
            }
            
            $aYear[$tMonth] = array($tMonth, $tCount);
            $lastMonthCount = $row['count'];
        }
        
        $aYears[$newYear]["array"] = $aYear;
        $aYears[$newYear]["sumCount"] = $sumCount;
        
        $yearCount=count($aYears);
        foreach($aYears as $key => $aYear){
            $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('Count')),$groupid,$grouphidden);            
            $aGroup[] = array("--------",$aYear["sumCount"]);            
            $this->Add($aGroup,"$key ".$this->user->lang('Totals'),array("",$this->user->lang('Total Count')),$groupid."-totals",$grouphidden);
            unset($aGroup);
        }        
        
        if($graphdata){
            //this supports lazy loading and dynamic loading of graphs            
            echo $this->GraphData($aYears); 
            exit;
        }        
        
        
        //Display Report
        echo "<div style='font-size:150%;font-weight:bold;'> New Customer Monthly Signup</div>";
        echo "<p>Displays yearly signups</p>";
        
        echo "<script type='text/javascript'>";        
        echo "function ShowYears(obj){";
        echo "	var strYear = obj.value;";          
        //Loop the number of years
        for($x=0;$x<$yearCount;$x++){
            $xYear = $thisYear - $x;
            echo  "if($('id-$xYear') != null) {";
            echo 	    "$('id-$xYear').style.display='none';";
            echo  "}";
            echo  "if($('id-$xYear-totals') != null) {";
            echo 	    "$('id-$xYear-totals').style.display='none';";
            echo  "}";
        }
        echo  "   if(strYear.substring(0,4)==\"Last\"){";
        echo  "     	yearsback = strYear.substring(4);";
        echo  "       for(x=0;x<yearsback;x++){";
        echo  "          if($('id-'+(".$thisYear."-x)) != null){";
        echo 	"            $('id-'+(".$thisYear."-x)).style.display='';";
        echo  "          };";
        echo  "          if($('id-'+(".$thisYear."-x)+'-totals') != null){";
        echo 	"            $('id-'+(".$thisYear."-x)+'-totals').style.display='';";
        echo  "          };";
        echo 	"       }";
        echo  "   }else{";
        echo  "       if($('id-'+obj.value) != null){";
        echo 	"           $('id-'+obj.value).style.display='';";
        echo  "       };";
        echo  "       if($('id-'+obj.value+'-totals') != null){";
        echo 	"           $('id-'+obj.value+'-totals').style.display='';";
        echo  "       };";
        echo  "   }";        
        echo  "	ChangeGraph(obj.value);";        
        echo "}";
        
        echo "function ChangeGraph(strYear){";
        echo "   var url;";        
        echo "   url ='index.php?noheaderfooter=1&graphdata=1&passedyear='+strYear+'&view=".$_REQUEST['view']."&fuse=".$_REQUEST['fuse']."&report=".urlencode($_REQUEST['report'])."&type=".$_REQUEST['type']."';";       
        echo "   retrieveReportData(url);";
        echo "}";                
        echo "</script>";        
        
        echo "<form id='reportdropdown' method='GET'>";
        echo "<table border=0 cellpadding=2 cellspacing=0 width=454>";
        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 number of years
        for($x=0;$x<$yearCount;$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><br/><br/>";         
                
        //create a lazy loading chart so that our showgraph will call ajax 
        //call to retrieve chart and populate it after load.  This should 
        //increase performance.         
        $url = "index.php?noheaderfooter=1&graphdata=1&passedyear=".$currentYear."&view=".$_REQUEST['view']."&fuse=".$_REQUEST['fuse']."&report=".urlencode($_REQUEST['report'])."&type=".urlencode($_REQUEST['type']);
        $this->ShowGraph(0,$url);                
        
        echo "<br/><br/>";     
        $this->Show();
        
    }
    
    function GraphData($aYears){
        // These headers must be set or IE will show an error.
        // IE + SSL = BAD
        // http://www.fusioncharts.com/KB/article.aspx?id=10091
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');
        
        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"],$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"],$key));
                        }
                    }
                }
            }
            $yearCount++;
        }
        
        $showborder="showborder='0'";
        $bgColor="bgColor='FFFFFF'";
        $title = "";
        $subcaption = "";
        
        if($this->viewingFromDashboard()){
            //do not want to see title in dashboard since we already show from dropdown
            $legend="showLegend='0'";
            $labelstep="labelStep='3'";
            $clickurl="clickURL='index.php?fuse=reports&report=New+Customers&type=Accounts&view=ViewReport'";
        }else{
            $clickurl="";
            $legend="";
            $labelstep="";
        }              
        
        $strXML  = "<chart ".$clickurl." ".$bgColor." ".$showborder." ".$labelstep." ".$legend." useRoundEdges='1' caption='".$title."' subcaption='".$subcaption."' xAxisName='' yAxisName='' yAxisMinValue='' numberPrefix='' showValues='0' alternateHGridColor='FCB541' alternateHGridAlpha='20' divLineColor='FCB541' divLineAlpha='50' canvasBorderColor='666666' baseFontColor='666666' lineColor='FCB541'>";
        arsort($ydata);

        $strXML  .= "<categories>";
        $strXML  .= "<category label='".$this->MonthName(1,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(2,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(3,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(4,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(5,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(6,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(7,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(8,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(9,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(10,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(11,true)."'/>";
        $strXML  .= "<category label='".$this->MonthName(12,true)."'/>";        
        $strXML  .= "</categories>";        

        $lines = 0;        
        foreach($ydata as $y){             
            $monthindex=1;
            $strXML .= "<dataset seriesName='".$y[0]."' color='".$this->colorArray[$lines]."'>";
            foreach($y[1] as $monthtotal){
                if ($monthtotal == "") $monthtotal="0";
                $strXML .= "<set value='$monthtotal' />";
                $monthindex++;
            }
            $strXML .= "</dataset>";
            $lines++;                
        }        
         
    	$strXML .= "<styles>";
    	$strXML .= "<definition>";
    	$strXML .= "<style name='Anim1' type='animation' param='_xscale' start='0' duration='1'/>";
    	$strXML .= "<style name='Anim2' type='animation' param='_alpha' start='0' duration='0.6'/>";
    	$strXML .= "<style name='DataShadow' type='Shadow' alpha='40'/>";
    	$strXML .= "</definition>";
    	$strXML .= "<application>";
    	$strXML .= "<apply toObject='DIVLINES' styles='Anim1'/>";
    	$strXML .= "<apply toObject='HGRID' styles='Anim2'/>";
    	$strXML .= "<apply toObject='DATALABELS' styles='DataShadow,Anim2'/>";
    	$strXML .= "</application>";
    	$strXML .= "</styles>";    
        
    	$strXML .= "</chart>";

        return $strXML;        
        
        
    }        
    
    function ReturnMonthsArray($aMonth,$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));
            $valIndex = 1;            
            
            if(!isset($aMonth[$tstrMonth])){
                $aReturn[] = "";
            }else if( $aMonth[$tstrMonth][$valIndex] == "na" ){
                $aReturn[] = "";
//            }else if( ($currentYear==date("Y")) && (date("F")==$tstrMonth) ){
//                    return $aReturn;
            }else{                
                $tempY = (int) $aMonth[$tstrMonth][$valIndex];
                $aReturn[] = $tempY;
            }
            
            if( ($currentYear==date("Y")) && (date("F")==$tstrMonth) )
            {
                return $aReturn;
            }
            
        }
        return $aReturn;
    }    
    
}
?>
