<?php
include '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'];

  // image will go through aq_resize if:
  // 1) if url is not a gif
  // 2) if flex is not on flothemes.com
  // 3) if "Use Original Resolution" option is disabled

  $filename_from_url = parse_url($img_url);
  $ext = pathinfo($filename_from_url['path'], PATHINFO_EXTENSION);
  $originalRes = isset($user_data['originalRes']) && $user_data['originalRes'];
  $parallax = isset($user_data['enableParallax']) && $user_data['enableParallax'];

  if($ext !== 'gif' && function_exists('flo_aq') && !$parallax && !$originalRes) {
    $img_width = floatval($data['elementWidth']) * 32;
    $img_height = floatval($data['elementHeight']) * 32;

    $aq_sizes = flex_get_aq_sizes($img_width, $img_height);
    $img_url = flo_aq(
      $img_url,
      $aq_sizes['width'],
      $aq_sizes['height'],
      $crop = false,
      $force_resize = true
    );

    // tablet size and srcset
    if($viewport === "desktop") {
      $tablet_img_width = floatval($data['elementWidth']) * 25.6;
      $tablet_img_height = floatval($data['elementHeight']) * 25.6;

      $tablet_aq_sizes = flex_get_aq_sizes($tablet_img_width, $tablet_img_height);
      $tablet_img_url = flo_aq(
        $img_url,
        $tablet_aq_sizes['width'],
        $tablet_aq_sizes['height'],
        $crop = false,
        $force_resize = true
      );

      $imgObj['srcset'] = "$img_url, $tablet_img_url 1024w";
    }

  }

  $imgObj['src'] = $img_url;
  return $imgObj;

}

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"];
    }
  }
  return $result;
}

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"]);
    $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 ($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"])) {
    $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, $flatMap = null, $colors = null, $viewport = "desktop", $parentSizePos = null, $blockID) {
  $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"])) {
    $custom_classes .= ' '.$b.'__element--has-animation ';
    $custom_classes .= ' '.$b.'__element--action-type-'.$user_data["animations"]["presetConfig"]["actionType"].' ';

    // 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';
  }

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

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

  return $elMarkup;
}
