<?php
/*=======================================================================
 *
 * html.inc.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


// Creates HTML-Options for the SELECT-Tag from a range of numbers
function addOptionsFromRange($numFrom, $numTo, $numSelected = "", $emptyItem = "", $padLength = "", $padSign = " ", $loopIterator = 1, $lf = "\n") {
  $options = "";
  if ($emptyItem != "") :
     $options .= "<option value=\"\"> </option>" . $lf;
  endif;
  if ($loopIterator == "" || !is_numeric($loopIterator)): $loopIterator = 1; endif;
  for ($i = $numFrom; $i <= $numTo; $i += $loopIterator) :
      if ($numSelected == "" || $numSelected != $i) :
         $options .= "<option value=\"$i\">" . ($padLength != "" ? pad($i,$padLength,$padSign) : $i) . "</option>" . $lf;
      else :
         $options .= "<option value=\"$i\" selected>" . ($padLength != "" ? pad($i,$padLength,$padSign) : $i) . "</option>" . $lf;
      endif;       
  endfor;  
  return $options;
}

// Creates HTML-Options for the SELECT-Tag from an ASSOCIATIVE array of option values
function addOptionsFromAssociativeArray($optionArray, $numSelected = "", $emptyItem = "", $valueMode = "0", $prefix = "", $lf = "\n") {
  $options = "";
  if ($optionArray == "") : $optionArray = array(); endif;
  if (count($optionArray) > 0) :
     if ($emptyItem != "") :
        $options .= "<option value=\"\"> </option>" . $lf;
     endif;  
     foreach ($optionArray as $key => $value) {
     	  $isSelected = "";
        if ($numSelected != "" && $numSelected == $key) : $isSelected = " selected"; endif;
        
        if ($valueMode == "1") :
          $options .= "<option value=\"" . $prefix . $value . "\"" . $isSelected . ">" . $prefix . $value . "</option>" . $lf;
        elseif ($valueMode == "2") :
          $options .= "<option value=\"" . $prefix . $key . "\"" . $isSelected . ">" . $prefix . $key . "</option>" . $lf;
        elseif ($valueMode == "3") :
          $options .= "<option value=\"" . $prefix . $value . "\"" . $isSelected . ">" . $prefix . $key . "</option>" . $lf;
        else :
          $options .= "<option value=\"" . $prefix . $key . "\"" . $isSelected . ">" . $prefix . $value . "</option>" . $lf;
        endif;
     };
  endif;
  return $options;
}

// Creates HTML-Options for the SELECT-Tag from an array of option values
function addOptionsFromArray($optionArray, $numSelected = "", $emptyItem = "", $lf = "\n") { 
  $options = "";
  if ($emptyItem != "") :
     $options .= "<option value=\"\"> </option>" . $lf;
  endif;
  $lenArray = count($optionArray);
  for ($i = 0; $i < $lenArray; $i++) :
      if ($numSelected == "" || $numSelected != $optionArray[$i]) :
         $options .= "<option value=\"$optionArray[$i]\">$optionArray[$i]</option>" . $lf;
      else :
         $options .= "<option value=\"$optionArray[$i]\" selected>$optionArray[$i]</option>" . $lf;
      endif;       
  endfor;
  return $options;
}

// Creates HTML-Options for the SELECT-Tag from two arrays (option values and corresponding texts)
function addOptionsAndTextsFromArrays($optionArray, $textArray, $numSelected = "", $emptyItem = "", $lf = "\n") {
  $options = "";
  if ($emptyItem != "") :
     $options .= "<option value=\"\"> </option>" . $lf;
  endif;
  $lenArray = min(count($optionArray),count($textArray));  
  for ($i = 0; $i < $lenArray; $i++) :
      if ($numSelected == "" || $numSelected != $optionArray[$i]) :
         $options .= "<option value=\"$optionArray[$i]\">$textArray[$i]</option>" . $lf;
      else :
         $options .= "<option value=\"$optionArray[$i]\" selected>$textArray[$i]</option>" . $lf;
      endif;       
  endfor;  
  return $options;
}

// Creates HTML-Options for the SELECT-Tag from a text array
function addOptionsGenericText($optionTextArray, $numSelected = "", $emptyItem = "", $lf = "\n") {
  $options = "";
  if ($emptyItem != "") :
     $options .= "<option value=\"\"> </option>" . $lf;
  endif;
  $lenOptionTextArray = count($optionTextArray);
  for ($i = 0; $i < $lenOptionTextArray; $i++) :
      $options .= "<option value=\"" . $i . "\" " . ($numSelected == $i ? "selected" : "") . ">" . ($optionTextArray[$i] != "" ? $optionTextArray[$i] : $i) . "</option>" . $lf;
  endfor;  
  return $options;
}

// Generates a button
// $content     : Content of the button
// $name        : Name and ID of the button usable for Javascript
// $action      : Javascript function for onClick (e.g. "finishPage(...);")
// $paddingTop  : Distance of the text to the top of the button element
// $paddingLeft : Distance of the text to the left of the button element
// $width       : With of the button
// $height      : Height of the button
// $fontXXX     : Font informations
function defineButton ($content, $name = "", $action = "", $float = "", $postspaces = "", $paddingTop = "", $paddingLeft = "", $width = "", $height = "", $background = "", $color = "", $fontSize = "", $fontWeight = "", $fontStyle = "", $fontFamily = "", $title = "", $accesskey = "", $submit = false, $disabled = "", $inDiv = "1") {
	global $constButtonBackground, $constButtonColor, $constButtonOnMouseOverColor, $usedFramework;

	// Make HTML
  $outHTML = "";  
  if ($name == "") : $name = "button"; endif;
  if ($action == "") : $action = "document.forms[0].submit();"; endif;
  if ($paddingTop == "") : $paddingTop = "0px"; endif;
    if (is_numeric($paddingTop)) : $paddingTop .= "px"; endif;
  if ($paddingLeft == "") : $paddingLeft = "5px"; endif;
    if (is_numeric($paddingLeft)) : $paddingLeft .= "px"; endif;  
  if ($width == "") : $width = "120px"; endif;
    if (is_numeric($width)) : $width .= "px"; endif;
  if ($height == "") : $height = "25px"; endif;
    if (is_numeric($height)) : $height .= "px"; endif;
  if ($background == "") : $background = $constButtonBackground; endif;
    if (substr($background, 0, 1) != "#") : $background = "#" . $background; endif;
  if ($color == "") : $color = $constButtonColor; endif;
    if (substr($color, 0, 1) != "#") : $color = "#" . $color; endif;
  if ($fontSize == "") : $fontSize = "12pt"; endif;
    if (is_numeric($fontSize)) : $fontSize .= "pt"; endif;
  if ($fontWeight == "") : $fontWeight = "bold"; endif;
  if ($fontStyle == "") : $fontStyle = "normal"; endif;
  if ($fontFamily == "") : $fontFamily = "Helvetica,Arial"; endif;
  if ($submit == true) : $type = "submit"; else : $type = "button"; endif;
  $frameworkOnMouseOver = "vSetCss('" . $name . "', {color: '" . $constButtonOnMouseOverColor . "'})";
  $frameworkOnMouseOut = "vSetCss('" . $name . "', {color: '" . $color . "'})";
  if ($inDiv == "1") :
     $outHTML .= "<div name=\"d_" . $name . "\" id=\"d_" . $name . "\" style=\"" . ($float != "" ? "float:" . $float . ";" : "") . "\" >\n";
  endif;
  $outHTML .= "<input type=\"$type\" name=\"$name\" id=\"$name\" title=\"$title\" value=\"$content\" accesskey=\"$accesskey\" " .
                                                         "style=\"width:" . $width . "; height:" . $height . "; padding-top:" . $paddingTop . "; " .
                                                         "background:" . $background . "; color:" . $color . "; " .
                                                         "font-size:" . $fontSize . "; font-weight:" . $fontWeight . "; " .
                                                         "font-style:" . $fontStyle . "; font-family:" . $fontFamily . "; " .
                                                         "border: 1px solid #ccc; " .
                                                         " -webkit-appearance: none; " .
                                                         " -moz-appearance: none; " .
                                                         " appearance: none; " .
                                                         " cursor: pointer; " .
                                                         "\" " .
                                                         ($disabled != "disabled" ? "onMouseover=\"" . $frameworkOnMouseOver . "\" " .
                                                         "onMouseout=\"" . $frameworkOnMouseOut . "\" " .
                                                         "onClick=\"" . $action . "\" " : "") . 
                                                         $disabled . " >\n";
  if ($inDiv == "1") :                                                         
     $outHTML .= "</div>\n";
     if ($float != "" && $postspaces != "" && is_numeric($postspaces)) :
        $outHTML .= "<div style=\"float:left;\">";
        for ($i = 1; $i <= $postspaces; $i++) :
            $outHTML .= "&nbsp;";
        endfor;
        $outHTML .= "</div>";
     endif;
  endif;
  return $outHTML;
}

function defineButtonType08 ($content, $name = "", $action = "", $width = "", $float = "", $postspaces = "", $title = "", $accesskey = "", $submit = "", $disabled = "", $inDiv = "1") {
  return defineButton($content, $name, $action, $float, $postspaces, "3px", "5px", $width, "20px", "", "", "8pt", "bold", "normal", "Helvetica,Arial", $title, $accesskey, $submit, $disabled, $inDiv);
}

function defineButtonType10 ($content, $name = "", $action = "", $width = "", $float = "", $postspaces = "", $title = "", $accesskey = "", $submit = "", $disabled = "", $inDiv = "1") {
  return defineButton($content, $name, $action, $float, $postspaces, "5px", "5px", $width, "25px", "", "", "10pt", "bold", "normal", "Helvetica,Arial", $title, $accesskey, $submit, $disabled, $inDiv);
}

// Generates a link button (e.g. to open a tab)
// $content     : Content of the button
// $name        : Name and ID of the button usable for Javascript
// $action      : Javascript function for onClick (e.g. "finishPage(...);")
// $paddingTop  : Distance of the text to the top of the button element
// $paddingLeft : Distance of the text to the left of the button element
// $width       : With of the button
// $height      : Height of the button
// $fontXXX     : Font informations
function defineLinkButton ($content, $name = "", $action = "", $float = "", $postspaces = "", $paddingTop = "", $paddingLeft = "", $width = 0, $height = 0, $background = "", $color = "", $fontSize = "", $fontWeight = "", $fontStyle = "", $fontFamily = "", $title = "", $accesskey = "", $submit = false, $disabled = "", $clickLength = "20", $marginTop = "0px", $marginLeft = "0px") {
	global $constButtonBackground, $constButtonColor, $constButtonOnMouseOverColor, $usedFramework, $hideFocus;

	// Make HTML
  $outHTML = "";  
  if ($name == "") : $name = "button"; endif;
  if ($action == "") : $action = "document.forms[0].submit();"; endif;
  if ($paddingTop == "") : $paddingTop = "0px"; endif;
    if (is_numeric($paddingTop)) : $paddingTop .= "px"; endif;
  if ($paddingLeft == "") : $paddingLeft = "5px"; endif;
    if (is_numeric($paddingLeft)) : $paddingLeft .= "px"; endif;  
  $width = intval($width);
  if ($width == 0) : $width = 120; endif;
  // $width = $width - 4;  // Because of the border
    if (is_numeric($width)) : $width .= "px"; endif;
  $height = intval($height);
  if ($height == 0) : $height = 25; endif;
  $height = $height - 7;  // Because of the border
    if (is_numeric($height)) : $height .= "px"; endif;
  if ($background == "") : $background = $constButtonBackground; endif;
    if (substr($background, 0, 1) != "#") : $background = "#" . $background; endif;
  if ($color == "") : $color = $constButtonColor; endif;
    if (substr($color, 0, 1) != "#") : $color = "#" . $color; endif;
  if ($fontSize == "") : $fontSize = "12pt"; endif;
    if (is_numeric($fontSize)) : $fontSize .= "pt"; endif;
  if ($fontWeight == "") : $fontWeight = "bold"; endif;
  if ($fontStyle == "") : $fontStyle = "normal"; endif;
  if ($fontFamily == "") : $fontFamily = "Helvetica,Arial"; endif;
  if ($submit == true) : $type = "submit"; else : $type = "button"; endif;
  $content = padCenter($content, $clickLength, "&nbsp;");   // Fill up with spaces to enlarge the clickable link
  $outHTML .= "<div name=\"d_" . $name . "\" id=\"d_" . $name . "\" style=\"" .
                                                         ($float != "" ? "float:" . $float . "; " : "") .
                                                         "text-align:center; width:" . $width . "; height:" . $height . "; " . 
                                                         "padding-top: " . $paddingTop . ";" .
                                                         "margin-top: " . $marginTop . ";" .
                                                         "margin-left: " . $marginLeft . ";" .
                                                         "background:" . $background . "; " .
                                                         "\" >\n";     // OLD: "border-style:solid; border-width:2px;" . "border-color:#F5F5F5 #7C7B7B #7C7B7B #F5F5F5; " .
  $outHTML .= "<style type=\"text/css\">\n" .
              ".a_button_" . $name . ":link { text-decoration:none; font-size:" . $fontSize . "; font-weight:" . $fontWeight . "; font-style:" . $fontStyle . "; font-family:" . $fontFamily . "; color:" . $color . "; cursor:default; " . $hideFocus . "}\n" .
              ".a_button_" . $name . ":visited { text-decoration:none; font-size:" . $fontSize . "; font-weight:" . $fontWeight . "; font-style:" . $fontStyle . "; font-family:" . $fontFamily . "; color:" . $color . "; cursor:default; " . $hideFocus . "}\n" .
              ".a_button_" . $name . ":hover { text-decoration:none; font-size:" . $fontSize . "; font-weight:" . $fontWeight . "; font-style:" . $fontStyle . "; font-family:" . $fontFamily . "; color:" . $constButtonOnMouseOverColor . "; cursor:default; " . $hideFocus . "}\n" .
              ".a_button_" . $name . ":active { text-decoration:none; font-size:" . $fontSize . "; font-weight:" . $fontWeight . "; font-style:" . $fontStyle . "; font-family:" . $fontFamily . "; color:" . $color . "; cursor:default; " . $hideFocus . "}\n" .
              ".a_button_" . $name . ":focus { text-decoration:none; font-size:" . $fontSize . "; font-weight:" . $fontWeight . "; font-style:" . $fontStyle . "; font-family:" . $fontFamily . "; color:" . $color . "; cursor:default; " . $hideFocus . "}\n" .
              "</style>\n";
  $outHTML .= "<a class=\"a_button_" . $name . "\" name=\"" . $name . "\" id=\"" . $name . "\" title=\"" . $title . "\" accesskey=\"" . $accesskey . "\" " . 
              " href=\"" . $action . "\" target=\"_blank\">" . $content . "</a>\n";
  $outHTML .= "</div>\n";
  if ($float != "" && $postspaces != "" && is_numeric($postspaces)) :
     $outHTML .= "<div style=\"float:left;\">";
     for ($i = 1; $i <= $postspaces; $i++) :
         $outHTML .= "&nbsp;";
     endfor;
     $outHTML .= "</div>";
  endif;
  return $outHTML;
}

function defineLinkButtonType08 ($content, $name = "", $action = "", $width = "", $float = "", $postspaces = "", $title = "", $accesskey = "", $submit = "", $disabled = "", $clickLength = "20") {
  return defineLinkButton($content, $name, $action, $float, $postspaces, "2px", "5px", $width, "23px", "", "", "8pt", "bold", "normal", "Helvetica,Arial", $title, $accesskey, $submit, $disabled, $clickLength, "1px", "0px");
}

function defineLinkButtonType10 ($content, $name = "", $action = "", $width = "", $float = "", $postspaces = "", $title = "", $accesskey = "", $submit = "", $disabled = "", $clickLength = "30") {
  return defineLinkButton($content, $name, $action, $float, $postspaces, "5px", "5px", $width, "25px", "", "", "10pt", "bold", "normal", "Helvetica,Arial", $title, $accesskey, $submit, $disabled, $clickLength, "1px", "1px");
}

// Gets checkboxes with headquarters
function getHeadquartersCheckboxes ($f_hq_id, $width = "", $float = "", $textSubst = "", $docFormParName = "f_hq_id", $jsFuncNameExtension = "") {
	global $md_id, $hq_id, $emp_id, $empGlobalMasterRights;

  $tmpArray = getHeadquartersAccessStructure();
  $mdId = $tmpArray[0];
  $empHqAccess = $tmpArray[1];
  $numOfHq = $tmpArray[2];

  $phpHeadquartersOut = "";
  $tmpStyle = "";
  if ($textSubst == "") : $textSubst = getLngt("Niederlassungen:"); endif;
	if ($hq_id != "" && is_numeric($hq_id) && $numOfHq > 0) :
	   // Get mandator of the current headquarters logged in
     if ($width == "") : $width = "750"; endif;
     if (is_numeric($width)) : $width .= "px"; endif;
     if ($width != "") :
        $tmpStyle .= "width:" . $width . ";";
     endif;
     if ($float != "") :
        $tmpStyle .= "float:" . $float . ";";
     endif;
     if ($tmpStyle != "") :
        $tmpStyle .= " style=\"" . $tmpStyle . "\"";
     endif;
     $phpHeadquartersOut .= "<div " . $tmpStyle . ">";
     $phpHeadquartersOut .= "  <div>";
     $phpHeadquartersOut .= "    <div style=\"float:left;\">";
     $phpHeadquartersOut .=        $textSubst . "&nbsp;&nbsp;" . addCheckboxesFromTable($docFormParName,"headquarters AS hq, mandatorheadquarters AS mdhq","hq.hq_id","hq.hq_mnemonic","hq.hq_mnemonic","hq.hq_disabled = '0' AND mdhq.md_id = '" . $mdId . "' AND hq.hq_id = mdhq.hq_id AND hq.hq_id IN (" . $empHqAccess . ")",$f_hq_id, "&nbsp;&nbsp;&nbsp;","");
     $phpHeadquartersOut .= "    </div>";
     $phpHeadquartersOut .= defineButtonType08(getLngt("Alle"), "f_hq_check_all", "hqCheckAll". $jsFuncNameExtension . "(" . $numOfHq . ");", "70px", "left", "3");
     $phpHeadquartersOut .= defineButtonType08(getLngt("Keine"), "f_hq_uncheck_all", "hqUncheckAll". $jsFuncNameExtension . "(" . $numOfHq . ");", "70px", "left");
     $phpHeadquartersOut .= "  </div>";
     $phpHeadquartersOut .= "</div>";
  endif;
  return $phpHeadquartersOut;
}

// Gets options with headquarters
function getHeadquartersOptions ($f_hq_id, $selectedHqId) {
	global $md_id, $hq_id, $emp_id, $empGlobalMasterRights;
  $tmpArray = getHeadquartersAccessStructure();
  $mdId = $tmpArray[0];
  $empHqAccess = $tmpArray[1];
  $numOfHq = $tmpArray[2];

  $phpHeadquartersOut = "";
	if ($hq_id != "" && is_numeric($hq_id) && $numOfHq > 0) :
     $phpHeadquartersOut .= addOptionsFromTable("headquarters AS hq, mandatorheadquarters AS mdhq","hq.hq_id","hq.hq_mnemonic","hq.hq_mnemonic","mdhq.md_id = '" . $mdId . "' AND hq.hq_id = mdhq.hq_id AND hq.hq_id IN (" . $empHqAccess . ")",$selectedHqId);
  endif;
  return $phpHeadquartersOut;
}

// Toggles list colors
function getListColor($x, $y) {
	global $constListBgCol1, $constListBgCol2, $constListBgCol3, $constListBgCol4;
	$bgCol = "";
	// #BBBBFF, #CCCCFF, #DDDDDD, #EEEEEE
	// #AAAAFF, #AAAAFF, #CCCCFF, #CCCCFF
  if ($x % 2 == 0 && $y == 0) : $bgCol = $constListBgCol1; endif;
  if ($x % 2 == 0 && $y == 1) : $bgCol = $constListBgCol2; endif;
  if ($x % 2 == 1 && $y == 0) : $bgCol = $constListBgCol3; endif;
  if ($x % 2 == 1 && $y == 1) : $bgCol = $constListBgCol4; endif;
  return $bgCol;
}

// Toggles list colors
function getListColorGeneric($x, $y, $bgCol1 = "#AAAAFF", $bgCol2 = "#AAAAFF", $bgCol3 = "#CCCCFF", $bgCol4 = "#CCCCFF") {
	$bgCol = "";
  if ($x % 2 == 0 && $y % 2 == 0) : $bgCol = $bgCol1; endif;
  if ($x % 2 == 0 && $y % 2 == 1) : $bgCol = $bgCol2; endif;
  if ($x % 2 == 1 && $y % 2 == 0) : $bgCol = $bgCol3; endif;
  if ($x % 2 == 1 && $y % 2 == 1) : $bgCol = $bgCol4; endif;
  return $bgCol;
}

// Inverts all <tr>....</tr> of a <table>. The last becomes the first, the penultimate becomes the second and so on
function reverseOuterTableRows(string $html): string {
    if (trim($html) === '') {
        return '';
    }

    // SCHRITT 1: Erzwinge die Konvertierung des Strings von Latin 1 nach UTF-8.
    $utf8Html = mb_convert_encoding($html, 'UTF-8', 'ISO-8859-1');

    $dom = new DOMDocument();
    
    libxml_use_internal_errors(true);
    
    // Wir fügen den Meta-Tag hinzu, um dem Parser zu helfen, den jetzt sauberen UTF-8-String zu verstehen.
    $dom->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . '<div>' . $utf8Html . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    libxml_clear_errors();

    $xpath = new DOMXPath($dom);
    $wrapper = $dom->getElementsByTagName('div')->item(0);

    // Die Logik zur Umkehrung der Zeilen bleibt identisch.
    $rows = $xpath->query('./tr | ./*/tr', $wrapper);
    if ($rows->length === 0) {
        return $html; // Keine Zeilen gefunden, Original zurückgeben
    }
    $reversedRows = [];
    foreach ($rows as $row) { $reversedRows[] = $row; }
    $reversedRows = array_reverse($reversedRows);
    
    $parent = $rows->item(0)->parentNode;
    while ($parent->hasChildNodes()) { $parent->removeChild($parent->firstChild); }
    foreach ($reversedRows as $row) { $parent->appendChild($row); }

    // Extrahiere das Ergebnis. Es ist immer noch in UTF-8 kodiert.
    $outputUtf8 = '';
    foreach ($wrapper->childNodes as $child) {
        if ($child->nodeName === 'meta') { continue; }
        $outputUtf8 .= $dom->saveHTML($child);
    }

    // SCHRITT 2: Konvertiere das Ergebnis zurück von UTF-8 nach Latin 1.
    $outputLatin1 = mb_convert_encoding($outputUtf8, 'ISO-8859-1', 'UTF-8');

    return $outputLatin1;
}
?>
