<?php
/**
 * New Customers Report
 *
 * @category Report
 * @package  ClientExec
 * @author   Jason Yates <jason@clientexec.com>
 * @license  ClientExec License
 * @version  1.1
 * @link     http://www.clientexec.com
 *
 *************************************************
 *   1.1 Updated the report to use Pear Commenting & the new title handing to make app reports consistent.
 ************************************************
 */

require_once 'modules/clients/models/user.php';

/**
 * New_Customers Report Class
 *
 * @category Report
 * @package  ClientExec
 * @author   Jason Yates <jason@clientexec.com>
 * @license  ClientExec License
 * @version  1.1
 * @link     http://www.clientexec.com
 */
class New_Customers extends Report
{
    protected $featureSet = 'accounts';

    var $m_hasgraph = true;
    var $friendlyName = 'New Customers';
    var $colorArray = array('#6699FF','#DFC329','#CC9933','#CC0033','#000099','#990033','#006600','#FFFF99','#FF6699');
    var $yearCount = 1;

    /**
     * Report Process Method
     *
     * @return null - direct output
     */
    function process()
    {

        // Set the report information
        $this->setName('New Customer Monthly Signup', true);
        $this->setVersion("1.1");
        $this->SetDescription($this->user->lang('Displays the total number of new signups for a given year broken down by month.'));

        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 usercount, 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;
        $sumAffCount = 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['usercount'];
            $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['usercount'];
        }

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


        $this->yearCount=count($aYears);

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

            if($currentYear==$key) {
                $grouphidden=false;
            }else {
                if( mb_substr($currentYear,0,4)=="Last") {
                    $tYears = mb_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;
        }

        // Output the headers before anything else
        $this->showReportHeader();

        //Display Report

        echo "<script type='text/javascript'>";
        echo "function ShowYears(obj){";
        echo "	var strYear = obj.value;";
        //Loop the number of years
        for($x=0;$x<$this->yearCount;$x++) {
            $xYear = $thisYear - $x;
            echo  "if(document.getElementById('id-$xYear') != null) {";
            echo 	    "document.getElementById('id-$xYear').style.display='none';";
            echo  "}";
            echo  "if(document.getElementById('id-$xYear-totals') != null) {";
            echo 	    "document.getElementById('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(document.getElementById('id-'+(".$thisYear."-x)) != null){";
        echo 	"            document.getElementById('id-'+(".$thisYear."-x)).style.display='';";
        echo  "          };";
        echo  "          if(document.getElementById('id-'+(".$thisYear."-x)+'-totals') != null){";
        echo 	"            document.getElementById('id-'+(".$thisYear."-x)+'-totals').style.display='';";
        echo  "          };";
        echo 	"       }";
        echo  "   }else{";
        echo  "       if(document.getElementById('id-'+obj.value) != null){";
        echo 	"           document.getElementById('id-'+obj.value).style.display='';";
        echo  "       };";
        echo  "       if(document.getElementById('id-'+obj.value+'-totals') != null){";
        echo 	"           document.getElementById('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<$this->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<$this->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 to generate the graph data
     *
     * @return null - direct output
     */
    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( mb_substr($currentYear,0,4)=="Last") {
                    $tYears = mb_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." caption='".$title."' subcaption='".$subcaption."' ".$this->linechartDefaults.">";

        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++;
        }

        // THIS CODE HAS BEEN COMMENTED TO AVOID SHOW THE YEAR TWICE
        /*
        $yearCount=0;
        $ydata = array();

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


        foreach($ydata as $y) {
            $monthindex=1;
            $strXML .= "<dataset seriesName='".$y[0]."' color='".$this->colorArray[$lines]."' parentYAxis='S'>";
            foreach($y[1] as $monthtotal) {
                if ($monthtotal == "") $monthtotal="0";
                $strXML .= "<set value='$monthtotal' />";
                $monthindex++;

            }
            $strXML .= "</dataset>";
            $lines++;
        }
        */
        // THIS CODE HAS BEEN COMMENTED TO AVOID SHOW THE YEAR TWICE

        $strXML .= "<styles>";
        $strXML .= "<definition>";
        $strXML .= "    <style name='myToolTipFont' borderColor='dddddd' leftMargin='20' type='font' font='Verdana' size='10' color='333333'/>";
        $strXML .= "    <style name='myLegendFont' type='font' font='Verdana' size='10' color='333333' bold='0' />";
        $strXML .= "</definition>";
        $strXML .= "<application>";
        $strXML .= "    <apply toObject='ToolTip' styles='myToolTipFont' />";
        $strXML .= "    <apply toObject='Legend' styles='myLegendFont' />";
        $strXML .= "</application>";
        $strXML .= "</styles>";

        $strXML .= "</chart>";

        return $strXML;


    }

    function ReturnMonthsArray($aMonth,$currentYear,$valIndex = 1)
    {
        //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;
    }

}
?>
