<?php

if (!function_exists('renderImageComparer')) {
  function renderImageComparer($imageBefore = false, $imageAfter = false, $handleColor = false, $handleInitialPosition = false) {
    $b = 'flex-element-type-image-comparison';

    // Check if images are ok
    if (!$imageBefore && !$imageBefore['url'] || !$imageAfter && !$imageAfter['url']) {
      return '';
    }

    $imagePositionData = isset($imageBefore['backgroundPosition']) ?
      $imageBefore['backgroundPosition']
      : array('x' => 0, 'y' => 0);
    $imagePosition = $imagePositionData['x'] . '% ' . $imagePositionData['y'] . '%';

    $mobileImagePositionData = isset($imageBefore['mobileBackgroundPosition']) ?
      $imageBefore['mobileBackgroundPosition']
      : $imagePositionData;
    $mobileImagePosition = $mobileImagePositionData['x'] . '% ' . $mobileImagePositionData['y'] . '%';

    $finalHandleInitialPosition = $handleInitialPosition;

    if ($handleInitialPosition <= 16) $finalHandleInitialPosition = 16;
    if ($handleInitialPosition >= 84) $finalHandleInitialPosition = 84;

    return '
      <div
        class="' . $b . '"
        data-flex-chunk="element-image-comparison"
        style="
          --handleColor: ' . getStyleKitColor($handleColor) . ';
          --handlePosition: ' . $finalHandleInitialPosition . '%;
          --imagePosition: ' . $imagePosition . ';
          --mobileImagePosition: ' . $mobileImagePosition . ';
        "
      >
        <div
          class="' . $b . '__image ' . $b . '__image--before"
          style="
            background-image: url(' . $imageBefore['url'] . ');
          "
        ></div>
        <div
          class="' . $b . '__image ' . $b . '__image--after"
          style="
            background-image: url(' . $imageAfter['url'] . ');
          "
        ></div>


        <div class="' . $b . '__handle-line ' . $b . '__handle-line--top"></div>
        <div class="' . $b . '__handle">
          <div class="' . $b . '__handle-arrow ' . $b . '__handle-arrow--left">
            <i class="flo-flex-icon-ice-left"></i>
          </div>
          <div class="' . $b . '__handle-circle"></div>
          <div class="' . $b . '__handle-arrow ' . $b . '__handle-arrow--right">
            <i class="flo-flex-icon-ice-right"></i>
          </div>
        </div>
        <div class="' . $b . '__handle-line ' . $b . '__handle-line--bottom"></div>
      </div>
    ';
  }
}

function renderImageComparisonElement($block_class, $element, $custom_classes, $elStyles, $colors, $viewport) {
  $data = $element['data'];
  $user_data = $data['user_data'];

  extract($user_data);

  $elMarkup = '
    <div class="' . $block_class . '__element ' . $block_class . '__element--' . $element["id"] . ' ' . $block_class . '__element--image-comparision ' . $custom_classes . '" style="' . $elStyles . '">
      ' . renderImageComparer($imageBefore, $imageAfter, $handleColor, $handleInitialPosition) . '
    </div>
  ';

  return $elMarkup;
}
