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

$name = $_GET['name'] ?? 'houses';
$allowed = ['houses', 'faq', 'reviews', 'rates', 'gallery'];
if (!in_array($name, $allowed, true)) {
    $name = 'houses';
}
$collection = cms_collection($name);
$collection['items'] = is_array($collection['items'] ?? null) ? $collection['items'] : [];
if ($collection['items'] === []) {
    $collection['items'][] = [];
}
$notice = '';

function admin_item_title(array $item, string $name): string
{
    switch ($name) {
        case 'houses': return (string)($item['title'] ?? 'Домик');
        case 'rates': return (string)($item['house'] ?? 'Тариф');
        case 'faq': return (string)($item['question'] ?? 'FAQ');
        case 'reviews': return (string)($item['name'] ?? 'Отзыв');
        case 'gallery': return (string)($item['alt'] ?? $item['caption'] ?? 'Фото');
        default: return 'Элемент';
    }
}

function admin_lines_to_array($value): array
{
    if (is_array($value)) {
        return array_values(array_filter(array_map(static function ($v) { return trim((string)$v); }, $value)));
    }
    $parts = preg_split('/\r\n|\r|\n/', (string)$value) ?: [];
    return array_values(array_filter(array_map('trim', $parts)));
}

function preview_image(?string $src): string
{
    if (!$src) return '';
    return '<div class="admin-image-preview"><img src="' . e($src) . '" alt=""></div>';
}

function preview_gallery(array $items): string
{
    $items = array_values(array_filter(array_map('trim', $items)));
    if (!$items) return '';
    $html = '<div class="admin-preview-grid">';
    foreach ($items as $src) {
        $html .= '<div class="admin-preview-grid__item"><img src="' . e($src) . '" alt=""></div>';
    }
    return $html . '</div>';
}

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $items = [];
        foreach (post_array('items') as $i => $item) {
            if (!is_array($item)) continue;
            $clean = [];
            foreach ($item as $k => $v) {
                $clean[$k] = is_string($v) ? trim($v) : $v;
            }
            $primary = $clean['title'] ?? $clean['question'] ?? $clean['name'] ?? $clean['house'] ?? $clean['src'] ?? '';
            if ($primary === '' && $name !== 'gallery') {
                continue;
            }
            if ($name === 'houses') {
                $existingGallery = admin_lines_to_array($clean['gallery'] ?? '');
                if (!empty($_FILES['house_main_upload']['name'][$i])) {
                    $file = [
                        'name' => $_FILES['house_main_upload']['name'][$i],
                        'type' => $_FILES['house_main_upload']['type'][$i] ?? '',
                        'tmp_name' => $_FILES['house_main_upload']['tmp_name'][$i] ?? '',
                        'error' => $_FILES['house_main_upload']['error'][$i] ?? UPLOAD_ERR_NO_FILE,
                        'size' => $_FILES['house_main_upload']['size'][$i] ?? 0,
                    ];
                    $uploaded = admin_upload_image_file($file, 'houses');
                    if ($uploaded) {
                        $clean['image'] = $uploaded;
                        array_unshift($existingGallery, $uploaded);
                    }
                }
                $galleryField = 'house_gallery_upload_' . $i;
                $existingGallery = array_merge($existingGallery, admin_upload_multiple($galleryField, 'houses'));
                $clean['gallery'] = array_values(array_unique(array_values(array_filter($existingGallery))));
                $clean['features'] = admin_lines_to_array($clean['features'] ?? '');
                if (empty($clean['image']) && !empty($clean['gallery'][0])) {
                    $clean['image'] = $clean['gallery'][0];
                }
            }
            if ($name === 'reviews') {
                if (!empty($_FILES['review_avatar_upload']['name'][$i])) {
                    $file = [
                        'name' => $_FILES['review_avatar_upload']['name'][$i],
                        'type' => $_FILES['review_avatar_upload']['type'][$i] ?? '',
                        'tmp_name' => $_FILES['review_avatar_upload']['tmp_name'][$i] ?? '',
                        'error' => $_FILES['review_avatar_upload']['error'][$i] ?? UPLOAD_ERR_NO_FILE,
                        'size' => $_FILES['review_avatar_upload']['size'][$i] ?? 0,
                    ];
                    $uploaded = admin_upload_image_file($file, 'reviews');
                    if ($uploaded) {
                        $clean['photo'] = $uploaded;
                    }
                }
                $photos = admin_lines_to_array($clean['photos'] ?? '');
                $photos = array_merge($photos, admin_upload_multiple('review_photos_upload_' . $i, 'reviews'));
                $clean['photos'] = array_values(array_unique(array_values(array_filter($photos))));
            }
            if ($name === 'gallery') {
                if (!empty($_FILES['gallery_image_upload']['name'][$i])) {
                    $file = [
                        'name' => $_FILES['gallery_image_upload']['name'][$i],
                        'type' => $_FILES['gallery_image_upload']['type'][$i] ?? '',
                        'tmp_name' => $_FILES['gallery_image_upload']['tmp_name'][$i] ?? '',
                        'error' => $_FILES['gallery_image_upload']['error'][$i] ?? UPLOAD_ERR_NO_FILE,
                        'size' => $_FILES['gallery_image_upload']['size'][$i] ?? 0,
                    ];
                    $uploaded = admin_upload_image_file($file, 'gallery');
                    if ($uploaded) {
                        $clean['src'] = $uploaded;
                    }
                }
                if (($clean['src'] ?? '') === '') continue;
            }
            if ($name === 'faq') {
                $clean = ['question' => (string)($clean['question'] ?? ''), 'answer' => (string)($clean['answer'] ?? '')];
            }
            if ($name === 'rates') {
                $clean['house'] = (string)($clean['house'] ?? '');
            }
            $items[] = $clean;
        }
        $collection['items'] = $items;
        cms_save_collection($name, $collection);
        $notice = '<div class="notice">Коллекция сохранена.</div>';
    }
}

