<?php
require_once dirname(__FILE__) . '/elementTypes/elementTypes.php';

function flexGetImageUrl($element, $viewport = "desktop") {
  $imgObj = [];

  $data = $element['data'];
  $user_data = $data['user_data'];

  if (!isset($user_data['backgroundImage'])) {
    return [
      "src" => "",
      "srcset" => "",
    ];
  }

  $img_url = $user_data['backgroundImage'];
  $originalRes = isset($user_data['originalRes']) && $user_data['originalRes'];

  $imgObj['src'] = $img_url;
  if (!$originalRes && $user_data && isset($user_data['imgId']) && !isset($_GET['stopsrcsets'])) {
    $imgObj['srcset'] = wp_get_attachment_image_srcset($user_data['imgId'], 'full');
  }


  return $imgObj;
}

// we need to check in case the FLex is activated on a site with active FloGuten theme which uses the same funnction for fallback
if (!function_exists('getStylekitColor')) {
  function getStylekitColor($color) {
    $result = $color;
    global $active_stylekit_colors;

    if (strpos($color, '/') !== false) {
      if (isset($active_stylekit_colors[$color])) {
        // $result = $active_stylekit_colors[$color]["value"];
        $result = 'var(--' . str_replace('/', '--', $color) . ')';
      }
    } else if (strpos($color, 'flo') !== false) {
      $result = strpos($color, 'var') !== false ? $color : 'var(--' . $color . ')';
    }

    return $result;
  }
}

if (!function_exists('flex_em_calc')) {
  function flex_em_calc($val, $font_size, $viewport) {
    $numVal = floatval($val);
    $viewportScale = $viewport === 'desktop' ? 12.8 : 3.75;
    $emVal = $numVal / ($viewportScale * $font_size);
    return $emVal;
  }
}

function getStylekitFontStyle($font_style_id) {
  $result = array();
  global $active_stylekit_fonts;

  if (isset($active_stylekit_fonts[$font_style_id])) {
    $result = $active_stylekit_fonts[$font_style_id];
  }

  return $result;
}

function fontMixin($user_data, $prefix, $important = false) {
  $result = '';
  $importantString = $important ? '!important' : '';

  if ($user_data[$prefix . "_useFontStyle"]) {
    $fontStyle = getStylekitFontStyle($user_data[$prefix . "_fontStyle"]);

    $fontStyle = array_merge(array(
      'lineHeight' => 1.3,
      'fontSize' => 13,
      'letterSpacing' => 0,
      'fontFamily' => 'inherit',
      'fontWeight' => 'regular',
      'fontStyle' => 'normal',
      'textDecoration' => 'initial',
      'textTransform' => 'initial'
    ), $fontStyle);

    $result = '
      line-height: ' . $fontStyle["lineHeight"] . '' . $importantString . ';
      font-size: ' . ($fontStyle["fontSize"] / 16) . 'rem' . $importantString . ';
      letter-spacing: ' . $fontStyle["letterSpacing"] . 'em' . $importantString . ';
      font-family: ' . $fontStyle["fontFamily"] . '' . $importantString . ';

      font-weight: ' . $fontStyle["fontWeight"] . '' . $importantString . ';
      font-style: ' . $fontStyle["fontStyle"] . '' . $importantString . ';
      text-decoration: ' . $fontStyle["textDecoration"] . '' . $importantString . ';
      text-transform: ' . $fontStyle["textTransform"] . '' . $importantString . ';
    ';
  } else {
    $result = '
      font-family: ' . $user_data[$prefix . "_fontFamily"] . '' . $importantString . ';
      font-size: ' . $user_data[$prefix . "_fontSize"] . 'rem' . $importantString . ';
      letter-spacing: ' . $user_data[$prefix . "_letterSpacing"] . 'em' . $importantString . ';
      line-height: ' . $user_data[$prefix . "_lineHeight"] . '' . $importantString . ';
    ';
  }

  return $result;
}

