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

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

// Get the rights of the employee logged in and check the accessibility
// authCheckEmployeeRights($emp_id, "3", "1");

// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "customerId", "cscIdRoot", "cscIdActual", "statusMessage",
                         "emp_id_act", "treeMode", "tableSort", "deactivateMenu", "f_hq_id"));

getLanguage(__FILE__);

$pageTitel = getLngt("MITARBEITER");
include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
getCurrentScript(__FILE__);

// Select user-type for mode of security check 
$userType = getFieldValueFromId("user","usr_id",$usr_id,"usr_type");
$userTypeName = getUserTypeName($userType);

// Get the rights of the employee logged in and check the accessibility
$empHasNoAccessToEmployees = false;
if ($userTypeName == "hq") :
   if (!authCheckEmployeeRights($emp_id, "3")) : $empHasNoAccessToEmployees = true; endif;
elseif ($userTypeName == "cs") :
   if (!authCheckEmployeeRights($emp_id, "2")) : $empHasNoAccessToEmployees = true; endif;
// else :
//    gotoReferer("1");     // REMARKED, because employee list will be restricted; emp. only can see himself !!!
endif;

// Check authentication verifying emmployee an his/her costcenter- and customer-association
if ( !( authCheckHQ($hq_id,$usr_id,$emp_id) || authCheck($hq_id,$usr_id,$emp_id,$cscIdRoot,$customerId,$cscIdActual) ) || $userTypeName == "" ) :
   die ("$PHP_SELF: Access denied!");
endif;

