<?php
declare(strict_types=1);
require_once __DIR__ . '/bootstrap.php';
admin_require_login();

$id = $_GET['id'] ?? '';
$pageSlug = $_GET['page'] ?? 'home';
$module = $id ? cms_module($id) : [];
if (!$module) {
    redirect('/admin/builder.php?page=' . urlencode($pageSlug));
}
$notice = '';

function decode_rows(string $raw): array {
    $lines = preg_split('/\r\n|\r|\n/', trim($raw)) ?: [];
    $items = [];
    foreach ($lines as $line) {
        if (trim($line) !== '') { $items[] = trim($line); }
    }
    return $items;
}
function decode_pairs(string $raw, array $keys): array {
    $lines = preg_split('/\r\n|\r|\n/', trim($raw)) ?: [];
    $items = [];
    foreach ($lines as $line) {
        if (trim($line) === '') continue;
        $parts = array_map('trim', explode('|', $line));
        $row = [];
        foreach ($keys as $index => $key) {
            $row[$key] = $parts[$index] ?? '';
        }
        $items[] = $row;
    }
    return $items;
}
function encode_pairs(array $rows, array $keys): string {
    $lines = [];
    foreach ($rows as $row) {
        $parts = [];
        foreach ($keys as $key) { $parts[] = $row[$key] ?? ''; }
        $lines[] = implode(' | ', $parts);
    }
    return implode("\n", $lines);
}

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $module['name'] = post_text('name');
        $module['anchor'] = post_text('anchor');
        $module['eyebrow'] = post_text('eyebrow');
        $module['title'] = post_text('title');
        $module['text'] = post_text('text');
        $module['button_label'] = post_text('button_label');
        $module['primary_label'] = post_text('primary_label');
        $module['secondary_label'] = post_text('secondary_label');
        $module['secondary_url'] = post_text('secondary_url');
        $module['image'] = post_text('image');
        $module['collection'] = post_text('collection');
        $module['video_url'] = post_text('video_url');
        $module['facts'] = decode_rows(post_text('facts'));
        $module['items'] = decode_pairs(post_text('items'), ['title','text']);
        $module['images'] = decode_pairs(post_text('images'), ['src','alt','caption']);
        $module['images'] = array_values(array_filter($module['images'], static fn($row) => !empty($row['src'])));
        if (($module['type'] ?? '') === 'complex_map') {
            $uploadedMap = admin_upload_image_file($_FILES['map_image_file'] ?? [], 'maps');
            $module['map_image'] = $uploadedMap ?: post_text('map_image');
            $module['address'] = post_text('address');
            $module['address_label'] = post_text('address_label');
            $module['route_note'] = post_text('route_note');
            $module['map_lat'] = str_replace(',', '.', post_text('map_lat'));
            $module['map_lon'] = str_replace(',', '.', post_text('map_lon'));
            $module['map_zoom'] = max(3, min(20, (int)post_text('map_zoom', '16')));
        }
        if (($module['type'] ?? '') === 'stats') {
            $module['items'] = decode_pairs(post_text('items_stats'), ['value','label']);
        }
        cms_save_module($id, $module);
        $notice = '<div class="notice">Блок сохранён.</div>';
    }
}

