<?php
require_once(__DIR__.'/productFilter.php');

if (is_file(__DIR__.'/productMain.php')) {
  require_once(__DIR__.'/productMain.php');
}

if (is_file(__DIR__.'/productSearch.php')) {
  require_once(__DIR__.'/productSearch.php');
}

function product_shop_text_e(?string $value): string {
  return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function product_shop_text_has_content(?array $data): bool {
  if (!$data) return false;

  return trim((string)($data['content'] ?? '')) !== '' || trim((string)($data['teaser'] ?? '')) !== '' || trim((string)($data['addition'] ?? '')) !== '';
}

function product_shop_text_get_current_level_guid(?string $content_guidv4 = null, array $content_data = []): ?string {
  if ($content_guidv4 && preg_match('/^[a-f0-9-]{36}$/i', $content_guidv4)) {
    return $content_guidv4;
  }

  if (!empty($content_data)) {
    $last = end($content_data);

    if (is_string($last) && preg_match('/^[a-f0-9-]{36}$/i', $last)) {
      return $last;
    }
  }

  return null;
}

function product_shop_text_resolve_level(PDO $conn, ?string $content_guidv4, array $content_data, string $language): ?array {
  $guidv4 = product_shop_text_get_current_level_guid($content_guidv4, $content_data);

  if (!$guidv4) return null;

  $sql = "SELECT * FROM content_levels WHERE guidv4 = :guidv4 AND language = :language AND c_active = '1' LIMIT 1";

  $stmt = $conn->prepare($sql);
  $stmt->bindValue(':guidv4', $guidv4, PDO::PARAM_STR);
  $stmt->bindValue(':language', $language, PDO::PARAM_STR);
  $stmt->execute();

  $data = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!product_shop_text_has_content($data)) return null;

  return [
    'kind'    	=> 'level',
    'title'   	=> $data['title'] ?? null,
    'teaser'  	=> $data['teaser'] ?? null,
    'content' 	=> $data['content'] ?? null,
    'addition' 	=> $data['addition'] ?? null,
    'data'    	=> $data,
  ];
}

function product_shop_text_create_filter(PDO $conn, array $input, string $language, ?string $stock_filter_mode = null): ProductFilter {
  $filter = new ProductFilter();
  $filter->setConnection($conn);
  $filter->setInput($input);

  if ($stock_filter_mode) {
    $filter->setStockFilterMode($stock_filter_mode);
  }

  $filter->init();

  $q = trim((string)($input['q'] ?? ''));
  if ($q !== '' && class_exists('ProductSearch')) {
    $filter->setSearchProvider(new ProductSearch($language));
    $filter->setSearchQuery($q);
  }

  return $filter;
}

function product_shop_text_resolve_single_filter(PDO $conn, array $input, string $language, ?string $stock_filter_mode = null): ?array {
  $filter = product_shop_text_create_filter($conn, $input, $language, $stock_filter_mode);

  $groups = $filter->getGroups();
  $items  = $filter->getItems();
  $active = $filter->getActiveFilters();

  $matches = [];

  foreach ($active AS $group_guid => $item_guids) {
    if (empty($groups[$group_guid])) continue;

    $group = $groups[$group_guid];

    foreach ((array)$item_guids AS $item_guid) {
      foreach (($items[$group_guid] ?? []) AS $item) {
        if (($item['guidv4'] ?? null) === $item_guid) {
          $matches[] = [
            'kind'       => 'filter',
            'type'       => $group['type'] ?? null,
            'group'      => $group,
            'item'       => $item,
            'guidv4'     => $item['guidv4'] ?? null,
            'input_key'  => ($group['type'] ?? '').'_'.($group['url'] ?? ''),
            'input_slug' => $item['url'] ?? null,
          ];

          break;
        }
      }
    }
  }

  if (count($matches) !== 1) return null;

  $match = $matches[0];

  if (!in_array($match['type'], ['tags', 'properties'], true)) {
    return null;
  }

  $guidv4 = (string)($match['guidv4'] ?? '');
  if ($guidv4 === '') return null;

  $table = 'products_'.$match['type'];

  $sql = "SELECT title, teaser, content, addition FROM ".$table." WHERE guidv4 = :guidv4 AND language = :language AND c_active = '1' LIMIT 1";

  $stmt = $conn->prepare($sql);
  $stmt->bindValue(':guidv4', $guidv4, PDO::PARAM_STR);
  $stmt->bindValue(':language', $language, PDO::PARAM_STR);
  $stmt->execute();

  $data = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!product_shop_text_has_content($data)) {
    return null;
  }

  return array_merge($match, [
    'title'   	=> $data['title'] ?? null,
    'teaser'  	=> $data['teaser'] ?? null,
    'content' 	=> $data['content'] ?? null,
    'addition' 	=> $data['addition'] ?? null,
    'data'    	=> $data,
  ]);
}

function product_shop_text_resolve(PDO $conn, array $input, ?string $content_guidv4, array $content_data, string $language, ?string $stock_filter_mode = null): ?array {
  $filter_text = product_shop_text_resolve_single_filter($conn, $input, $language, $stock_filter_mode);

  if ($filter_text) {
    return $filter_text;
  }

  return product_shop_text_resolve_level($conn, $content_guidv4, $content_data, $language);
}

function product_shop_text_resolve_product(PDO $conn, int $id, string $language): ?array {
  if ($id <= 0) return null;

  if (class_exists('ProductMain')) {
    $main = new ProductMain($conn, $language);

    $parent_id = $main->getParentId($id);
    $is_variant = $main->isVariant($id);

    $data = $is_variant ? $main->getMergedContent($id, $parent_id) : $main->getContent($id, $language, true);

    if (!$data || trim((string)($data['title'] ?? '')) === '') {
      return null;
    }

    return [
      'kind'      => 'product',
      'id'        => $id,
      'parent_id' => $parent_id,
      'variant'   => $is_variant,
      'title'     => $data['title'],
      'url'       => $data['url'] ?? null,
      'data'      => $data,
    ];
  }

  $sql = "SELECT title, url FROM products_content WHERE id_module = :id_module AND language = :language LIMIT 1";
  $result = $conn->prepare($sql);
  $result->bindValue(':id_module', $id, PDO::PARAM_INT);
  $result->bindValue(':language', $language, PDO::PARAM_STR);
  $result->execute();

  $data = $result->fetch(PDO::FETCH_ASSOC);

  if (!$data || trim((string)($data['title'] ?? '')) === '') {
    return null;
  }

  return [
    'kind'  => 'product',
    'id'    => $id,
    'title' => $data['title'],
    'url'   => $data['url'] ?? null,
    'data'  => $data,
  ];
}