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

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

$collection = cms_collection('reviews');
$items = is_array($collection['items'] ?? null) ? $collection['items'] : [];
if (!$items) $items = [[]];
$notice = '';

if (request_method() === 'POST') {
    if (!verify_csrf($_POST['csrf_token'] ?? null)) {
        $notice = '<div class="notice notice--error">Ошибка безопасности.</div>';
    } else {
        $incoming = post_array('items');
        $result = [];
        foreach ($incoming as $i => $item) {
            if (!is_array($item)) continue;
            $name = trim((string)($item['name'] ?? ''));
            $text = trim((string)($item['text'] ?? ''));
            if ($name === '' && $text === '') continue;
            $photo = trim((string)($item['photo'] ?? ''));
            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) $photo = $uploaded;
            }
            $photos = lines_to_array($item['photos'] ?? '');
            $photos = array_merge($photos, admin_upload_multiple('review_photos_upload_' . $i, 'reviews'));
            if (!empty($item['remove_photos']) && is_array($item['remove_photos'])) {
                $remove = array_map('strval', $item['remove_photos']);
                $photos = array_values(array_filter($photos, static fn($src) => !in_array((string)$src, $remove, true)));
            }
            $result[] = [
                'name' => $name,
                'location' => trim((string)($item['location'] ?? '')),
                'date' => trim((string)($item['date'] ?? '')),
                'rating' => max(1, min(5, (int)($item['rating'] ?? 5))),
                'photo' => $photo,
                'photos' => array_values(array_unique(array_filter(array_map('trim', $photos)))),
                'text' => $text,
            ];
        }
        cms_save_collection('reviews', ['items' => $result]);
        $items = $result ?: [[]];
        $notice = '<div class="notice">Отзывы сохранены.</div>';
    }
}

ob_start();
echo $notice;
?>
<div class="panel admin-page-head">
  <div>
    <div class="badge">Исправленный раздел</div>
    <h2 style="margin:10px 0 6px">Отзывы гостей</h2>
    <p class="muted">Управляйте отзывами как отдельной сущностью: имя, рейтинг, текст, фото гостя и дополнительные снимки внутри карточки.</p>
  </div>
  <div class="module-actions">
    <a class="button button--ghost" href="/admin/media.php">Медиатека</a>
    <a class="button button--ghost" href="/admin/houses.php">Домики</a>
  </div>
</div>
<form method="post" enctype="multipart/form-data" class="grid" data-collection-form data-collection-name="reviews">
  <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
  <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>
  </div>
  <?php foreach ($items as $i => $item): $photos = array_values(array_filter($item['photos'] ?? [])); ?>
    <section class="collection-item review-editor" data-repeatable-item data-item-type="reviews">
      <div class="collection-item__head">
        <div>
          <strong data-item-title><?= e($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-4">
        <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>
        <label><span>Рейтинг</span><input type="number" min="1" max="5" name="items[<?= $i ?>][rating]" value="<?= e((string)($item['rating'] ?? 5)) ?>"></label>
      </div>
      <div class="grid grid-2">
        <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>
      </div>
      <label><span>Текст отзыва</span><textarea name="items[<?= $i ?>][text]"><?= e($item['text'] ?? '') ?></textarea></label>
      <div class="house-media-manager house-media-manager--pro">
        <div>
          <div class="muted" style="margin-bottom:8px">Дополнительные фотографии отзыва</div>
          <div class="admin-media-grid" data-sortable-gallery>
            <?php foreach ($photos as $src): ?>
              <label class="admin-media-card" data-sort-item draggable="true">
                <img src="<?= e($src) ?>" alt="">
                <span class="admin-media-card__caption"><?= e(basename((string)$src)) ?></span>
                <span class="pill danger"><input type="checkbox" name="items[<?= $i ?>][remove_photos][]" value="<?= e($src) ?>"> удалить</span>
              </label>
            <?php endforeach; ?>
            <?php if (!$photos): ?><div class="muted">Дополнительных фото пока нет.</div><?php endif; ?>
          </div>
        </div>
        <div class="grid">
          <label><span>Добавить фото</span><input type="file" name="review_photos_upload_<?= $i ?>[]" multiple accept=".jpg,.jpeg,.png,.webp,.gif"></label>
          <label><span>Или вставить URL фото — по одному на строку</span><textarea name="items[<?= $i ?>][photos]"><?= e(implode("\n", $photos)) ?></textarea></label>
        </div>
      </div>
    </section>
  <?php endforeach; ?>
</form>
<?php
admin_layout('Отзывы гостей', ob_get_clean(), 'reviews');
