<?php
/*=======================================================================
 *
 * employee_rights.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", "statusMessage", "emp_id_act", "emp_rights", "tableSort", "deactivateMenu", "f_hq_id"));

getLanguage(__FILE__);

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


// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1");


// Get the right of the employee logged in and check the access 
$empHasNoAccessToEmployees = TRUE;
if ($userTypeName == "hq" && authCheckEmployeeRights($emp_id, "3") && $emp_id_act != "" && is_numeric($emp_id_act) && $emp_id_act != $emp_id) : 
   $empHasNoAccessToEmployees = FALSE;
endif;
// HEADQUARTERS ACCESS
// Check accessibility to headquarters, init for headquarters logged in (also for $userTypeName != "hq")
// First check mandator of the employee logged in has to be the same (!!!) like from the employee edited !!!!
$usrIdAct = getFieldValueFromId("employee", "emp_id", $emp_id_act, "usr_id");
$hqIdAct = getFieldValueFromId("user", "usr_id", $usrIdAct, "hq_id");
$empIdActMdId = getFieldValueFromId("mandatorheadquarters", "hq_id", $hqIdAct, "md_id");
if ($empHasNoAccessToEmployees) :
   if ($md_id == "" || !is_numeric($md_id) || $md_id != $empIdActMdId) :
      $empHasNoAccessToEmployees = FALSE;
   endif;
endif;
if ($empHasNoAccessToEmployees) : gotoReferer("1"); endif;

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

$usrNameAct = getFieldValueFromId("user", "usr_id", $usrIdAct, "usr_name");
$usrFirstNameAct = getFieldValueFromId("user", "usr_id", $usrIdAct, "usr_firstname");
$usrAccountAct = getFieldValueFromId("user", "usr_id", $usrIdAct, "usr_account");


// For access restriction regarding to edit another employee, get headquarters the employee logged in has access to
$empIdAccessToHq = "";
$whereClauseHqRestriction = "";
if ($empIdRootAdmin != $emp_id) :
   $empIdAccessToHq = getFieldValueFromId("employee", "emp_id", $emp_id, "emp_headquarters");
   if ($empIdAccessToHq != "") : 
      $whereClauseHqRestriction = " AND mdhq.hq_id IN (" . $empIdAccessToHq . ")";
   endif;
endif;

// Get ALL headquarters to be displayed of the current mandator RESTRICTED by headquarters of the employee logged in
$hqVector = getColVectorFromDB2ArrayByClause("headquarters AS hq, mandatorheadquarters AS mdhq", "hq.hq_mnemonic", "mdhq.md_id = '" . $md_id . "' AND hq.hq_id = mdhq.hq_id" . $whereClauseHqRestriction, "hq.hq_id", "hq.hq_id", "");  // Returns associative array ($retArray[$row[hq_id]]= hq_mnemonic)
$hqArrayKeys = array_keys($hqVector);
$hqArrayKeysLen = count($hqArrayKeys);
$rgtVector = getColVectorFromDB2ArrayByClause("rights", "rgt_name", "", "rgt_id", "rgt_id", "");  // Returns associative array ($retArray[$row[rgt_id]]= rgt_name)
$rgtArrayKeys = array_keys($rgtVector);
$rgtArrayKeysLen = count($rgtArrayKeys);

$empIdHqRgtVector = getEmpHqRights($emp_id);          // Rights (hq-rgt-matrix) of the user logged in
$empIdActHqRgtVector = getEmpHqRights($emp_id_act);   // Rigths (hq-rgt-matrix) of the current user


// Set rights
if ($f_act == "setRights") :
   if ($emp_id_act != "") :   

      $rightsLogString = "";
               
      TA("B");

      // Remove current rights of the employee
      if ($empIdRootAdmin == $emp_id) :
         $res = deleteStmt("employeerights","emp_id = '" . $emp_id_act . "'");
      else :
         $res = deleteStmt("employeerights","emp_id = '" . $emp_id_act . "' AND hq_id IN (" . $empIdAccessToHq . ")");
      endif;
      if ($db->affected_rows > 0) :
         $rightsLogString .= "DELETED_RIGHTS=YES";
      else :
         $rightsLogString .= "DELETED_RIGHTS=NO";
      endif;

      // Insert new rigths
      $emp_rights_len = count($emp_rights);
      for ($i = 0; $i < $emp_rights_len; $i++) :

          // Get hq_id and rgt_id from the element values of the array (e.g. an element could be "102_7" corresponding with "HTG-HH"_"Export")
          $tmpArray = split("_", $emp_rights[$i]);
          $specialHqId = $tmpArray[0];
          $specialRgtId = $tmpArray[1];

          if ($specialHqId != "" && is_numeric($specialHqId) && $specialRgtId != "" && is_numeric($specialRgtId)) :

             $res = insertStmt("employeerights", array("emp_id", $emp_id_act, "hq_id", $specialHqId, "rgt_id", $specialRgtId));
             if ($db->affected_rows > 0) :
                $rightsLogString .= "|" . $specialHqId . "_" . $specialRgtId;
             endif;
          endif;
      endfor;      

      TA("C");
      TA("E");      

      // Write logdata into log database
      writeToLogDB("115",$hq_id,"",$usr_id,"","","",$rightsLogString,"","",$emp_id_act);

      // Get rights again after changing
      $empIdHqRgtVector = getEmpHqRights($emp_id);          // Rights of the user logged in
      $empIdActHqRgtVector = getEmpHqRights($emp_id_act);   // Rigths of the current user

      $statusMessage = getLngt("Die Rechte wurden gesetzt!");
   endif;
endif;


// Create hq-rgt-matrix
$output = "<table>";
$output .= "<tr>";
$output .= "<td align=\"left\">" . defineButtonType10(getLngt("Rechte&nbsp;zuweisen"), "action_set_rights", "finishPage('setRights');", "140", "left") . "</td>";  // Left top corner
// Column headlines
for ($i = 0; $i < $hqArrayKeysLen; $i++) :
    // $output .= "<td align=\"center\" width=\"50\"><b>" . $hqVector[$hqArrayKeys[$i]] . "</b></td>";
    $output .= "<td align=\"center\" width=\"50\">";
    $output .= "<b>" . $hqVector[$hqArrayKeys[$i]] . "</b><br>";
    $output .= "<span class=\"toggle_cell\"><input type=\"checkbox\" class=\"toggle_chkbx\" onclick=\"toggleColumn(" . $i . ", this)\"></span>\n";
    $output .= "</td>";
endfor;
$output .= "</tr>";
for ($j = 0; $j < $rgtArrayKeysLen; $j++) :
    $output .= "<tr>";
    $output .= "<td  width=\"150\"><b>" .  getLngt($rgtVector[$rgtArrayKeys[$j]]) . "</b></td>";
    for ($i = 0; $i < $hqArrayKeysLen; $i++) :
        $output .= "<td align=\"center\">";

        $tmpChecked = "";

        mcArrIsSet($rgtArrayKeys, $j);
        mcArrIsSet($hqArrayKeys, $i);
        $empIdActHqRgtVector[$hqArrayKeys[$i]][$rgtArrayKeys[$j]] = mcArrMultiDimIsSet($empIdActHqRgtVector[$hqArrayKeys[$i]], $rgtArrayKeys[$j]);

        if ($empIdActHqRgtVector[$hqArrayKeys[$i]][$rgtArrayKeys[$j]] == "1") : $tmpChecked = "checked"; endif;

        $tmpDisabled = "disabled";
        if ($emp_id == $empIdRootAdmin || $empIdHqRgtVector[$hqArrayKeys[$i]][$rgtArrayKeys[$j]] == "1") : $tmpDisabled = ""; endif;

        $output .= "<input type=\"checkbox\" class=\"row_" . $j . " col_" . $i . "\" name=\"emp_rights[]\" value=\"" . $hqArrayKeys[$i] . "_" . $rgtArrayKeys[$j] . "\" ".$tmpChecked." ".$tmpDisabled.">\n";
        $output .= "</td>";
    endfor;
    $output .= "<td class=\"toggle_cell\" align=\"center\"><input type=\"checkbox\" class=\"toggle_chkbx\" onclick=\"toggleRow(" . $j . ", this)\">\n</td>";
    $output .= "</tr>";
endfor;
$output .= "</table>";

?>

<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"); ?>

  .toggle_cell 
    { background-color: #e0e0e0;
      border-bottom: 2px solid #bbb;
      text-align: center; /* Zentriert den Inhalt (die Checkbox) */
      padding: 5px;      /* Etwas Luft */
    }

  .toggle_chkbx 
    { accent-color: #555;
      cursor: pointer;
    }
