<?php
/*=======================================================================
 *
 * motivationcounter_1.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/
 

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");
include_once ("../include/html.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "f_business_volume", "f_password", "f_year", "f_month", "f_hq_id"));

// Parameters
$f_business_volume = str_replace (",", ".", $f_business_volume);
$listOfAmounts = "";
if ($f_hq_id == "") : $f_hq_id = $hq_id; endif;

/* 
// Nach Mitarbeiter gesplittet
SELECT 
    count(jb.jb_id) AS count_jobs, 
    SUM(jb.jb_totalprice) as business_volume, 
    jb.emp_id
  FROM 
    job AS jb 
  WHERE 
    jb.jb_status = '2' AND 
    jb.hq_id IN (2) AND 
    (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND 
    jb.jb_finishtime >= '2010-01-01 00:00:00' AND 
    jb.jb_finishtime <= '2010-01-31 23:59:59' 
  GROUP BY jb.emp_id 
  ORDER BY emp_id
*/

function htmlDivLineSpacerBlack ($height = "10px", $width = "", $clear = "") {
	global $constMenuBackground;
	if ($width == "") : $width = "100%"; endif;
  return "<div style=\"width:" . $width . "; height:" . $height . ";" . ($clear != "" ? "clear:" . $clear . ";" : "") . " background: #000000\"> </div>";
}

// Returns the statement to get the statistic of the sum of all jobs according to a specified datetime interval
// ONE HEADQUARTERS
function getCumulatedJobData ($fromDatetime, $toDatetime, $hqIds = "", $retMode = "0", $whereClause = "", $orderByClause = "") {
  global $db, $PHP_SELF;
	$retVal = "";

  if ($fromDatetime != "" && $toDatetime != "") :
     $whereClauseHq = "";
     if ($hqIds != "") : $whereClauseHq = " AND jb.hq_id IN (" . $hqIds . ") "; endif;
     if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
     if ($orderByClause == "") : $orderByClause = "count_jobs"; endif;

     $sqlquery = "SELECT count(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) as business_volume" .
                 " FROM job AS jb" .
                 " WHERE jb.jb_status = '2' " . $whereClauseHq . " AND " .
                 "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND" .
                 "       jb.jb_finishtime >= '" . $fromDatetime . "' AND" .
                 "       jb.jb_finishtime <= '" . $toDatetime . "'" . $whereClause .
                 " ORDER BY " . $orderByClause;

     if ($retMode == "0") : return $sqlquery; endif;

     // Execute statement
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     while ($row = $result->fetch_assoc()):
           $count_jobs = $row["count_jobs"];
           $business_volume = $row["business_volume"];
     endwhile;
     $result->free();

     if ($retMode == "1") : $retVal = array($count_jobs, $business_volume); endif;
     if ($retMode == "2") : $retVal = $count_jobs; endif;
     if ($retMode == "3") : $retVal = round($business_volume, 2); endif;
  endif;

  return $retVal;
}

// Returns the statement to get the statistic of the sum of all jobs according to a specified datetime interval
function getCumulatedJobDataMultiHeadquarters ($fromDatetime, $toDatetime, $whereClause = "", $orderByClause = "", $excludedHQs) {
	global $db, $PHP_SELF;
	$retVal = "";

  if ($fromDatetime != "" && $toDatetime != "") :
     $whereClauseHq = "";
     if ($excludedHQs != "") : $whereClauseHq = " AND jb.hq_id NOT IN (" . $excludedHQs . ") "; endif;
     if ($whereClause != "") : $whereClause = " AND " . $whereClause; endif;
     if ($orderByClause == "") : $orderByClause = "count_jobs"; endif;

     $sqlquery = "SELECT count(jb.jb_id) AS count_jobs, SUM(jb.jb_totalprice) as business_volume, hq.hq_id, hq.hq_mnemonic" .
                 " FROM job AS jb, headquarters AS hq" .
                 " WHERE jb.jb_status = '2'" . $whereClauseHq . " AND " .
                 "       (isnull(jb.jb_storno) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3') AND" .
                 "       jb.jb_finishtime >= '" . $fromDatetime . "' AND" .
                 "       jb.jb_finishtime <= '" . $toDatetime . "'" . $whereClause . " AND" .
                 "       jb.hq_id = hq.hq_id" .
                 " GROUP BY jb.hq_id" .
                 " ORDER BY " . $orderByClause;

     // Execute statement
     $result = $db->query($sqlquery);
     if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
     $hq_mnemonic = array();
     $count_jobs = array();
     $business_volume = array();
     while ($row = $result->fetch_assoc()):
           $hq_mnemonic[$row["hq_id"]] = $row["hq_mnemonic"];
           $count_jobs[$row["hq_id"]] = $row["count_jobs"];
           $business_volume[$row["hq_id"]] = $row["business_volume"];
     endwhile;
     $result->free();

     $retVal = array($hq_mnemonic, $count_jobs, $business_volume);
  endif;

  return $retVal;
}