ob_start();
echo $notice;
?>
<div class="collection-toolbar">
  <div class="module-actions">
    <a class="button button--ghost" href="/admin/houses.php">Домики</a>
    <a class="button <?= $name === 'rates' ? '' : 'button--ghost' ?>" href="/admin/collections.php?name=rates">Тарифы</a>
    <a class="button <?= $name === 'faq' ? '' : 'button--ghost' ?>" href="/admin/collections.php?name=faq">FAQ</a>
    <a class="button button--ghost" href="/admin/reviews.php">Отзывы</a>
    <a class="button <?= $name === 'gallery' ? '' : 'button--ghost' ?>" href="/admin/collections.php?name=gallery">Фотогалерея</a>
  </div>
  <div class="badge">Премиальный режим: превью, сортировка, быстрые перестановки и удобное управление фото</div>
</div>

<form class="grid" method="post" enctype="multipart/form-data" style="margin-top:18px" data-collection-form data-collection-name="<?= e($name) ?>">
  <?php if ($name === 'gallery'): ?>
  <section class="panel gallery-manager__toolbar">
    <div>
      <div class="badge">Фотогалерея</div>
      <div class="gallery-manager__hint">Здесь можно менять порядок фотографий кнопками ↑ ↓, быстро удалять лишние кадры и видеть крупное превью. После сохранения порядок сразу применяется на сайте.</div>
    </div>
  </section>
  <?php endif; ?>
  <div class="panel sticky-actions">
    <div class="module-actions">
      <button class="button button--ghost" type="button" data-add-item>Добавить элемент</button>
      <button class="button" type="submit">Сохранить коллекцию</button>
    </div>
    <p class="muted admin-helper-text">Можно добавлять и удалять элементы, загружать фото прямо в сущность и сразу видеть превью.</p>
  </div>
  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">

  <?php if ($name === 'houses'): ?>
    <?php foreach (($collection['items'] ?? []) as $i => $item): ?>
      <section class="collection-item grid" data-repeatable-item data-item-type="houses">
        <div class="collection-item__head">
          <div>
            <strong data-item-title><?= e(admin_item_title($item, $name)) ?></strong>
            <div class="muted">Управление карточкой домика, главным фото, галереей и описанием.</div>
          </div>
          <button class="button button--ghost button--small" type="button" data-remove-item>Удалить</button>
        </div>
        <div class="grid grid-2">
          <label><span>Название</span><input data-title-source name="items[<?= $i ?>][title]" value="<?= e($item['title'] ?? '') ?>"></label>
          <label><span>Цена будни / базовая</span><input name="items[<?= $i ?>][price]" value="<?= e($item['price'] ?? '') ?>"></label>
        </div>
        <div class="grid grid-3">
          <label><span>Короткое meta</span><input name="items[<?= $i ?>][meta]" value="<?= e($item['meta'] ?? '') ?>"></label>
          <label><span>Вместимость</span><input name="items[<?= $i ?>][capacity]" value="<?= e($item['capacity'] ?? '') ?>"></label>
          <label><span>Площадь / формат</span><input name="items[<?= $i ?>][area]" value="<?= e($item['area'] ?? '') ?>"></label>
        </div>
        <div class="grid grid-2">
          <label><span>Цена выходные</span><input name="items[<?= $i ?>][weekend_price]" value="<?= e($item['weekend_price'] ?? '') ?>"></label>
          <label><span>Цена праздники</span><input name="items[<?= $i ?>][holiday_price]" value="<?= e($item['holiday_price'] ?? '') ?>"></label>
        </div>
        <div class="grid grid-2">
          <label><span>Краткое описание</span><textarea name="items[<?= $i ?>][description]"><?= e($item['description'] ?? '') ?></textarea></label>
          <label><span>Подробное описание</span><textarea name="items[<?= $i ?>][full_description]"><?= e($item['full_description'] ?? '') ?></textarea></label>
        </div>
        <div class="grid grid-2">
          <label><span>Главное изображение (URL)</span><input data-image-input name="items[<?= $i ?>][image]" value="<?= e($item['image'] ?? '') ?>"></label>
          <label><span>Загрузить главное изображение</span><input type="file" name="house_main_upload[<?= $i ?>]" accept=".jpg,.jpeg,.png,.webp,.gif"></label>
        </div>
        <?= preview_image($item['image'] ?? '') ?>
        <div class="grid grid-2">
          <label><span>Особенность / вид</span><input name="items[<?= $i ?>][view]" value="<?= e($item['view'] ?? '') ?>"></label>
          <label><span>Фишки (каждая с новой строки)</span><textarea name="items[<?= $i ?>][features]"><?= e(implode("\n", $item['features'] ?? [])) ?></textarea></label>
        </div>
        <div class="grid grid-2">
          <label><span>Галерея (каждый URL с новой строки)</span><textarea name="items[<?= $i ?>][gallery]"><?= e(implode("\n", $item['gallery'] ?? [])) ?></textarea></label>
          <label><span>Добавить фото в галерею</span><input type="file" name="house_gallery_upload_<?= $i ?>[]" multiple accept=".jpg,.jpeg,.png,.webp,.gif"></label>
        </div>
        <?= preview_gallery($item['gallery'] ?? []) ?>
      </section>
    <?php endforeach; ?>
  <?php elseif ($name === 'rates'): ?>
    <?php foreach (($collection['items'] ?? []) as $i => $item): ?>
      <section class="collection-item grid" data-repeatable-item data-item-type="rates">
        <div class="collection-item__head"><div><strong data-item-title><?= e(admin_item_title($item, $name)) ?></strong><div class="muted">Тариф для домика с сезонами и ценами.</div></div><div class="collection-item__tools"><button class="button button--ghost button--small button--icon" type="button" data-move-up title="Поднять выше">↑</button><button class="button button--ghost button--small button--icon" type="button" data-move-down title="Опустить ниже">↓</button><button class="button button--ghost button--small" type="button" data-remove-item>Удалить</button></div></div>
        <div class="grid grid-3">
          <label><span>Домик</span><input data-title-source name="items[<?= $i ?>][house]" value="<?= e($item['house'] ?? '') ?>"></label>
          <label><span>Сезон / тариф</span><input name="items[<?= $i ?>][season]" value="<?= e($item['season'] ?? '') ?>"></label>
          <label><span>Мин. ночей</span><input name="items[<?= $i ?>][min_nights]" value="<?= e($item['min_nights'] ?? '') ?>"></label>
        </div>
        <div class="grid grid-3">
          <label><span>Цена будни</span><input name="items[<?= $i ?>][weekday_price]" value="<?= e($item['weekday_price'] ?? '') ?>"></label>
          <label><span>Цена выходные</span><input name="items[<?= $i ?>][weekend_price]" value="<?= e($item['weekend_price'] ?? '') ?>"></label>
          <label><span>Цена праздники</span><input name="items[<?= $i ?>][holiday_price]" value="<?= e($item['holiday_price'] ?? '') ?>"></label>
        </div>
        <label><span>Примечание</span><textarea name="items[<?= $i ?>][notes]"><?= e($item['notes'] ?? '') ?></textarea></label>
      </section>
    <?php endforeach; ?>
  <?php elseif ($name === 'faq'): ?>
    <?php foreach (($collection['items'] ?? []) as $i => $item): ?>
      <section class="collection-item grid" data-repeatable-item data-item-type="faq">
        <div class="collection-item__head">
          <div>
            <strong data-item-title><?= e(admin_item_title($item, $name)) ?></strong>
            <div class="muted">Вопрос и ответ для FAQ. Можно прикрепить фото к ответу.</div>
          </div>
          <div class="collection-item__tools">
            <button class="button button--ghost button--small button--icon" type="button" data-move-up title="Поднять выше">↑</button>
            <button class="button button--ghost button--small button--icon" type="button" data-move-down title="Опустить ниже">↓</button>
            <button class="button button--ghost button--small" type="button" data-remove-item>Удалить</button>
          </div>
        </div>
        <div class="grid grid-2">
          <label><span>Вопрос</span><input data-title-source name="items[<?= $i ?>][question]" value="<?= e($item['question'] ?? '') ?>"></label>
          <label><span>URL изображения к ответу</span><input data-image-input name="items[<?= $i ?>][image]" value="<?= e($item['image'] ?? '') ?>"></label>
        </div>
        <div class="grid grid-2">
          <label><span>Загрузить изображение</span><input type="file" name="faq_image_upload[<?= $i ?>]" accept=".jpg,.jpeg,.png,.webp,.gif"></label>
          <div><?= preview_image($item['image'] ?? '') ?></div>
        </div>
        <label><span>Ответ</span><textarea name="items[<?= $i ?>][answer]" rows="5"><?= e($item['answer'] ?? '') ?></textarea></label>
      </section>
    <?php endforeach; ?>