function getFontData($data, $prefix) {
  $result = array('dataFont' => '', 'style' => '');

  if (!isset($data[$prefix . "_useFontStyle"])) {
    return $result;
  }

  if ($data[$prefix . "_useFontStyle"]) {
    $result['dataFont'] = $data[$prefix . "_fontStyle"];
  } else {
    $result['style'] = '
      font-family: ' . $data[$prefix . "_fontFamily"] . ';
      font-size: ' . $data[$prefix . "_fontSize"] . 'rem;
      letter-spacing: ' . $data[$prefix . "_letterSpacing"] . 'em;
      line-height: ' . $data[$prefix . "_lineHeight"] . ';
    ';
  }

  return $result;
}

function flexRenderElAnimations($element, $blockID) {
  $id = $element['id'];
  $data = $element['data'];
  $user_data = $data['user_data'];
  $elAnimation = "";

  if (isset($user_data["animations"]["preset"]) && $user_data["animations"]["preset"] !== false) {
    $animations = $user_data["animations"];
    $elAnimation = "
      <script>
        if (!window.flex) window.flex = {
          animations: {},
          appearedElements: {},
        };
        if (!window.flex.animations['" . $blockID . "']) {
          window.flex.animations['" . $blockID . "'] = {};
        }
        window.flex.animations['" . $blockID . "']['" . $element["id"] . "'] = " . json_encode($user_data["animations"]) . ";
      </script>
    ";

    if ($animations['initial']['enabled'] === true) {
      $vars = $animations['initial']['steps']['step0'];
      $opacity =  $vars["opacity"] / 100;
      $scale = $vars["scale"] / 100;
      $initialVars = "
        <style>
          .flex-block__element--block-" . $blockID . ".flex-block__element--" . $id . " {
            --animation-top: " . ($vars["top"] / 16) . "rem;
            --animation-left: " . ($vars["left"] / 16) . "rem;
            --animation-rotate: " . $vars["rotate"] . "deg;
            --animation-opacity: " . $opacity . ";
            --animation-scale: " . $scale . ";
            --animation-blur: " . $vars["blur"] . "px;
      ";

      if (isset($vars["color"])) {
        $color = getStylekitColor($vars["color"]);
        $initialVars .= "--animation-color: " . $color . ";";
      }

      $initialVars .= "
          }
        </style>
      ";

      if (isset($vars["color"])) {
        $initialVars .= "<div class='flex-block-element-has-color-indicator'></div>";
      }

      $elAnimation .= $initialVars;
    }
  }

  return $elAnimation;
}

function flexRenderEl($element, $blockID, $flatMap = null, $colors = null, $viewport = "desktop", $parentSizePos = null) {
  $b = "flex-block";
  $elMarkup = "";
  $data = $element['data'];
  $user_data = $data['user_data'];

  $custom_classes = isset($user_data['customClasses']) ? $user_data['customClasses'] : '';
  if (strlen($custom_classes)) {
    $custom_classes = str_replace(' ', '', $custom_classes);
    $custom_classes = str_replace(',', ' ', $custom_classes);
  }

  // Add Block ID to Class
  $custom_classes .= ' ' . $b . '__element--block-' . $blockID . ' ';

  // Add "has animation" modifier
  if (isset($user_data["animations"]["preset"]) && $user_data["animations"]["preset"] !== false) {
    $custom_classes .= ' ' . $b . '__element--has-animation ';
    $custom_classes .= ' ' . $b . '__element--action-type-' . $user_data["animations"]["presetConfig"]["actionType"] . ' ';
    $custom_classes .= ' ' . $b . '__element--animation-type-' . $user_data["animations"]["preset"] . ' ';

    // Add "has color Animation" modifier
    $animations = $user_data["animations"];
    $vars = $animations['initial']['steps']['step0'];
    if (isset($vars["color"])) {
      $custom_classes .= ' ' . $b . '__element--has-color-animation ';
    }
  }

  // Add Vertical Alignment Classes
  if (isset($user_data['verticalAlignment'])) {
    $custom_classes .= ' ' . $b . '__element--vertical-alignment-' . $user_data['verticalAlignment'];
  }

  // Add Em Strong Fix for Text and Button
  if (isset($user_data['editorTagsFix']) && $user_data['editorTagsFix'] === true) {
    $custom_classes .= ' ' . $b . '__element--editorTagsFix';
  }

  if ($flatMap) {
    $elIndexFromMap = $flatMap[$element['id']];
  } else {
    $elIndexFromMap = null;
  }

  $elStyles = flex_get_element_styles($element, $elIndexFromMap, $colors, $viewport, $parentSizePos);

  $elMarkup = elementTypesRenderElement($data['type'], $b, $element, $custom_classes, $elStyles, $colors, $viewport, array("block_id" => $blockID));

  $elMarkup = flexRenderElAnimations($element, $blockID) . $elMarkup;

  return $elMarkup;
}

