<?php
// index.php — главная страница, генерация галереи из gallery/
$galleryDir = __DIR__ . '/gallery';

function scanGallery($dir) {
    $sessions = [];
    if (!is_dir($dir)) return $sessions;

    $items = scandir($dir);
    sort($items);

    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;

        $path = $dir . '/' . $item;

        if (is_dir($path)) {
            // Подпапка = сессия
            $images = array_map(function ($f) use ($item) {
                return $item . '/' . $f;
            }, scanImages($path));
            $desc = '';
            if (file_exists($path . '/desc.txt')) {
                $desc = normalizeText(file_get_contents($path . '/desc.txt'));
            }
            if (!empty($images)) {
                $sessions[] = [
                    'folder' => $item,
                    'desc'   => $desc,
                    'images' => $images
                ];
            }
        } elseif (isImage($item)) {
            // Файл в корне gallery/ = одиночная сессия
            $sessions[] = [
                'folder' => '',
                'desc'   => '',
                'images' => [$item]
            ];
        }
    }

    return $sessions;
}

function scanImages($dir) {
    $ext = ['jpg', 'jpeg', 'png', 'webp', 'avif', 'gif'];
    $files = [];
    foreach (scandir($dir) as $f) {
        if ($f === '.' || $f === '..') continue;
        if (is_file($dir . '/' . $f)) {
            $e = strtolower(pathinfo($f, PATHINFO_EXTENSION));
            if (in_array($e, $ext)) $files[] = $f;
        }
    }
    sort($files, SORT_NATURAL | SORT_FLAG_CASE);
    return $files;
}

function isImage($name) {
    $ext = ['jpg', 'jpeg', 'png', 'webp', 'avif', 'gif'];
    return in_array(strtolower(pathinfo($name, PATHINFO_EXTENSION)), $ext);
}

// Приводит текст описания к валидному UTF-8.
// Работает и без mbstring: файл мог быть сохранён в Windows-1251.
function normalizeText($text) {
    if ($text === false || $text === null) return '';
    // Убираем BOM
    $text = preg_replace('/^\xEF\xBB\xBF/', '', $text);

    // Валидный UTF-8 — оставляем как есть
    if (preg_match('//u', $text) === 1) {
        return $text;
    }

    // Пробуем перекодировать из Windows-1251
    if (function_exists('mb_convert_encoding')) {
        $converted = @mb_convert_encoding($text, 'UTF-8', 'Windows-1251');
        if (is_string($converted) && preg_match('//u', $converted) === 1) {
            return $converted;
        }
    } elseif (function_exists('iconv')) {
        $converted = @iconv('Windows-1251', 'UTF-8//IGNORE', $text);
        if (is_string($converted) && preg_match('//u', $converted) === 1) {
            return $converted;
        }
    }

    // Последняя страховка: выкидываем невалидные байты
    return preg_replace('/[\x80-\xFF]/', '', $text);
}

// json_encode с гарантией валидного результата
function toJson($data) {
    $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
    if (defined('JSON_INVALID_UTF8_SUBSTITUTE')) {
        $flags |= JSON_INVALID_UTF8_SUBSTITUTE;
    }
    if (defined('JSON_PARTIAL_OUTPUT_ON_ERROR')) {
        $flags |= JSON_PARTIAL_OUTPUT_ON_ERROR;
    }

    $json = json_encode($data, $flags);
    if ($json === false || $json === null || $json === '') {
        // Аварийный вариант: без юникода и слешей, но всегда валидный
        $json = json_encode($data);
    }
    return ($json === false || $json === null || $json === '') ? '[]' : $json;
}

$sessions = scanGallery($galleryDir);
?>
<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>IVAN PEREDERO — trash horror photography</title>
  <link rel="stylesheet" href="style.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Special+Elite&family=Inter:wght@300;400;700&display=swap" rel="stylesheet">
</head>
<body>
  <!-- Vignette -->
  <div class="vignette" aria-hidden="true"></div>

  <!-- Помехи старого монитора -->
  <div class="static-overlay" aria-hidden="true"></div>
  <div class="scanlines" aria-hidden="true"></div>

  <!-- Navigation -->
  <nav class="nav">
    <a href="#" class="nav-logo">IP</a>
    <ul class="nav-links">
      <li><a href="#gallery">Галерея</a></li>
      <li><a href="#about">Обо мне</a></li>
      <li><a href="#contact">Контакт</a></li>
    </ul>
  </nav>

  <!-- Hero -->
  <header class="hero" id="hero">
    <div class="hero-content">
      <h1 class="hero-title">
        <span class="title-line">IVAN</span>
        <span class="title-line title-last">PEREDERO</span>
      </h1>
      <p class="hero-subtitle">программист &amp; trash horror photography</p>
      <div class="hero-divider"></div>
      <p class="hero-tagline">красота в уродстве</p>
    </div>
    <div class="hero-scroll">
      <span>scroll</span>
      <div class="scroll-line"></div>
    </div>
  </header>

  <!-- Gallery -->
  <section class="gallery" id="gallery">
    <h2 class="section-title">
      <span class="title-mark">///</span> Галерея
    </h2>
    <div class="gallery-grid" id="gallery-grid"></div>
  </section>

  <!-- About -->
  <section class="about" id="about">
    <div class="about-container">
      <div class="about-left">
        <h2 class="section-title">
          <span class="title-mark">///</span> Обо мне
        </h2>
      </div>
      <div class="about-right">
        <p class="about-text">
          Меня зовут <strong>Ivan Peredero</strong>. Я программист и люблю
          <em>trash horror photography</em> — эстетику разбитых зеркал,
          повреждённых плёнок, крови и неоновых огней ночного города.
        </p>
        <p class="about-text">
          В коде я создаю системы. В фотографии — разрушаю их.
          Каждый кадр — это момент, когда что-то идёт не так,
          и именно в этой ошибке рождается красота.
        </p>
        <div class="about-skills">
          <h3>навыки</h3>
          <ul>
            <li>программирование</li>
            <li>trash horror photography</li>
            <li>визуальные эффекты</li>
            <li>постпродакшн</li>
          </ul>
        </div>
      </div>
    </div>
  </section>

  <!-- Contact -->
  <section class="contact" id="contact">
    <h2 class="section-title">
      <span class="title-mark">///</span> Контакт
    </h2>
    <div class="contact-content">
      <p class="contact-text">
        Есть идея для коллаборации? Хочешь обсудить эстетику упадка?
        Напиши мне.
      </p>
      <a href="mailto:ivan@perederoblog.com" class="contact-email">
        ivan@perederoblog.com
      </a>
      <div class="contact-links">
        <a href="https://t.me/philosophyabsurd" class="contact-link">Telegram</a>
        <a href="#" class="contact-link">GitHub</a>
      </div>
    </div>
  </section>

  <!-- Footer -->
  <footer class="footer">
    <p>&copy; 2010-2026 Ivan Peredero. Все права защищены. И ни у кого нет.</p>
  </footer>

  <script>
    // Передаём данные из PHP в JS
    window.GALLERY = <?php echo toJson($sessions); ?>;
  </script>
  <script src="script.js"></script>
</body>
</html>
