<?php

function fwembed_parse_html($url = null) {
  if ($url === null) {
    throw new ValueError("Missing URL");
  }
  $html = null;
  $dom = new DOMDocument();
  @$dom->loadHTML(file_get_contents($url));
  $dom->documentURI = $url;
  $divs = $dom->getElementsByTagName('div');
  foreach ($divs as $div) {
    if ($div->hasAttribute('data-testid') && $div->getAttribute('data-testid') === 'product') {
      $xpath = new DOMXPath($dom);

      $tileLink = $xpath->query('.//a[contains(@class, "tile")]', $div);
      $tileItem = $xpath->query('.//img[contains(@class, "tile__item--1")
                                and not(contains(@class, "badge"))
                                and not(contains(@class, "tile_options"))
                                and not(contains(@class, "tile__item--2"))]', $div);
      $tileDesc = $xpath->query('.//*[contains(@class, "tile__description")
                                and not(contains(@class, "badge"))
                                and not(contains(@class, "tile_options"))]', $div);
      $tilePrices = $xpath->query('.//*[contains(@class, "tile__prices")
                                  and not(contains(@class, "badge"))
                                  and not(contains(@class, "tile_options"))
                                  and not(contains(@class, "tile__price tile__price--original"))]', $div);
      $productHTML = '';
      $linkHref = '';
      if ($tileLink->length > 0) {
        $linkHref = $tileLink->item(0)->getAttribute('href');
      }
      if ($tileItem->length > 0) {
        $productHTML .= $dom->saveHTML($tileItem->item(0));
      }
      if ($tileDesc->length > 0) {
        $productHTML .= $dom->saveHTML($tileDesc->item(0));
      }
      //if ($tilePrices->length > 0) {
      //  $productHTML .= $dom->saveHTML($tilePrices->item(0));
     // }

      $html = $html . '<div class="product-tile"><a class="product-link" target="_blank" href="' . $url . $linkHref . '">' . $productHTML . '</a></div>';
    }
  }
  return $html;
}

function fwembed_shortcode( $atts ) {
  $options = get_option( 'fourthwall_settings_name' );
  $value = isset( $options['fourth_url'] ) ? $options['fourth_url'] : 'https://fourthwall.com';
  $store_html = fwembed_parse_html($value);
  $store_render = '<div class="fw-store-parent">' . PHP_EOL . $store_html . PHP_EOL . '</div>';
  return $store_render;
}
add_shortcode( 'fourthwall', 'fwembed_shortcode' );