ob_start();
echo $notice;
?>
<form class="panel grid" method="post" enctype="multipart/form-data">
  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
  <div class="grid grid-2">
    <label><span>Внутреннее имя</span><input name="name" value="<?= e($module['name'] ?? '') ?>"></label>
    <label><span>Якорь</span><input name="anchor" value="<?= e($module['anchor'] ?? '') ?>"></label>
  </div>
  <div class="grid grid-2">
    <label><span>Eyebrow</span><input name="eyebrow" value="<?= e($module['eyebrow'] ?? '') ?>"></label>
    <label><span>Заголовок</span><input name="title" value="<?= e($module['title'] ?? '') ?>"></label>
  </div>
  <label><span>Текст</span><textarea name="text"><?= e($module['text'] ?? '') ?></textarea></label>

  <?php if (in_array($module['type'], ['hero','text_image','contacts','video'], true)): ?>
    <label><span>Изображение</span><input name="image" value="<?= e($module['image'] ?? '') ?>"></label>
  <?php endif; ?>

  <?php if ($module['type'] === 'hero'): ?>
    <div class="grid grid-2">
      <label><span>Текст кнопки 1</span><input name="primary_label" value="<?= e($module['primary_label'] ?? '') ?>"></label>
      <label><span>Текст кнопки 2</span><input name="secondary_label" value="<?= e($module['secondary_label'] ?? '') ?>"></label>
    </div>
    <label><span>Ссылка второй кнопки</span><input name="secondary_url" value="<?= e($module['secondary_url'] ?? '') ?>"></label>
    <label><span>Факты (каждый с новой строки)</span><textarea name="facts"><?= e(implode("\n", $module['facts'] ?? [])) ?></textarea></label>
  <?php endif; ?>

  <?php if (in_array($module['type'], ['cta','text_image'], true)): ?>
    <label><span>Текст кнопки</span><input name="button_label" value="<?= e($module['button_label'] ?? '') ?>"></label>
  <?php endif; ?>

  <?php if (in_array($module['type'], ['features'], true)): ?>
    <label><span>Карточки (формат: Заголовок | Текст, каждая с новой строки)</span><textarea name="items"><?= e(encode_pairs($module['items'] ?? [], ['title','text'])) ?></textarea></label>
  <?php endif; ?>

  <?php if ($module['type'] === 'stats'): ?>
    <label><span>Статистика (формат: Значение | Подпись, каждая с новой строки)</span><textarea name="items_stats"><?php foreach (($module['items'] ?? []) as $row) { echo e(($row['value'] ?? '') . ' | ' . ($row['label'] ?? '')) . "\n"; } ?></textarea></label>
  <?php endif; ?>

  <?php if ($module['type'] === 'gallery'): ?>
    <label><span>Изображения (формат: src | alt | caption, каждая с новой строки)</span><textarea name="images"><?= e(encode_pairs($module['images'] ?? [], ['src','alt','caption'])) ?></textarea></label>
  <?php endif; ?>

  <?php if ($module['type'] === 'video'): ?>
    <label><span>URL видео (mp4 / YouTube / Rutube embed)</span><input name="video_url" value="<?= e($module['video_url'] ?? '') ?>"></label>
  <?php endif; ?>

  <?php if (in_array($module['type'], ['houses','faq','reviews'], true)): ?>
    <label><span>Коллекция</span><input name="collection" value="<?= e($module['collection'] ?? '') ?>"></label>
  <?php endif; ?>


  <?php if ($module['type'] === 'complex_map'): ?>
    <section class="panel grid" style="margin:0;background:#fffaf1">
      <div class="badge">Карта комплекса</div>
      <label><span>Загрузить новую карту комплекса</span><input type="file" name="map_image_file" accept=".png,.jpg,.jpeg,.webp,.gif,.svg"></label>
      <label><span>Путь / URL карты комплекса</span><input name="map_image" value="<?= e($module['map_image'] ?? '') ?>" placeholder="/uploads/maps/feyaframe-map.png"></label>
      <?php if (!empty($module['map_image'])): ?><img src="<?= e($module['map_image']) ?>" alt="Карта комплекса" style="width:100%;max-height:320px;object-fit:contain;border-radius:20px;border:1px solid #e4d8c3;background:#fff"><?php endif; ?>
    </section>
    <section class="panel grid" style="margin:0;background:#fffaf1">
      <div class="badge">Точка на Яндекс.Карте</div>
      <label><span>Адрес для карты</span><input name="address" value="<?= e($module['address'] ?? '') ?>"></label>
      <label><span>Текстовый адрес под картой</span><input name="address_label" value="<?= e($module['address_label'] ?? '') ?>"></label>
      <label><span>Описание маршрута / подсказка</span><textarea name="route_note"><?= e($module['route_note'] ?? '') ?></textarea></label>
      <div class="grid grid-3">
        <label><span>Широта</span><input name="map_lat" value="<?= e($module['map_lat'] ?? '') ?>" placeholder="59.8996"></label>
        <label><span>Долгота</span><input name="map_lon" value="<?= e($module['map_lon'] ?? '') ?>" placeholder="29.0857"></label>
        <label><span>Масштаб</span><input type="number" min="3" max="20" name="map_zoom" value="<?= e((string)($module['map_zoom'] ?? 16)) ?>"></label>
      </div>
      <p class="muted" style="margin:0">Если координаты пустые, кнопка маршрута будет открывать поиск по адресу. Если заполнить широту и долготу, маршрут будет открываться точнее по этим координатам.</p>
    </section>
  <?php endif; ?>

  <div class="module-actions">
    <button class="button" type="submit">Сохранить блок</button>
    <a class="button button--ghost" href="/admin/builder.php?page=<?= e($pageSlug) ?>">Назад в конструктор</a>
  </div>
</form>
<?php
admin_layout('Редактор блока', ob_get_clean(), 'builder');