if ($empHasNoAccessToEmployees) :
   header("Location: ../admin/employee.php?currentNavigationItem=zentralenmitarbeiter&emp_id_act=" . ec($emp_id) . "&customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual));
endif;

// Get the emp_id of the root admin because he/she is allowed to change a password of an employee
$empIdRootAdmin = getEmpIdOfRootAdmin($userTypeName);

$empHasNoAccessToEmployeeHistory = false;
if ($userTypeName == "hq") :
   if ($emp_id == $empIdRootAdmin || authCheckEmployeeRights($emp_id, "32")) : $empHasNoAccessToEmployeeHistory = true; endif;
endif;

// Get ALL administrator IDs
$empIdRootArr = getColVectorFromDB2ArrayByClause("headquarters", "hq_admin", "", "", "hq_admin", "");

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = array(); endif;
if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

// Get the rights of the employee logged in
$empRights = getRights($emp_id);

// Secure-check of the association between customer and the ACTUAL(!) costcenter 
// Is it the same customer like for the "root"-costcenter?
$tmpFields = array("cs_id",$customerId,"csc_id",$cscIdActual);
if ($userTypeName == "hq" || existsEntry("costcenter",$tmpFields)) : 

   // $treeMode decides to show the employees only of the current costcenter or all 
   // employees of all sub-costcenters inclusive the actual one
   if ($treeMode != "") : $treeMode = TRUE; else : $treeMode = FALSE; endif;
   if ($tableSort == "") : $tableSort = "usr_name"; endif;
   
   $cscNameActual = getFieldValueFromId("costcenter","csc_id",$cscIdActual,"csc_name");

   // Get the user_id of the current employee in $emp_id_act
   $usrId = getFieldValueFromId("employee", "emp_id", $emp_id_act, "usr_id");

   // Remove employee
   if ($f_act == "removeEmployee" && $emp_id_act != "") :
      if ( ($userTypeName == "hq" && !existsEntry("headquarters",array("hq_admin",$emp_id_act))) || ($userTypeName == "cs" && !existsEntry("customer",array("cs_admin",$emp_id_act))) ) :
         if ($usrId != "") :

            TA("B");

            $tmpUsrName = getFieldValueFromId("user", "usr_id", $usrId, "usr_name");
            $tmpUsrFirstName = getFieldValueFromId("user", "usr_id", $usrId, "usr_firstname");
            $tmpUsrAccount = getFieldValueFromId("user", "usr_id", $usrId, "usr_firstname");
            $tmpUsrPassword = getFieldValueFromId("user", "usr_id", $usrId, "usr_password");
            $tmpEmpRigths = getFieldValueFromId("employee", "emp_id", $emp_id_act, "emp_rights");
            $logString = makeLogString(array($tmpUsrName,$tmpUsrFirstName,$tmpUsrAccount,$tmpEmpRigths,$tmpUsrPassword,$tmpEmpRigths), ";", "0");

            deleteStmt("employee","emp_id = ".$emp_id_act);
            deleteStmt("user","usr_id = ".$usrId);                  
            
            // Write logdata into log database
            writeToLogDB("75",$hq_id,"",$usr_id,"","","","STATUS_DELETED=" . $logString,"","",$emp_id_act);
            
            TA("C");
            TA("E");
            
            // Check for execute functionality
            if ($GLOBAL_USAGE_HASH) :
               // Get current global number of THIS database instance
               $constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");
               if ($constGlobalDbInstNo != "" && is_numeric($constGlobalDbInstNo)) :
                  // Get database instance connection data of metaobject
                  $constExtDbInst = getExternalMetaDbInst();
                  $db_conn = getDbConnectionSpecial($constExtDbInst, $dbname, $dblogin, $dbpassword);
                  $tmpSqlQuery = "DELETE FROM meta_object.metaobject WHERE mo_id_ref_db = '" . $constGlobalDbInstNo . "' AND mo_obj_type = 'usr' AND mo_obj_id = '" . $usrId . "'";
                  $result = $db_conn->query($tmpSqlQuery);
                  $err = "";
                  if (DB::isError($result)) {$err = "ERR";};
                  if ($err == "ERR") :
                     // Message to system administrator...
                     // $statusMessage = getLngt("Message to system administrator...!");
                  endif;
               endif;
            endif;
         else : 
            $statusMessage = getLngt("Datenfehler! Löschen Sie bitte den Mitarbeiter und legen Sie ihn neu an! :-(");
         endif;
      else :
         $statusMessage = getLngt("Der Administratoreintrag kann nicht entfernt werden! ;-)");
      endif;
   endif;

 
   // **********************************************************************************************
   // * Selection of all employees of the actual costcenter (customer) or headquarter for the list *
   // **********************************************************************************************

   // Check if employee has NO access to other employees
   $whereClause = "";
   if ($empHasNoAccessToEmployees) :
      $whereClause = " AND emp.emp_id = '" . $emp_id . "'";
   endif;

   if ($userTypeName == "hq") :

      $sqlquery = "SELECT emp.emp_id, usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_phone,"
                   . "    usr.usr_phone2, usr.usr_account, hq.hq_mnemonic"
                   . " FROM user AS usr, employee AS emp, headquarters AS hq"
                   . " WHERE usr.usr_type = '1' AND emp.usr_id = usr.usr_id AND emp.csc_id = '0' AND usr.hq_id = hq.hq_id AND hq.hq_id IN " . getSQLMandatorArray($f_hq_id) . " " . $whereClause
                   . " ORDER BY $tableSort";
   endif;
   
   if ($userTypeName == "cs") :
   
      if ($treeMode) :
         $sqlquery = "SELECT emp.emp_id, usr.usr_name, usr.usr_firstname, usr.usr_email, usr.usr_phone,"
                      . "    usr.usr_phone2, usr.usr_account, csc.csc_name"
                      . " FROM user AS usr, employee AS emp, costcenter AS csc"
                      . " WHERE emp.usr_id = usr.usr_id AND emp.csc_id = csc.csc_id AND csc.cs_id = '$customerId' AND"
                      . " (csc.csc_path LIKE '%//$cscNameActual//%' OR csc.csc_id = '$cscIdActual')" . $whereClause
                      . " ORDER BY $tableSort";   
      else :
         $sqlquery = "SELECT emp.emp_id, usr.usr_name, usr.usr_firstname, usr.usr_email,"
                      . "    usr.usr_phone, usr.usr_phone2, usr.usr_account"
                      . " FROM user AS usr, employee AS emp"
                      . " WHERE emp.usr_id = usr.usr_id AND csc_id = '$cscIdActual'" . $whereClause
                      . " ORDER BY $tableSort";
      endif;
   endif;
   $result = $db->query($sqlquery);
   if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
   
   // Only for output
   $treeModeOut = "";
   $treeModeOut2 = "";
   if ($userTypeName == "hq") :
      $treeModeLinkText = "";
   else : 
      $treeModeLinkText = getLngt("Mitarbeiter der aktuellen Kostenstelle");
      if ($treeMode) : 
         $treeModeOut2 = "&treeMode=true";
      else :
         $treeModeOut = "&treeMode=true"; 
         $treeModeLinkText = getLngt("Mitarbeiter aller Unterkostenstellen");
      endif;
   endif;

   // Maintable with header
   $numOfUser = 0;   
   $tableOfEmployees = "<table border=\"0\" cellpadding=\"5\">";
   $tableOfEmployees .= "<tr class=\"f8bp1\">";
   if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) :
      $tableOfEmployees .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_name';document.forms[0].submit();\">" . getLngt("Name") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_firstname';document.forms[0].submit();\">" . getLngt("Vorname") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='hq_mnemonic';document.forms[0].submit();\">" . getLngt("Niederlassung") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_email';document.forms[0].submit();\">" . getLngt("E-Mail") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_phone';document.forms[0].submit();\">" . getLngt("Telefon") . "</a></td>";  
      $tableOfEmployees .= "<td>&nbsp;<a href=\"javascript:document.forms[0].tableSort.value='usr_account';document.forms[0].submit();\">" . getLngt("Anmeldename") . "</a></td>";      
      $tableOfEmployees .= "<td>&nbsp;" . getLngt("Löschen") . "</td>";
      if ($empHasNoAccessToEmployeeHistory) :
         $tableOfEmployees .= "<td>&nbsp;" . getLngt("Historie") . "</td>";
      endif;
      $tableOfEmployees .= "<td>&nbsp;" . getLngt("Bearbeiten") . "</td>";
   else :
      $tableOfEmployees .= "<td>&nbsp;<a href=\"../admin/employee_list.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . $treeModeOut2 . "&currentNavigationItem=zentralenmitarbeiter&tableSort=usr_name\">" . getLngt("Name") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"../admin/employee_list.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . $treeModeOut2 . "&currentNavigationItem=zentralenmitarbeiter&tableSort=usr_firstname\">" . getLngt("Vorname") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"../admin/employee_list.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . $treeModeOut2 . "&currentNavigationItem=zentralenmitarbeiter&tableSort=usr_email\">" . getLngt("E-Mail") . "</a></td>";
      $tableOfEmployees .= "<td>&nbsp;<a href=\"../admin/employee_list.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . $treeModeOut2 . "&currentNavigationItem=zentralenmitarbeiter&tableSort=usr_phone\">" . getLngt("Telefon") . "</a></td>";  
      $tableOfEmployees .= "<td>&nbsp;<a href=\"../admin/employee_list.php?customerId=" . ec($customerId) . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . $treeModeOut2 . "&currentNavigationItem=zentralenmitarbeiter&tableSort=usr_account\">" . getLngt("Anmeldename") . "</a></td>";      
      if ($treeMode) : $tableOfEmployees .= "<td>" . getLngt("Kostenstelle") . "</td>"; endif;
      $tableOfEmployees .= "<td>&nbsp;" . getLngt("Löschen") . "</td>";
      $tableOfEmployees .= "<td>&nbsp;" . getLngt("Bearbeiten") . "</td>";
   endif;
   $tableOfEmployees .= "</tr>";

   $rowCounter = 0;
   $lineToggler = 0;   
   while ($row = $result->fetch_assoc()):
         $numOfUser++;

         $cellColor = getListColor($numOfUser, $lineToggler);

         $tableOfEmployees .= "<tr>";
         $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . "<a href=\"employee.php?emp_id_act=" . ec($row["emp_id"])
                                       . "&customerId=" . ec($customerId)
                                       . "&cscIdRoot=" . ec($cscIdRoot)
                                       . "&cscIdActual=" . ec($cscIdActual)
                                       . "&deactivateMenu=" . ec(1)
                                       . "\" target=\"_blank\">" . $row["usr_name"]
                                       . "</a>" . "</td>";
         $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_firstname"] . "</td>";
         if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) :
            $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["hq_mnemonic"] . "</td>";
         endif;
         $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_email"] . "</td>";
         $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_phone"] . "</td>";

         $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["usr_account"] . "</td>";

         if ($treeMode) : $tableOfEmployees .= "<td bgcolor=\"" . $cellColor ."\">&nbsp;" . $row["csc_name"] . "</td>"; endif;
         $tableOfEmployees .= "<td align=\"center\" bgcolor=\"" . $cellColor ."\"><a href=\"javascript:removeEmployee('".ec("removeEmployee")."','".ec($row["emp_id"])."','".$row["usr_account"]."','".ec($customerId)."','".ec($cscIdRoot)."','".ec($cscIdActual)."');\">"
                                       . "<img src=\"../images/trash.jpg\" border=\"0\" height=\"13\" width=\"8\">" 
                                       . "</a>" . "</td>";
         if ($empHasNoAccessToEmployeeHistory) :
            $tableOfEmployees .= "<td align=\"center\" bgcolor=\"" . $cellColor ."\">";
            if ($emp_id == $empIdRootAdmin || !in_array($row["emp_id"], $empIdRootArr)) :
               $tableOfEmployees .= "<a href=\"history.php?history_mode=" . ec(4) . "&empIdHist=" . ec($row["emp_id"]) . "&customerId=" . ec($customerId)
                                        . "&cscIdRoot=" . ec($cscIdRoot) . "&cscIdActual=" . ec($cscIdActual) . "&deactivateMenu=" . ec(1)
                                        . "\" target=\"_blank\">"
                                        . "<img src=\"../images/arrow_right.png\" border=\"0\" height=\"10\" width=\"25\">"
                                        . "</a>";
            endif;
            $tableOfEmployees .= "</td>";
         endif;
         $tableOfEmployees .= "<td align=\"center\" bgcolor=\"" . $cellColor ."\"><a href=\"employee.php?emp_id_act=" . ec($row["emp_id"])
                                       . "&customerId=" . ec($customerId)
                                       . "&cscIdRoot=" . ec($cscIdRoot)
                                       . "&cscIdActual=" . ec($cscIdActual)
                                       . "&deactivateMenu=" . ec(1)
                                       . "\" target=\"_blank\">"
                                   . "<img src=\"../images/arrow_right.png\" border=\"0\" height=\"10\" width=\"25\">"
                                   . "</a>" . "</td>";
         $tableOfEmployees .= "</tr>";
         
         $usrName = $row["usr_name"];
         $usrFirstname = $row["usr_firstname"];
   endwhile;
   $tableOfEmployees .= "</table>";
   $result->free();   