<?php elseif ($name === 'reviews'): ?>
    <?php foreach (($collection['items'] ?? []) as $i => $item): ?>
      <section class="collection-item grid review-editor" data-repeatable-item data-item-type="reviews">
        <div class="collection-item__head">
          <div>
            <strong data-item-title><?= e(admin_item_title($item, $name)) ?></strong>
            <div class="muted">Исправленный редактор отзывов: фото гостя, галерея, рейтинг и текст без поломки интерфейса.</div>
          </div>
          <button class="button button--ghost button--small" type="button" data-remove-item>Удалить</button>
        </div>
        <div class="grid grid-3">
          <label><span>Имя гостя</span><input data-title-source name="items[<?= $i ?>][name]" value="<?= e($item['name'] ?? '') ?>"></label>
          <label><span>Локация / подпись</span><input name="items[<?= $i ?>][location]" value="<?= e($item['location'] ?? '') ?>"></label>
          <label><span>Дата / сезон</span><input name="items[<?= $i ?>][date]" value="<?= e($item['date'] ?? '') ?>"></label>
        </div>
        <div class="grid grid-3">
          <label><span>Фото гостя (URL)</span><input data-image-input name="items[<?= $i ?>][photo]" value="<?= e($item['photo'] ?? '') ?>"></label>
          <label><span>Загрузить фото гостя</span><input type="file" name="review_avatar_upload[<?= $i ?>]" accept=".jpg,.jpeg,.png,.webp,.gif"></label>
          <label><span>Рейтинг (1–5)</span><input name="items[<?= $i ?>][rating]" value="<?= e((string)($item['rating'] ?? '5')) ?>"></label>
        </div>
        <?= preview_image($item['photo'] ?? '') ?>
        <div class="grid grid-2">
          <label><span>Доп. фото (каждый URL с новой строки)</span><textarea name="items[<?= $i ?>][photos]"><?= e(implode("\n", $item['photos'] ?? [])) ?></textarea></label>
          <label><span>Добавить доп. фото</span><input type="file" name="review_photos_upload_<?= $i ?>[]" multiple accept=".jpg,.jpeg,.png,.webp,.gif"></label>
        </div>
        <?= preview_gallery($item['photos'] ?? []) ?>
        <label><span>Текст отзыва</span><textarea name="items[<?= $i ?>][text]" class="review-editor__textarea"><?= e($item['text'] ?? '') ?></textarea></label>
      </section>
    <?php endforeach; ?>
  <?php elseif ($name === 'gallery'): ?>
    <section class="panel gallery-manager__toolbar">
      <div>
        <div class="badge">Фотогалерея — удобный редактор</div>
        <div class="gallery-manager__hint">Меняйте порядок фотографий стрелками ↑ ↓, смотрите крупное превью, правьте alt и подписи без путаницы. Сохраняется именно тот порядок, который вы соберёте здесь.</div>
      </div>
    </section>
    <?php foreach (($collection['items'] ?? []) as $i => $item): ?>
      <section class="collection-item grid gallery-item" data-repeatable-item data-item-type="gallery">
        <div class="collection-item__head">
          <div>
            <strong data-item-title><?= e(($item['alt'] ?? '') ?: admin_item_title($item, $name)) ?></strong>
            <div class="muted">Элемент фотогалереи на главной странице.</div>
          </div>
          <div class="collection-item__tools">
            <button class="button button--ghost button--small button--icon" type="button" data-move-up title="Поднять выше">↑</button>
            <button class="button button--ghost button--small button--icon" type="button" data-move-down title="Опустить ниже">↓</button>
            <button class="button button--ghost button--small" type="button" data-remove-item>Удалить</button>
          </div>
        </div>

        <div class="gallery-order">
          <?= preview_image($item['src'] ?? '') ?>
          <div class="gallery-fields">
            <div class="grid grid-2">
              <label><span>URL фото</span><input data-image-input data-title-source name="items[<?= $i ?>][src]" value="<?= e($item['src'] ?? '') ?>"></label>
              <label><span>Загрузить фото</span><input type="file" name="gallery_image_upload[<?= $i ?>]" accept=".jpg,.jpeg,.png,.webp,.gif"></label>
            </div>
            <div class="grid grid-2">
              <label><span>Alt / название</span><input name="items[<?= $i ?>][alt]" value="<?= e($item['alt'] ?? '') ?>"></label>
              <label><span>Краткая подпись</span><input name="items[<?= $i ?>][caption]" value="<?= e($item['caption'] ?? '') ?>"></label>
            </div>
          </div>
        </div>
      </section>
    <?php endforeach; ?>
  <?php endif; ?>

  <div class="module-actions"><button class="button" type="submit">Сохранить коллекцию</button></div>
</form>
<?php
admin_layout('Сущности: ' . strtoupper($name), ob_get_clean(), 'collections');