function flexRenderElStyles($element, $blockID, $elStyles, $elStylesMobile) {
  $id = $element['id'];

  $style = "
        <style>
        @media only screen and (min-width: 768px) {

          .flex-block__element--block-" . $blockID . ".flex-block__element--" . $id . " {
           " . (!empty($elStyles) ? $elStyles : 'display: none;') . "
      ";

  $style .= "
          }
        }
        @media only screen and (max-width: 767px) {
          .flex-block__element--block-" . $blockID . ".flex-block__element--" . $id . " {
           " . (!empty($elStylesMobile) ? $elStylesMobile : 'display: none;') . "
          }
        }
        </style>
      ";
  return $style;
}

// function flexRenderHTMLEl($element, $blockID, $colors = null, $main_data) {

//   $viewport = 'desktop';
//   $b = "flex-block";
//   $elMarkup = "";
//   $data = $element['data'];
//   $user_data = $data['user_data'];
//   $z_indexes_per_device = isset($main_data["zIndexMaps"]) ? $main_data["zIndexMaps"] : null;

//   $custom_classes = isset($user_data['customClasses']) ? $user_data['customClasses'] : '';
//   if (strlen($custom_classes)) {
//     $custom_classes = str_replace(' ', '', $custom_classes);
//     $custom_classes = str_replace(',', ' ', $custom_classes);
//   }

//   // Add Block ID to Class
//   $custom_classes .= ' ' . $b . '__element--block-' . $blockID . ' ';

//   // Add "has animation" modifier
//   if (isset($user_data["animations"]["preset"]) && $user_data["animations"]["preset"] !== false) {
//     $custom_classes .= ' ' . $b . '__element--has-animation ';
//     $custom_classes .= ' ' . $b . '__element--action-type-' . $user_data["animations"]["presetConfig"]["actionType"] . ' ';
//     $custom_classes .= ' ' . $b . '__element--animation-type-' . $user_data["animations"]["preset"] . ' ';



//     // Add "has color Animation" modifier
//     $animations = $user_data["animations"];
//     $vars = $animations['initial']['steps']['step0'];
//     if (isset($vars["color"])) {
//       $custom_classes .= ' ' . $b . '__element--has-color-animation ';
//     }
//   }

//   // Add Em Strong Fix for Text and Button
//   if (isset($user_data['editorTagsFix']) && $user_data['editorTagsFix'] === true) {
//     $custom_classes .= ' ' . $b . '__element--editorTagsFix';
//   }

//   $elStyles = '';

//   $elMarkup = elementTypesRenderElement($data['type'], $b, $element, $custom_classes, $elStyles, $colors, $viewport, array("block_id" => $blockID));

//   $z_index_desktop = get_deep_value($z_indexes_per_device, ['desktop', $element['id']], 1);
//   $z_index_mobile = get_deep_value($z_indexes_per_device, ['mobile', $element['id']], $z_index_desktop);

//   $elStyles = isset($main_data['elements'][$element['id']]) ? flex_get_element_styles($element, $z_index_desktop, $colors, 'desktop', null) : '';

//   if (isset($main_data['mobile_elements'][$element['id']]) && !$main_data['mobile_elements'][$element['id']]['data']['user_data']) {
//     $main_data['mobile_elements'][$element['id']]['data']['user_data'] = $main_data['elements'][$element['id']]['data']['user_data'];
//   }

//   $elStylesMobile = isset($main_data['mobile_elements'][$element['id']]) ? flex_get_element_styles($main_data['mobile_elements'][$element['id']], $z_index_mobile, $colors, 'mobile', null) : '';

//   $elMarkup = flexRenderElAnimations($element, $blockID) . flexRenderElStyles($element, $blockID, $elStyles, $elStylesMobile) . $elMarkup;

//   return $elMarkup;
// }
