<?php

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

    function process()
    {
        $numDomainsToShow = 20; // number of domains to show per page

        $numMonthsToShow = 7;   // number of months to show in the graph
                                // if there are no domains in a certain month, that month will not be shown

        $graphWidth = 320;      // width of the graph in pixels
        $graphHeight = 150;     // height of the graph in pixels


        // if graph doesn't show, set this to a directory that PHP has read & write access to
        $cache_dir = "c:\\temp\\";    // example for Windows
        // $cache_dir = "/tmp/";      // example for Linux


        // -------------------------------------------------------------

        // Check if filter is on
        if((isset($_GET['filter'])) && ($_GET['filter'] != "")) {
          $filter = $this->db->escape_string($_GET['filter']);
        }
          
        ini_set('include_path', dirname(__FILE__) . '/../..');

        $viewimage = false;
        $firstDomain="";

        if (!get_magic_quotes_gpc()) {
          if(isset($_GET['viewimage'])) $viewimage = addslashes($_GET['viewimage']); // used to specify that we're returning the graph
          if(isset($_GET['firstDomain'])) $firstDomain = addslashes($_GET['firstDomain']); // first domain to show
          if(isset($_GET['go'])) $go = addslashes($_GET['go']); // direction to move through domains
        } else {
          if(isset($_GET['viewimage'])) $viewimage = $_GET['viewimage'];
          if(isset($_GET['firstDomain'])) $firstDomain = $_GET['firstDomain'];
          if(isset($_GET['go'])) $go = $_GET['go'];
        }


        if ($viewimage) { // we're returning an image to the browser
          
          
          // grab the domains per month data
          if(isset($filter) && $filter != '') {
                $sql = "SELECT dateActivated FROM domains WHERE plan = '$filter'";
            }
            else {
               $sql = "SELECT dateActivated FROM domains";
            }
          
          $result = $this->db->query($sql);
          while ($dateActivated = $result->fetch()) {
            $date1 = date("Ym"); // this year/month
            $date2 = date("Ym", strtotime($dateActivated[0])); // year/month of domain activation
            
            // determine the months between now and dataActivated
            $sql = "SELECT PERIOD_DIFF($date1,$date2)";
            $dateresult = $this->db->query($sql);
            $monthDiff = $dateresult->fetch();
            if ($monthDiff[0] <= $numMonthsToShow) { // only track a certain number of months of data
              if (!isset($monthData[$date2])) {
                $monthData[$date2] = 0;
              }
              $monthData[$date2] += 1;
            }
          }
          
          if (isset($monthData)) {
            ksort($monthData);
            foreach ($monthData as $month => $numDomains) {
              // reconstruct a date that's readable by the PHP date() function
              $month = substr($month, 0, 4) . "-" . substr($month, 4, 2) . "-01";

              $months[] = date("M", strtotime($month));
              $domains[] = $numDomains;
            }
          } else { // if no domains were found
            $months[] = date("M");
            $domains[] = 0;
          }
          

          
          require_once 'classes/jpgraph/src/jpgraph.php';
          require_once 'classes/jpgraph/src/jpgraph_bar.php';
          
          // data for the graph
          $datay = $domains;
          $datax = $months;

          // set up the graph
          $graph = new Graph($graphWidth,$graphHeight,"auto");  
          $graph = new Graph(320,150,"auto");
          $graph->SetScale("textlin");
          $graph->SetMarginColor("white");
          $graph->SetFrame(false);
          
          // set up the title for the graph
          $txt =new Text($this->user->lang('New Domains per Month'));
          $txt->Pos(55,0);
          $txt->SetFont(FF_FONT1,FS_BOLD);
          $txt->SetColor( "black");
          $graph->AddText( $txt);

          // show 0 label on Y-axis (default is not to show)
          $graph->yscale->ticks->SupressZeroLabel(false);

          // set up x-axis labels
          $graph->xaxis->SetTickLabels($datax);
          
          // create the bar pot
          $bplot = new BarPlot($datay);
          $bplot->SetWidth(0.5);
          
          // set more graph colors
          $bplot->SetColor("black");
          $bplot->SetFillGradient("navy","#CCCCFF",GRAD_LEFT_REFLECTION);
          $graph->ygrid->SetFill(true,'#EFEFEF@0.5','#BBCCFF@0.5'); 
          $graph->ygrid->Show(); 
          $graph->xgrid->Show();

          $graph->Add($bplot);
          
          // send the graph to the browser
          $graph->Stroke();

        } else { // we're returning the report data to the browser
          
          if ($firstDomain == "") {
            $firstDomain = 0;
          } else {
            if ($go == "back") {
              $firstDomain -= $numDomainsToShow;
            } else {
              $firstDomain += $numDomainsToShow;
            }
          }

          // get the total number of domains in the database
           if(isset($filter)) {
                $sql = "SELECT * FROM domains WHERE plan = '$filter'";
            }
            else {
                $sql = "SELECT * FROM domains";
            }
          $result = $this->db->query($sql);
          $totalDomains = $result->getNumRows();
          
          // grab domain, customer id, plan id from database
          if(isset($_GET["filter"])) {
          $filter = $this->db->escape_string($_GET['filter']);
          $sql = "SELECT DomainName, CustomerID, Plan FROM domains WHERE domainname IS NOT NULL AND plan = '$filter' ORDER BY DomainName ASC LIMIT $firstDomain,$numDomainsToShow";
          }
          else {
          $sql = "SELECT DomainName, CustomerID, Plan FROM domains WHERE domainname IS NOT NULL ORDER BY DomainName ASC LIMIT $firstDomain,$numDomainsToShow";
          }
          $result = $this->db->query($sql);
          while (list($DomainName, $CustomerID, $Plan) = $result->fetch()) {
              // we've got what we need so prepare the array for the report
              $domainsGroup[] = "<a href='http://$DomainName/' target='_blank'>$DomainName</a>";
              // these will require more manipulation
              $customerIDGroup[] = array($CustomerID);
              $planIDGroup[] = array($Plan);
          }

          if ($totalDomains > 0) { // make sure there were domains returned from the database

             // determine customer names from customer ids and prepare the array for the report
            foreach ($customerIDGroup as $customerID) {
                $userid = $customerID[0];
                $tUser =& new User($userid);
                 if ($tUser->isOrganization() == true) {
                    $username = $tUser->getOrganization();
                    if (strlen($username) > 20) {
                        $title = "title=\"$username\"";
                        $dusername = substr($username, 0,20) . "...";
                        $username =  "<a href=\"index.php?fuse=clients&amp;frmClientID=". $userid ."\" $title>" .$dusername."</a>";
                    } else {
                        $title = "";
                        $username =  "<a href=\"index.php?fuse=clients&amp;frmClientID=". $userid ."\" $title>" .$username."</a>";
                    }
                } else {
                    $username = $tUser->getFullName();
                    $title = "";
                    $username =  "<a href=\"index.php?fuse=clients&amp;frmClientID=". $userid ."\" $title>" .$username."</a>";
                }
                $customerGroup[] = $username;
                unset($username);
            }
            // determine domain plans from plan ids and prepare the array for the report
            foreach ($planIDGroup as $planID) {
              $sql = "SELECT planname, description, id FROM package WHERE id=?";
              $planResult = $this->db->query($sql, $planID[0]);
              while (list($planname, $description, $id) = $planResult->fetch()) {
                $description = preg_replace("/<.+?>/","",$description);
                $planGroup[] = "<a title='$description' href='" . $_SERVER['PHP_SELF'] . "?fuse=reports&amp;report=Customer+Domains&amp;type=Account+%26+Packages&amp;view=ViewReport&amp;filter=$id'>$planname</a>";
                //$planGroup[] = "<a href='javascript:void(0);' title='$description'>$planname</a>";
              }
            }

          } else { // there were no domains returned from the database
            $domainsGroup[] = "no domains to show";
            $customerGroup[] = " ";
            $planGroup[] = " ";
          }
          
          // display the graph image
          echo "<br><br><img src='index.php?fuse=reports&amp;report=".urlencode('Customer Domains')."&amp;type=".urlencode('account_&_packages')."&amp;viewimage=1&filter=".@$filter."'><br><br>";

          
          // initialize the report
          $this->SetDescription("");
          
          // prepare a master array with items for the report
          $total = count($domainsGroup);
          for ($i=0; $i<$total; $i++) {
            $masterGroup[] = array($domainsGroup[$i], $customerGroup[$i], $planGroup[$i]);
          }
          // add all items to the report and set up column names
          $reportLastDomain = $firstDomain + $numDomainsToShow;
          $reportFirstDomain = $firstDomain + 1;
          $this->Add($masterGroup, $this->user->lang('Customer Domains'), array($this->user->lang('Domains').' '.$reportFirstDomain.' '.$this->user->lang('through').' '.$reportLastDomain, $this->user->lang('Customer'), $this->user->lang('Package')));
          
          // send the report to the browser
          $this->Show();
          

          // display the "next" and "back" links to move through the list of domains
          // ...and make sure we don't try to look at database rows that don't exist
          if (!isset($filter)) {
              $nextBackLinks  = "";
              if ($firstDomain > 0) {
                $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=reports&amp;report=Customer+Domains&amp;type=Account+%26+Packages&amp;view=ViewReport&amp;firstDomain=" . $firstDomain . "&amp;go=back'>".$this->user->lang('Back')."</a>";
              }
              if (($firstDomain > 0) && (($firstDomain + $numDomainsToShow) < $totalDomains)) {
                  $nextBackLinks .= " | ";
              }
          
              if (($firstDomain + $numDomainsToShow) < $totalDomains) {
                $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=reports&amp;report=Customer+Domains&amp;type=Account+%26+Packages&amp;view=ViewReport&amp;firstDomain=" . $firstDomain . "&amp;go=next'>".$this->user->lang('Next')."</a>";
              }
          }
          else {
            $nextBackLinks  = "";
          if ($firstDomain > 0) {
            $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=reports&amp;report=Customer+Domains&amp;type=Account+%26+Packages&amp;view=ViewReport&amp;firstDomain=" . $firstDomain . "&amp;filter=$filter&go=back'>".$this->user->lang('Back')."</a> | ";
          }
          if (($firstDomain + $numDomainsToShow) < $totalDomains) {
            $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=reports&amp;report=Customer+Domains&amp;type=Account+%26+Packages&amp;view=ViewReport&amp;firstDomain=" . $firstDomain . "&amp;filter=$filter&go=next'>".$this->user->lang('Next')."</a> | ";
          }
          $nextBackLinks .= "[ <a title='$description' href='" . $_SERVER['PHP_SELF'] . "?fuse=reports&amp;report=Customer+Domains&amp;type=Account+%26+Packages&amp;view=ViewReport'>".$this->user->lang('Remove filter')."</a> ]";
          }
          echo $nextBackLinks;

        }
    }
}

?>