// Set color of the difference amount
function getColorOfAmount ($percentValue) {
  $colorOfBalanceDue = "#FF0000";
  if ($percentValue >= 100) : 
     $colorOfBalanceDue = "#00FF00";
  elseif ($percentValue < 10) : 
     $colorOfBalanceDue = "#FF2200";
  elseif ($percentValue >= 10 && $percentValue < 20) : 
     $colorOfBalanceDue = "#FF5500";
  elseif ($percentValue >= 20 && $percentValue < 30) :
     $colorOfBalanceDue = "#FF9900";
  elseif ($percentValue >= 30 && $percentValue < 40) : 
     $colorOfBalanceDue = "#FFCC00";
  elseif ($percentValue >= 40 && $percentValue < 50) : 
     $colorOfBalanceDue = "#FFFF00";
  elseif ($percentValue >= 50 && $percentValue < 60) : 
     $colorOfBalanceDue = "#CCFF00";
  elseif ($percentValue >= 60 && $percentValue < 70) : 
     $colorOfBalanceDue = "#99FF00";
  elseif ($percentValue >= 70 && $percentValue < 80) : 
     $colorOfBalanceDue = "#55FF00";
  elseif ($percentValue >= 80 && $percentValue < 90) : 
     $colorOfBalanceDue = "#22FF00";
  elseif ($percentValue >= 90 && $percentValue < 100) : 
     $colorOfBalanceDue = "#00FF00";
  endif;
  return $colorOfBalanceDue;
};


$currentYear  = getDateTime("year");
$currentMonth = getDateTime("month");
$currentDay   = getDateTime("day");

$fromDatetime = $currentYear . "-" . $currentMonth . "-01 00:00:00";
$toDatetime   = $currentYear . "-" . $currentMonth . "-" . $currentDay . " 23:59:59";


// *** STORE DATA BEGIN ***
if ($f_act == "storeAmount") :
   // Check for password
   $parMotivationcounterPassword = getParameterValue("0", "MOTIVATIONCOUNTER_PASSWORD", $f_hq_id);
   if ($parMotivationcounterPassword != "" && $parMotivationcounterPassword == $f_password) :
      // Check for selected year and month
      if ($f_year != "" && $f_month != "") :
         $f_month = pad($f_month, 2);
         // Check for not overwriting months before
         if ($f_year . $f_month >= $currentYear . $currentMonth) :
            if ($f_business_volume != "" && is_numeric($f_business_volume)) :
               $parKey = "MOTIVATIONCOUNTER_" . $f_year . "_" . $f_month;
               if (existsEntry("parameter",array("par_key",$parKey,"emp_id","0","hq_id",$f_hq_id))) :
                  updateStmt("parameter", "emp_id", "0", array("par_value", $f_business_volume), " par_key = '" . $parKey . "' AND hq_id = '" . $f_hq_id . "'");
               else:
                  insertStmt("parameter", array("par_key", $parKey, "emp_id", "0", "par_value", $f_business_volume, "hq_id", $f_hq_id));
               endif;
               $f_year = "";
               $f_month = "";
            else :
               $statusMessage = "Sie müssen bitte auch einen Betrag eingeben!";
            endif;
         else :
            $statusMessage = "Ältere Monate dürfen nicht überschrieben werden!";
         endif;
      endif;
   else :
      $statusMessage = "Das Passwort ist nicht korrekt!";
   endif;
