<?php

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

$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 = $GLOBALS['db']->escape_string($_GET['filter']);
}
  
ini_set('include_path', dirname(__FILE__) . '/../..');

include_once 'config.php';
include_once 'common/varDefinitions.php';
$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 = $GLOBALS['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 = $GLOBALS['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->img->SetMargin(45,30,20,20);
  $graph->SetScale("textlin");
  $graph->SetMarginColor("white");
  
  // set up the title for the graph
  $graph->title->Set(lang('New Domains per Month'));
  $graph->title->SetColor("black");
  
  // 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->SetFillColor("#FFA500");
  $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 = $GLOBALS['db']->query($sql);
  $totalDomains = $result->getNumRows();
  
  // grab domain, customer id, plan id from database
  if(isset($_GET["filter"])) {
  $filter = $GLOBALS['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 = $GLOBALS['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);
        $tUser->PopulateCustomFields();
         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=3&frmClientID=". $userid ."&action=0\" $title>" .$dusername."</a>";
            } else {
                $title = "";
                $username =  "<a href=\"index.php?fuse=3&frmClientID=". $userid ."&action=0\" $title>" .$username."</a>";
            }
        } else {
            $username = $tUser->getFullName();
            $title = "";
            $username =  "<a href=\"index.php?fuse=3&frmClientID=". $userid ."&action=0\" $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 = $GLOBALS['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=7&report=Customer+Domains&type=Account+%26+Packages&action=0&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=".cREPORT."&report=".urlencode('Customer Domains')."&type=".urlencode('account_&_packages')."&viewimage=1&filter=".@$filter."'><br><br>";

  
  // initialize the report
  $report = new Report();
  $report->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;
  $report->Add($masterGroup, lang('Customer Domains'), array(lang('Domains').' '.$reportFirstDomain.' '.lang('through').' '.$reportLastDomain, lang('Customer'), lang('Package')));
  
  // send the report to the browser
  $report->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=7&report=Customer+Domains&type=Account+%26+Packages&action=0&firstDomain=" . $firstDomain . "&go=back'>Back</a>";
      }
      if (($firstDomain > 0) && (($firstDomain + $numDomainsToShow) < $totalDomains)) {
          $nextBackLinks .= " | ";
      }
  
      if (($firstDomain + $numDomainsToShow) < $totalDomains) {
        $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=7&report=Customer+Domains&type=Account+%26+Packages&action=0&firstDomain=" . $firstDomain . "&go=next'>Next</a>";
      }
  }
  else {
    $nextBackLinks  = "";
  if ($firstDomain > 0) {
    $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=7&report=Customer+Domains&type=Account+%26+Packages&action=0&firstDomain=" . $firstDomain . "&filter=$filter&go=back'>Back</a>";
  }
  $nextBackLinks .= " | ";
  if (($firstDomain + $numDomainsToShow) < $totalDomains) {
    $nextBackLinks .= "<a href='" . $_SERVER['PHP_SELF'] . "?fuse=7&report=Customer+Domains&type=Account+%26+Packages&action=0&firstDomain=" . $firstDomain . "&filter=$filter&go=next'>Next</a>";
  }
  $nextBackLinks .= " | ";
  $nextBackLinks .= "[ <a title='$description' href='" . $_SERVER['PHP_SELF'] . "?fuse=7&report=Customer+Domains&type=Account+%26+Packages&action=0'>Remove filter</a> ]";
  }
  echo $nextBackLinks;

}
?>