</style>

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

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

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

function toggleColumn(colIndex, source) {
    // Sucht nach allen Elementen mit der Klasse .col_0, .col_1 usw.
    const targets = document.querySelectorAll('.col_' + colIndex);
    
    targets.forEach(checkbox => {
      if (!checkbox.readOnly && !checkbox.disabled) {
         checkbox.checked = source.checked;
      }
    });
}

function toggleRow(rowIndex, source) {
    // Sucht nach allen Elementen mit der Klasse .row_0, .row_1 usw.
    const targets = document.querySelectorAll('.row_' + rowIndex);
    
    targets.forEach(checkbox => {
      if (!checkbox.readOnly && !checkbox.disabled) {
         checkbox.checked = source.checked;
      }
    });
}
-->
</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_rights.php" method="post">
  <input type="hidden" name="f_act" value="">
  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">
  <input type="hidden" name="emp_id_act" value="<?php echo ec($emp_id_act) ?>">

  <?php echo htmlDivLineSpacer("10px"); ?>
 
  <div class="f12bp1_blue">
    <?php echo $usrFirstNameAct . " " . $usrNameAct . " [" . $usrAccountAct . "]"; ?>
  </div>
  <?php echo htmlDivLineSpacer("20px"); ?>

  <div class="f10np1">
    <?php 
     if ($userTypeName == "hq") : 
        if (!$empHasNoAccessToEmployees) :
           echo $output;
        endif;
     endif;
    ?>
  </div>

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

</html>