endif;

if ($f_act == "listAmounts") :
   // Check for password
   $parMotivationcounterPassword = getParameterValue("0", "MOTIVATIONCOUNTER_PASSWORD", $hq_id);
   if ($parMotivationcounterPassword != "" && $parMotivationcounterPassword == $f_password) :
      // Get all parameters "MOTIVATIONCOUNTER_YYYY_mm" in database for the current headquarters
      $sqlquery = "SELECT par.par_key, par.par_value FROM parameter AS par"
                . " WHERE par.par_key LIKE 'MOTIVATIONCOUNTER_2%' AND"
                . "       par.hq_id = '". $hq_id . "' AND"
                . "       par.emp_id = '0'"
                . " ORDER BY par.par_key";
                
      $result = $db->query($sqlquery);
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      $insertFlag = TRUE;
      while ($row = $result->fetch_assoc()):
            $listOfAmounts .= "<tr>\n";
            $listOfAmounts .= "<td align=\"center\">" . substr($row["par_key"], 18, 4) . "</td>\n";   // Year extracted out of par_key
            $listOfAmounts .= "<td align=\"center\">" . substr($row["par_key"], 23, 2) . "</td>\n";   // Month extracted out of par_key
            $listOfAmounts .= "<td align=\"right\">" . number_format($row["par_value"], 2, ",", ".") . "</td>\n";                        
            $listOfAmounts .= "</tr>\n";
      endwhile;
      if ($listOfAmounts != "") :
         $listOfAmounts = "<div style=\"width:100%; padding: 0px; margin: 0px; border: 0px; outline: 0px; text-align:center; vertical-align:middle;\"><br><br><table border=\"0\" align=\"center\">\n" .
                          "<tr><td align=\"center\">&nbsp;<b>Jahr</b>&nbsp;</td><td align=\"center\">&nbsp;<b>Monat</b>&nbsp;</td><td align=\"center\">&nbsp;<b>Soll</b>&nbsp;</td></tr>\n" .
                          $listOfAmounts .
                          "</table></div>\n";
      endif;
      $result->free();
      
      
   else :
      $statusMessage = "Das Passwort ist nicht korrekt!";
   endif;
endif;
// *** STORE DATA END ***


// Check for output mode for only one headquarters or for all headquarters with exceptions
$parMotivationCounterMode = getParameterValue("0", "MOTIVATIONCOUNTER_MODE", "0");
if ($parMotivationCounterMode == "") : $parMotivationCounterMode = "0"; endif;
if ($parMotivationCounterMode == "0") :
   // SINGLE HEADQUARTERS

   // Get business volume of the current month done by finished jobs
   $businessVolume = getCumulatedJobData($fromDatetime, $toDatetime, $hq_id, "3", "", "");
   $businessVolumeOut = number_format($businessVolume, 2, ",", ".");

   // Get presetting set by leader
   $parBusinessVolumeCurrentMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $currentYear . "_" . $currentMonth, $hq_id);
   if ($parBusinessVolumeCurrentMonth == "") : $parBusinessVolumeCurrentMonth = 0; endif;
   $parBusinessVolumeCurrentMonth = round($parBusinessVolumeCurrentMonth, 2);
   $parBusinessVolumeCurrentMonthOut = number_format($parBusinessVolumeCurrentMonth, 2, ",", ".");

   // Difference amount
   $balanceDue = ($parBusinessVolumeCurrentMonth - $businessVolume);
   $balanceDue = round($balanceDue,2);
   if ($balanceDue < 0) :
      $balanceDue = $balanceDue * (-1);
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
      $balanceDueOut = "+&nbsp;" . $balanceDueOut;
   else :
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
   endif;

   // Percent value
   $percentValue = 0;
   $colorOfBalanceDue = getColorOfAmount ($percentValue);
   $percentValueOut = "";
   if ($parBusinessVolumeCurrentMonth != "0") :
      $percentValue = (($businessVolume / $parBusinessVolumeCurrentMonth) * 100);   
      $percentValue = round($percentValue,2);
      $colorOfBalanceDue = getColorOfAmount ($percentValue);
      $percentValueOut = "<div style=\"color:" . $colorOfBalanceDue . "; font-size:10pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;\">" .
                         "[&nbsp;" . number_format($percentValue, 2, ",", ".") . "&nbsp;%&nbsp;erreicht&nbsp;]" .
                         "</div>";
   endif;

   // Percent value bar
   $tmpPercentValue = round(($percentValue * 4),0);
   $tmpPercentValue2 = (400 - $tmpPercentValue);
   $percentValueBarOut .= "<img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\">";
   $percentValueBarOut .= "<img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\">";

