<?php 

  function flexGetGroupSizePos($grpId, $data, $viewport = "desktop") {
    $allGroupsSizes = $data["groupsSizes"][$viewport];
    $sizePos = $allGroupsSizes[$grpId];
    $flatMap = $data["zIndexMaps"][$viewport];
    
    return [
      "top" => $sizePos["min_y"],
      "left" => $sizePos["min_x"],
      "width" => $sizePos["w"],
      "height" => $sizePos["h"],
      "z-index" => $flatMap[$grpId]
    ];
  }
  
  function flexRenderChildren($data, $children, $viewport, $parentSizePos = null) {
    $childrenMarkup = "";
    
    // get flat map if available (for z-indexes)
    $flatMap = isset($data["zIndexMaps"]) ? $data["zIndexMaps"][$viewport] : null;
    
    // get color names and send to renderer
    $colors = null;
    if(
      isset($data["globalOptions"]["themeColors"]) && 
      sizeof($data["globalOptions"]["themeColors"])
    ) {
      $colors = $data["globalOptions"]["themeColors"];
    }
    
    // get elements obj
    if($viewport === "desktop") {
      $elements = $data["elements"];
    } else {
      $elements = $data["mobile_elements"];
    }
    
    foreach ($children as $node) {
      if($node["type"] === "gr") {
        $groupSizePos = flexGetGroupSizePos($node["id"], $data, $viewport);
        
        $styleString = "";
        foreach ($groupSizePos as $sizePosKey => $sizePosVal) {
          if($parentSizePos && ($sizePosKey === "top" || $sizePosKey === "left")) {
            $sizePosVal = $sizePosVal - $parentSizePos[$sizePosKey];
          }
          if($sizePosKey !== "z-index") {
            $unit = "em";
          } else {
            $unit = "";
          }
          $styleString .= $sizePosKey . ":" . $sizePosVal . $unit . ";";
        }
        
        $childrenMarkup .= "<div style='".$styleString."' class='flex-group flex-group--".$node['id']."'>";
        $childrenMarkup .= flexRenderChildren($data, $node["children"], $viewport, $groupSizePos);
        $childrenMarkup .= "</div>";
      } else {
        $element = $elements[$node["id"]];
        $childrenMarkup .= flexRenderEl($element, $flatMap, $colors, $viewport, $parentSizePos);
      }
    }
    return $childrenMarkup;
  }

  function flexRenderFromMap($data, $viewport = "desktop") {
    
    $maps = $data["maps"];
    $map = $maps[$viewport];
    $first_level_children = $map["children"];
    
    $markup = flexRenderChildren($data, $first_level_children, $viewport);
    
    return $markup;
  }
?>