<?php
// Helpers om designs.json en te-koop.json te lezen.

require_once __DIR__ . '/config.php';

function _read_json(string $path): array {
  if (!is_file($path)) return [];
  $raw = file_get_contents($path);
  if ($raw === false) return [];
  // Strip UTF-8 BOM als die er per ongeluk in staat
  if (substr($raw, 0, 3) === "\xEF\xBB\xBF") $raw = substr($raw, 3);
  $data = json_decode($raw, true);
  return is_array($data) ? $data : [];
}

function load_designs(): array {
  static $cache = null;
  if ($cache !== null) return $cache;
  $path = dirname(__DIR__) . '/data/designs.json';
  $data = _read_json($path);
  if (!$data) return $cache = [];

  // Verrijk elk design met afgeleide velden
  foreach ($data as &$d) {
    $d['series']   = derive_series($d['title'] ?? '');
    $d['slug']     = slugify($d['series']);
    $d['model']    = derive_model($d['title'] ?? '', $d['series']);
    $d['length_m'] = parse_length($d['fields']['Lengte'] ?? null);
    $d['category'] = $d['fields']['Categorie'] ?? '';
    $d['type']     = $d['fields']['Type'] ?? '';
    $d['name']     = trim(preg_replace('/\s+/', ' ', $d['title'] ?? ''));
  }
  unset($d);

  // Sorteer op serie + lengte
  usort($data, function($a, $b){
    $s = strcasecmp($a['series'] ?? '', $b['series'] ?? '');
    if ($s !== 0) return $s;
    return ($a['length_m'] ?? 0) <=> ($b['length_m'] ?? 0);
  });

  return $cache = $data;
}

// Groepeer designs per serie
function group_by_series(array $designs): array {
  $groups = [];
  foreach ($designs as $d) {
    $key = $d['series'] ?: 'Overig';
    if (!isset($groups[$key])) {
      $groups[$key] = [
        'name'     => $key,
        'slug'     => $d['slug'],
        'models'   => [],
        'cover'    => null,
        'length_min' => null,
        'length_max' => null,
        'categories' => [],
      ];
    }
    $g = &$groups[$key];
    $g['models'][] = $d;
    if (!$g['cover'] && !empty($d['images'])) {
      $g['cover'] = ['id' => $d['id'], 'file' => $d['images'][0]];
    }
    $L = $d['length_m'] ?? null;
    if ($L !== null) {
      if ($g['length_min'] === null || $L < $g['length_min']) $g['length_min'] = $L;
      if ($g['length_max'] === null || $L > $g['length_max']) $g['length_max'] = $L;
    }
    if (!empty($d['category']) && !in_array($d['category'], $g['categories'], true)) {
      $g['categories'][] = $d['category'];
    }
    unset($g);
  }

  // Sorteer series op aantal modellen (grootste eerst)
  uasort($groups, function($a, $b){
    return count($b['models']) <=> count($a['models']);
  });

  return $groups;
}

function find_design_by_id(int $id): ?array {
  foreach (load_designs() as $d) {
    if (($d['id'] ?? null) === $id) return $d;
  }
  return null;
}

function find_serie_by_slug(string $slug): ?array {
  $groups = group_by_series(load_designs());
  foreach ($groups as $g) {
    if ($g['slug'] === $slug) return $g;
  }
  return null;
}

// ---- helpers ----

function derive_series(string $title): string {
  $t = trim($title);
  if (preg_match('/^([A-Za-zéëïü\s]+?)[-\s]?\d/', $t, $m)) {
    return trim($m[1]);
  }
  if (preg_match('/^([A-Za-zéëïü]+)/', $t, $m)) {
    return $m[1];
  }
  return 'Overig';
}

function derive_model(string $title, string $series): string {
  $rest = trim(preg_replace('/^' . preg_quote($series, '/') . '\s*-?\s*/i', '', $title));
  return $rest !== '' ? $rest : $title;
}

function parse_length($val): ?float {
  if ($val === null) return null;
  if (is_numeric($val)) return (float)$val;
  if (preg_match('/([\d]+[.,]?\d*)/', (string)$val, $m)) {
    return (float)str_replace(',', '.', $m[1]);
  }
  return null;
}

// Pad voor design-afbeelding (relatief vanaf web-root)
function design_img(array $design, int $idx = 0): ?string {
  if (empty($design['images'][$idx])) return null;
  return 'images/designs/' . $design['id'] . '/' . rawurlencode($design['images'][$idx]);
}

// ---- te-koop data ----

function load_forsale(): array {
  $path = dirname(__DIR__) . '/data/te-koop.json';
  $data = _read_json($path);
  // sort by datum_added desc
  usort($data, function($a, $b){
    return strcmp($b['added'] ?? '', $a['added'] ?? '');
  });
  return $data;
}

function save_forsale(array $items): bool {
  $path = dirname(__DIR__) . '/data/te-koop.json';
  return file_put_contents($path, json_encode($items, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) !== false;
}