else :
   // MULTI HEADQUARTERS

   // Get business volume of the current month done by finished jobs
   $multiArray = getCumulatedJobDataMultiHeadquarters($fromDatetime, $toDatetime, "", "", "203");

   $hqMnemonicArray = $multiArray[0];
   $countJobsArray = $multiArray[1];
   $businessVolumeArray = $multiArray[2];

   // Business volume of the current headquarters
   $businessVolume = round($businessVolumeArray[$hq_id], 2);
   $businessVolumeOut = number_format($businessVolumeArray[$hq_id], 2, ",", ".");

   $parBusinessVolumeCurrentMonthArray = array();
   $percentValueArray = array();
   $outArray = array();

   $tmpKeys = array_keys($businessVolumeArray);   // Headquarters IDs
   $tmpKeysLen = count($tmpKeys);
   for ($i = 0; $i < $tmpKeysLen; $i++) :
       $currHqId = $tmpKeys[$i];

       // Get presetting set by leader
       $parBusinessVolumeCurrentMonth = getParameterValue("0", "MOTIVATIONCOUNTER_" . $currentYear . "_" . $currentMonth, $currHqId);
       if ($parBusinessVolumeCurrentMonth == "") : $parBusinessVolumeCurrentMonth = 0; endif;
       $parBusinessVolumeCurrentMonthArray[$currHqId] = round($parBusinessVolumeCurrentMonth, 2);

       // Percent value
       $percentValue = 0;
       if ($parBusinessVolumeCurrentMonth != "0") :
          $percentValue = (($businessVolumeArray[$currHqId] / $parBusinessVolumeCurrentMonth) * 100);   
          $percentValue = round($percentValue,2);
       endif;
       if ($currHqId == $hq_id) :
          $colorOfBalanceDue = getColorOfAmount($percentValue);
          $parBusinessVolumeCurrentMonthOut = number_format($parBusinessVolumeCurrentMonth, 2, ",", ".");
       endif;

       // Percent value bar
       $tmpPercentValue = round(($percentValue * 4),0);
       $tmpPercentValue2 = (400 - $tmpPercentValue);
       $outArray[$currHqId] = "<tr><td style=\"color:#00FF00\">" . $hqMnemonicArray[$currHqId] . "&nbsp;&nbsp;&nbsp;</td><td><img src=\"../images/spacer_green.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue . "\">" .
                              "<img src=\"../images/spacer_red.jpg\" border=\"0\" height=\"20\" width=\"" . $tmpPercentValue2 . "\"></td>" .
                              "<td style=\"color:#00FF00; text-align:right;\">&nbsp;&nbsp;&nbsp;" . number_format($percentValue, 2, ",", ".") . "&nbsp;%</td></tr>\n";
   endfor;

   // Sort and output of all bars
   $percentValueBarOut .= "<table align=\"center\">";
   $percentValueBarOut .= $outArray[$hq_id];
   $percentValueBarOut .= "<tr><td colspan=\"3\"><&nbsp;></td></tr>";
   for ($i = 0; $i < $tmpKeysLen; $i++) :
       $currHqId = $tmpKeys[$i];
       if ($currHqId != $hq_id) :
          $percentValueBarOut .= $outArray[$currHqId];
       endif;
   endfor;
   $percentValueBarOut .= "</table>";
   
   // Do not show the single percent value
   $percentValueOut = "";

   // Difference amount
   $balanceDue = ($parBusinessVolumeCurrentMonthArray[$hq_id] - $businessVolume);
   $balanceDue = round($balanceDue,2);
   if ($balanceDue < 0) :
      $balanceDue = $balanceDue * (-1);
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
      $balanceDueOut = "+&nbsp;" . $balanceDueOut;
   else :
      $balanceDueOut = number_format($balanceDue, 2, ",", ".");
   endif;
