<?php
declare(strict_types=1);

function admin_is_logged(): bool
{
    return !empty($_SESSION[ADMIN_SESSION_KEY]['logged_in']);
}

function admin_require_login(): void
{
    if (!admin_is_logged()) {
        redirect('/admin/login.php');
    }
}

function admin_login(string $username, string $password): bool
{
    if ($username === ADMIN_USERNAME && password_verify($password, ADMIN_PASSWORD_HASH)) {
        session_regenerate_id(true);
        $_SESSION[ADMIN_SESSION_KEY] = ['logged_in' => true, 'time' => time()];
        return true;
    }
    return false;
}

function admin_logout(): void
{
    unset($_SESSION[ADMIN_SESSION_KEY]);
    session_regenerate_id(true);
}

function admin_menu_sections(): array
{
    return [
        'content' => [
            'title' => 'Контент сайта',
            'items' => [
                'dashboard' => ['/admin/index.php', 'Дашборд'],
                'pages' => ['/admin/pages.php', 'Страницы'],
                'builder' => ['/admin/builder.php?page=home', 'Конструктор'],
                'houses' => ['/admin/houses.php', 'Домики'],
                'reviews' => ['/admin/reviews.php', 'Отзывы'],
                'collections' => ['/admin/collections.php?name=faq', 'Коллекции'],
                'animals' => ['/admin/animals.php', 'Про животных'],
                'booking_form' => ['/admin/booking-form.php', 'Форма бронирования'],
                'telegram_message' => ['/admin/telegram-message.php', 'Текст Telegram'],
                'location' => ['/admin/location.php', 'Карта и адрес'],
            ],
        ],
        'sales' => [
            'title' => 'Продажи и аналитика',
            'items' => [
                'availability' => ['/admin/availability.php', 'Календарь'],
                'leads' => ['/admin/leads.php', 'CRM заявки'],
                'revenue' => ['/admin/revenue.php', 'Финансы'],
                'activity' => ['/admin/activity.php', 'Онлайн-активность'],
            ],
        ],
        'appearance' => [
            'title' => 'Внешний вид и настройки',
            'items' => [
                'header' => ['/admin/header.php', 'Шапка сайта'],
                'settings' => ['/admin/settings.php', 'Настройки'],
                'analytics' => ['/admin/analytics.php', 'Метрика и пиксели'],
                'media' => ['/admin/media.php', 'Медиатека'],
            ],
        ],
        'system' => [
            'title' => 'Система',
            'items' => [
                'backups' => ['/admin/backups.php', 'Бэкапы'],
            ],
        ],
    ];
}

function admin_layout(string $title, string $content, string $active = 'dashboard'): void
{
    $menuSections = admin_menu_sections();
    ?><!DOCTYPE html>
    <html lang="ru">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <?php $adminSettings = cms_settings(); ?>
      <title><?= e($title) ?> — CMS</title>
      <link rel="icon" href="<?= e($adminSettings['branding']['favicon'] ?? '/tild6138-3238-4136-b139-333839626664/favicon.ico') ?>">
      <link rel="stylesheet" href="/admin/assets/admin.css?v=48">
    </head>
    <body>
      <div class="admin-shell">
        <aside class="admin-sidebar">
          <a class="admin-brand" href="/admin/index.php"><?= e($adminSettings['brand']['name'] ?? 'feyaframe.com') ?> CMS</a>
          <div class="admin-sidebar__caption">Управление сайтом, контентом и медиа</div>
          <nav class="admin-nav">
            <?php foreach ($menuSections as $section): ?>
              <div class="admin-nav__section">
                <div class="admin-nav__section-title"><?= e($section['title']) ?></div>
                <?php foreach ($section['items'] as $key => [$url, $label]): ?>
                  <a class="<?= $key === $active ? 'is-active' : '' ?>" href="<?= e($url) ?>"><?= e($label) ?></a>
                <?php endforeach; ?>
              </div>
            <?php endforeach; ?>
            <div class="admin-nav__section admin-nav__section--logout">
              <a href="/admin/logout.php">Выйти</a>
            </div>
          </nav>
        </aside>
        <main class="admin-main">
          <header class="admin-header">
            <h1><?= e($title) ?></h1>
            <a class="admin-view-link" href="/" target="_blank" rel="noopener">Открыть сайт ↗</a>
          </header>
          <?= $content ?>
        </main>
      </div>
      <script src="/admin/assets/admin.js?v=48"></script>
    </body>
    </html><?php
}

function module_type_options(): array
{
    return [
        'hero' => 'Hero',
        'stats' => 'Статистика',
        'text_image' => 'Текст + изображение',
        'features' => 'Преимущества',
        'gallery' => 'Галерея',
        'houses' => 'Карточки домов',
        'faq' => 'FAQ',
        'reviews' => 'Отзывы',
        'cta' => 'CTA',
        'contacts' => 'Контакты',
        'complex_map' => 'Карта комплекса и адрес',
        'video' => 'Видео',
        'rates' => 'Тарифы',
    ];
}


function admin_upload_image_file(array $file, string $subdir = ''): ?string
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        return null;
    }
    $name = (string)($file['name'] ?? 'image');
    $tmp = (string)($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        return null;
    }
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','webp','gif','svg','ico'], true)) {
        return null;
    }
    $dir = rtrim(UPLOADS_DIR . '/' . trim($subdir, '/'), '/');
    ensure_dir($dir);
    $safe = slugify(pathinfo($name, PATHINFO_FILENAME)) . '-' . date('YmdHis') . '-' . substr(bin2hex(random_bytes(3)), 0, 6) . '.' . $ext;
    if (!move_uploaded_file($tmp, $dir . '/' . $safe)) {
        return null;
    }
    $prefix = '/uploads/' . ($subdir !== '' ? trim($subdir, '/') . '/' : '');
    return $prefix . $safe;
}

function admin_upload_multiple(string $field, string $subdir = ''): array
{
    $result = [];
    if (empty($_FILES[$field]) || !is_array($_FILES[$field]['name'] ?? null)) {
        return $result;
    }
    foreach ($_FILES[$field]['name'] as $idx => $name) {
        $file = [
            'name' => $name,
            'type' => $_FILES[$field]['type'][$idx] ?? '',
            'tmp_name' => $_FILES[$field]['tmp_name'][$idx] ?? '',
            'error' => $_FILES[$field]['error'][$idx] ?? UPLOAD_ERR_NO_FILE,
            'size' => $_FILES[$field]['size'][$idx] ?? 0,
        ];
        $uploaded = admin_upload_image_file($file, $subdir);
        if ($uploaded) $result[] = $uploaded;
    }
    return $result;
}