endif;
?>

<html>

<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

function removeEmployee(f_act,emp_id_act,emp_act_account,cs_id,csc_id_root,csc_id_actual) {
  if (confirm('Benutzer ' + emp_act_account + ' entfernen?')) {
     document.location.href = "employee_list.php?f_act="+f_act+"&emp_id_act="+emp_id_act+"&customerId="+cs_id+"&cscIdRoot="+csc_id_root+"&cscIdActual="+csc_id_actual+"&currentNavigationItem=zentralenmitarbeiter";
  };
};

function finishPage() {
  document.forms[0].submit();
}

function newEmployee() {
  document.location.href = "employee.php?customerId=<?php echo ec($customerId) ?>&cscIdRoot=<?php echo ec($cscIdRoot) ?>&cscIdActual=<?php echo ec($cscIdActual) ?>&currentNavigationItem=zentralenmitarbeiter" ;
};

function employeeHistory(empId) {
  var widthPopupWin = 1000;
  var heightPopupWin = 900;
  var leftPopupWin = (screen.width / 2) - (widthPopupWin / 2) - 12;
  var topPopupWin = (screen.height / 2) - (heightPopupWin / 2) - 50;
  var popupWin;
  popupWin = window.open("../admin/history.php?history_mode=<?php echo ec(4) ?>&empIdHist=" + empId + "&op=0","","dependent=yes,width=" + widthPopupWin + ",height=" + heightPopupWin +",left=" + leftPopupWin + ",top=" + topPopupWin + ",scrollbars=yes");	
}
-->
</script>
</head>