endif;

// Output
if ($f_year == "") : $f_year = $currentYear; endif;
if ($f_month == "") : $f_month = $currentMonth; endif;
?>


<html>
<head>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css"> 

<script type="text/javascript">

var refreshStatus = 1;
var statusMessage = "<?php echo $statusMessage ?>";

function displayStatusMessage() {
 if (statusMessage != "") {
    alert(statusMessage);
 }
};

function startReload() {  
  if (refreshStatus == 1) {
     // self.location.reload();
     document.forms[0].submit();
  }
}

function startTimeout() {  
  self.setTimeout("startReload()", 180000);
}

function finishPage(f_act) {
	document.forms[0].f_act.value = f_act;
  document.forms[0].submit();
}
</script>
</head>

<body style="background:#777777; padding: 0px; margin: 0px; border: 0px" onLoad="startTimeout();displayStatusMessage();">

  <form action="../tools/motivationcounter_1.php" method="post">

    <input type="hidden" name="f_act" value="">

    <?php if ($parMotivationCounterMode == "0") : echo htmlDivLineSpacerBlack("250px"); else : echo htmlDivLineSpacerBlack("50px"); endif; ?>

    <div style="width:100%; <?php if ($parMotivationCounterMode == "0") : echo "height:100px;"; endif; ?> padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
      <div style="color:<?php echo $colorOfBalanceDue ?>; font-size:40pt; font-family:Arial,Helvetica; font-weight:normal; text-align:center; vertical-align:middle;">
        <?php echo $balanceDueOut ?>&nbsp;€
      </div>
      <?php echo htmlDivLineSpacerBlack("50px"); ?>
      
      <?php echo $percentValueOut ?>
      <?php echo htmlDivLineSpacerBlack("10px"); ?>

      <?php echo $percentValueBarOut ?>
    </div>        

    <?php echo htmlDivLineSpacerBlack("300px"); ?>
    
    <div style="width:100%; height:100px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background:#000000; text-align:center; vertical-align:middle;">
      <span style="font-family: Arial, Helvetica, sans-serif; font-size: 14pt; font-weight: normal; padding: 1px; color: #7777FF;">SOLL:&nbsp;&nbsp;&nbsp;<?php echo $parBusinessVolumeCurrentMonthOut ?>&nbsp;€</span>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <span style="font-family: Arial, Helvetica, sans-serif; font-size: 14pt; font-weight: normal; padding: 1px; color: #7777FF;">IST:&nbsp;&nbsp;&nbsp;<?php echo $businessVolumeOut ?>&nbsp;€</span>
    </div>
    
    <?php echo htmlDivLineSpacerBlack("20px"); ?>
    
    <div style="width:100%; height:400px; padding: 0px; margin: 0px; border: 0px; outline: 0px; background-image:url(../images/motivationcounterfade.png);">
    </div>

    <div style="width:100%; padding: 0px; margin: 0px; border: 0px; outline: 0px; text-align:center; vertical-align:middle;">
    	<select name="f_hq_id"><?php echo addOptionsFromTable("headquarters","hq_id","hq_mnemonic","hq_id","",$f_hq_id); ?></select>
    	&nbsp;&nbsp;
      <select name="f_year"><?php echo addOptionsFromRange($currentYear,$currentYear + 1,$f_year,"") ?></select>
      &nbsp;&nbsp;
      <select name="f_month"><?php echo addOptionsFromRange(1,12,$f_month,"") ?></select>
      &nbsp;&nbsp;
      Betrag:<input class="f8np1" type="text" name="f_business_volume" value="" size="15">
      (<a href="javascript:finishPage('listAmounts');">Liste</a>)
      &nbsp;&nbsp;
      Passwort:&nbsp;<input class="f8np1" type="password" name="f_password" value="" size="15">
      &nbsp;&nbsp;
      <a href="javascript:finishPage('storeAmount');">Speichern</a>
    </div>

    <?php echo $listOfAmounts ?>
</form>

</body>

</html>