<body onLoad="<?php echo $phpCurrentNavigationOnLoad ?>displayStatusMessage();">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent" name="maincontent" id="maincontent">

<form action="../admin/employee_list.php" method="post">
  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="customerId" value="<?php echo ec($customerId) ?>">
  <input type="hidden" name="cscIdRoot" value="<?php echo ec($cscIdRoot) ?>">
  <input type="hidden" name="cscIdActual" value="<?php echo ec($cscIdActual) ?>">  
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="tableSort" value="<?php echo $tableSort ?>">

  <?php echo htmlDivLineSpacer("10px"); ?>

  <!-- Headquarters checkboxes -->
  <?php if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) : ?>
    <?php echo getHeadquartersCheckboxes($f_hq_id); ?>
    <?php echo htmlDivLineSpacer("10px", "", "left"); ?>
  <?php endif; ?>

  <div class="f12bp1_blue">
    <div>
      <?php 
       if ($userTypeName == "hq") : 
          if (!$empHasNoAccessToEmployees) :
             if (authCheckEmployeeRights($emp_id, "10")) :
                $titleText = getLngt("Mitarbeiter der Niederlassungen");
             else :
                $titleText = getLngt("Mitarbeiter der Niederlassung");
             endif;
          else :
             $titleText = $usrFirstname . " " . $usrName;
          endif;
       else :   
          if (!$empHasNoAccessToEmployees) :
             if ($treeMode) : 
                $titleText = getLngt("Mitarbeiter aller Unterkostenstellen von") . " " . $cscNameActual;
             else :
                $titleText = getLngt("Mitarbeiter der Kostenstelle") . " " . $cscNameActual;
             endif;
          else :
             $titleText = $usrFirstname . " " . $usrName;
          endif;
       endif;
      ?>
    </div>
    <?php if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "10")) : ?>
       <div>
         <div <?php echo setStyleHtmlDiv("400px","left"); ?>><?php echo $titleText ?></div>
         <?php echo defineButtonType10(getLngt("Aktualisieren"), "action_reload", "document.forms[0].submit();", "100", "left", "3"); ?>
       </div>
    <?php endif; ?>
  </div>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <?php echo defineButtonType10(getLngt("Neuer&nbsp;Mitarbeiter"), "action_new", "newEmployee();", "140", "left", "50") ?>
  <?php // echo defineButtonType10(getLngt("Mitarbeiterhistorie"), "action_history", "employeeHistory(" . ec(0) . ");", "140", "left") ?>
  <?php echo htmlDivLineSpacer("20px", "", "left"); ?>

  <div>
    <table border="0">
      <tr>
        <td class="f10np1">
          <?php echo $tableOfEmployees ?>
          <br><br>
          <?php 
           if (!$empHasNoAccessToEmployees) :
              echo getLngt("Anzahl Benutzer:") . " " . $numOfUser;
           endif;
          ?>
          <br><br><br>
          <?php if (!$empHasNoAccessToEmployees) : ?>
                   <a href="../admin/employee_list.php?customerId=<?php echo ec($customerId) ?>&cscIdRoot=<?php echo ec($cscIdRoot) ?>&cscIdActual=<?php echo ec($cscIdActual) ?><?php echo $treeModeOut ?>"><?php echo $treeModeLinkText ?></a>
          <?php endif; ?>              
        </td>
      </tr>                  
    </table>
  </div>


</form>
</div>
</body>

</html>