<?php
declare(strict_types=1);

require_once __DIR__ . '/../../includes/start.php';
require_role(['admin']);

require_once __DIR__ . '/../_helpers.php';
require_once __DIR__ . '/../_sidebar.php';
require_once __DIR__ . '/_lib.php';

$pdo = seo_admin_db();
$me  = seo_admin_me();
$adminUserId = (int)($me['id'] ?? 0);
$settings = seo_admin_load_settings($pdo);
$flash = seo_admin_get_flash();

$title = admin_tt('seo_title', 'Налаштування sitemap', 'Настройки sitemap', 'Sitemap settings');
$seoAdminActive = 'sitemap';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!seo_admin_csrf_check_local((string)($_POST['csrf'] ?? ''))) {
        seo_admin_set_flash('danger', seo_admin_t('Помилка CSRF.', 'Ошибка CSRF.', 'CSRF error.'));
        header('Location: ' . seo_admin_url('sitemap.php'));
        exit;
    }

    $maxUrls = max(100, min(50000, (int)($_POST['seo_sitemap_max_urls'] ?? 50000)));
    $changefreq = (string)($_POST['seo_sitemap_changefreq'] ?? 'daily');
    if (!in_array($changefreq, ['always','hourly','daily','weekly','monthly','yearly','never'], true)) {
        $changefreq = 'daily';
    }

    $payload = [
        'seo_sitemap_include_profiles'        => seo_admin_bool_from_post('seo_sitemap_include_profiles'),
        'seo_sitemap_include_groups'          => seo_admin_bool_from_post('seo_sitemap_include_groups'),
        'seo_sitemap_include_posts'           => seo_admin_bool_from_post('seo_sitemap_include_posts'),
        'seo_sitemap_include_albums'          => seo_admin_bool_from_post('seo_sitemap_include_albums'),
        'seo_sitemap_include_static'          => seo_admin_bool_from_post('seo_sitemap_include_static'),
        'seo_sitemap_exclude_private_profiles'=> seo_admin_bool_from_post('seo_sitemap_exclude_private_profiles'),
        'seo_sitemap_exclude_closed_groups'   => seo_admin_bool_from_post('seo_sitemap_exclude_closed_groups'),
        'seo_sitemap_max_urls'                => (string)$maxUrls,
        'seo_sitemap_changefreq'              => $changefreq,
        'seo_sitemap_priority_home'           => trim((string)($_POST['seo_sitemap_priority_home'] ?? '1.0')),
        'seo_sitemap_priority_profile'        => trim((string)($_POST['seo_sitemap_priority_profile'] ?? '0.8')),
        'seo_sitemap_priority_group'          => trim((string)($_POST['seo_sitemap_priority_group'] ?? '0.8')),
        'seo_sitemap_priority_post'           => trim((string)($_POST['seo_sitemap_priority_post'] ?? '0.7')),
        'seo_sitemap_priority_album'          => trim((string)($_POST['seo_sitemap_priority_album'] ?? '0.7')),
    ];

    try {
        $old = $settings;
        seo_admin_save_settings($pdo, $payload);
        seo_admin_add_log($pdo, $adminUserId, 'sitemap', null, 'sitemap.save', $old, $payload);
        seo_admin_set_flash('success', seo_admin_t('Налаштування sitemap збережено.', 'Настройки sitemap сохранены.', 'Sitemap settings saved.'));
    } catch (Throwable $e) {
        seo_admin_set_flash('danger', seo_admin_t('Не вдалося зберегти sitemap-налаштування.', 'Не удалось сохранить sitemap-настройки.', 'Failed to save sitemap settings.'));
    }

    header('Location: ' . seo_admin_url('sitemap.php'));
    exit;
}

$stats = seo_admin_dashboard_stats($pdo);
$sitemapUrl = '/sitemap.xml.php';

require __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-lg-9">
    <?php require __DIR__ . '/_nav.php'; ?>

    <?php if ($flash): ?>
      <div class="alert alert-<?= seo_admin_h((string)($flash['type'] ?? 'info')) ?>">
        <?= seo_admin_h((string)($flash['message'] ?? '')) ?>
      </div>
    <?php endif; ?>

    <div class="card card-app p-3 mb-3">
      <div class="d-flex align-items-center justify-content-between gap-2 mb-2 flex-wrap">
        <h1 class="h4 mb-0"><?= seo_admin_h($title) ?></h1>
        <a class="btn btn-outline-primary btn-sm" href="<?= seo_admin_h($sitemapUrl) ?>" target="_blank" rel="noopener"><?= seo_admin_h(seo_admin_t('Відкрити sitemap', 'Открыть sitemap', 'Open sitemap')) ?></a>
      </div>

      <form method="post">
        <input type="hidden" name="csrf" value="<?= seo_admin_h(seo_admin_csrf_token_local()) ?>">

        <div class="row g-3">
          <div class="col-12 col-xl-6">
            <div class="border rounded p-3 h-100">
              <div class="fw-semibold mb-2"><?= seo_admin_h(seo_admin_t('Що включати в sitemap', 'Что включать в sitemap', 'What to include in the sitemap')) ?></div>

              <?php
              $incFields = [
                'seo_sitemap_include_static' => seo_admin_t('Статичні сторінки', 'Статические страницы', 'Static pages'),
                'seo_sitemap_include_profiles' => seo_admin_t('Профілі', 'Профили', 'Profiles'),
                'seo_sitemap_include_groups' => seo_admin_t('Групи', 'Группы', 'Groups'),
                'seo_sitemap_include_posts' => seo_admin_t('Пости', 'Посты', 'Posts'),
                'seo_sitemap_include_albums' => seo_admin_t('Фотоальбоми', 'Фотоальбомы', 'Photo albums'),
                'seo_sitemap_exclude_private_profiles' => seo_admin_t('Виключати приватні профілі', 'Исключать приватные профили', 'Exclude private profiles'),
                'seo_sitemap_exclude_closed_groups' => seo_admin_t('Виключати закриті групи', 'Исключать закрытые группы', 'Exclude closed groups'),
              ];
              ?>

              <div class="d-flex flex-column gap-2">
                <?php foreach ($incFields as $key => $label): ?>
                  <label class="form-check">
                    <input class="form-check-input" type="checkbox" name="<?= seo_admin_h($key) ?>" value="1" <?= ($settings[$key] ?? '0') === '1' ? 'checked' : '' ?>>
                    <span class="form-check-label"><?= seo_admin_h($label) ?></span>
                  </label>
                <?php endforeach; ?>
              </div>
            </div>
          </div>

          <div class="col-12 col-xl-6">
            <div class="border rounded p-3 h-100">
              <div class="fw-semibold mb-2"><?= seo_admin_h(seo_admin_t('Ліміти й частота', 'Лимиты и частота', 'Limits and frequency')) ?></div>
              <div class="mb-3">
                <label class="form-label"><?= seo_admin_h(seo_admin_t('Максимум URL', 'Максимум URL', 'Maximum URLs')) ?></label>
                <input type="number" min="100" max="50000" class="form-control" name="seo_sitemap_max_urls" value="<?= seo_admin_h($settings['seo_sitemap_max_urls'] ?? '50000') ?>">
              </div>
              <div class="mb-0">
                <label class="form-label"><?= seo_admin_h(seo_admin_t('changefreq за замовчуванням', 'changefreq по умолчанию', 'Default changefreq')) ?></label>
                <select class="form-select" name="seo_sitemap_changefreq">
                  <?php foreach (['always','hourly','daily','weekly','monthly','yearly','never'] as $freq): ?>
                    <option value="<?= seo_admin_h($freq) ?>" <?= ($settings['seo_sitemap_changefreq'] ?? 'daily') === $freq ? 'selected' : '' ?>><?= seo_admin_h($freq) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
          </div>

          <div class="col-12">
            <div class="border rounded p-3">
              <div class="fw-semibold mb-2"><?= seo_admin_h(seo_admin_t('Priority по типах сторінок', 'Priority по типам страниц', 'Priority by page type')) ?></div>
              <div class="row g-3">
                <div class="col-md-6 col-xl-2">
                  <label class="form-label">Home</label>
                  <input type="text" class="form-control" name="seo_sitemap_priority_home" value="<?= seo_admin_h($settings['seo_sitemap_priority_home'] ?? '1.0') ?>">
                </div>
                <div class="col-md-6 col-xl-2">
                  <label class="form-label"><?= seo_admin_h(seo_admin_t('Профілі', 'Профили', 'Profiles')) ?></label>
                  <input type="text" class="form-control" name="seo_sitemap_priority_profile" value="<?= seo_admin_h($settings['seo_sitemap_priority_profile'] ?? '0.8') ?>">
                </div>
                <div class="col-md-6 col-xl-2">
                  <label class="form-label"><?= seo_admin_h(seo_admin_t('Групи', 'Группы', 'Groups')) ?></label>
                  <input type="text" class="form-control" name="seo_sitemap_priority_group" value="<?= seo_admin_h($settings['seo_sitemap_priority_group'] ?? '0.8') ?>">
                </div>
                <div class="col-md-6 col-xl-2">
                  <label class="form-label"><?= seo_admin_h(seo_admin_t('Пости', 'Посты', 'Posts')) ?></label>
                  <input type="text" class="form-control" name="seo_sitemap_priority_post" value="<?= seo_admin_h($settings['seo_sitemap_priority_post'] ?? '0.7') ?>">
                </div>
                <div class="col-md-6 col-xl-2">
                  <label class="form-label"><?= seo_admin_h(seo_admin_t('Альбоми', 'Альбомы', 'Albums')) ?></label>
                  <input type="text" class="form-control" name="seo_sitemap_priority_album" value="<?= seo_admin_h($settings['seo_sitemap_priority_album'] ?? '0.7') ?>">
                </div>
              </div>
            </div>
          </div>

          <div class="col-12">
            <div class="border rounded p-3">
              <div class="fw-semibold mb-2"><?= seo_admin_h(seo_admin_t('Швидка довідка', 'Быстрая справка', 'Quick notes')) ?></div>
              <div class="small text-muted">
                <?= seo_admin_h(seo_admin_t('На базі поточної БД у тебе є профілі, групи, пости та фотоальбоми — модуль уже враховує ці сутності.', 'На базе текущей БД у тебя есть профили, группы, посты и фотоальбомы — модуль уже учитывает эти сущности.', 'Based on your current DB you already have profiles, groups, posts and photo albums — the module already accounts for them.')) ?>
              </div>
              <div class="row g-3 mt-1 small">
                <div class="col-md-3"><?= seo_admin_h(seo_admin_t('Профілі', 'Профили', 'Profiles')) ?>: <strong><?= (int)$stats['users_total'] ?></strong></div>
                <div class="col-md-3"><?= seo_admin_h(seo_admin_t('Групи', 'Группы', 'Groups')) ?>: <strong><?= (int)$stats['groups_total'] ?></strong></div>
                <div class="col-md-3"><?= seo_admin_h(seo_admin_t('Пости', 'Посты', 'Posts')) ?>: <strong><?= (int)$stats['posts_total'] ?></strong></div>
                <div class="col-md-3"><?= seo_admin_h(seo_admin_t('Альбоми', 'Альбомы', 'Albums')) ?>: <strong><?= (int)$stats['albums_total'] ?></strong></div>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-3">
          <button class="btn btn-primary" type="submit"><?= seo_admin_h(seo_admin_t('Зберегти', 'Сохранить', 'Save')) ?></button>
        </div>
      </form>
    </div>

  </div>
  <div class="col-lg-3">
    <?php admin_sidebar('seo'); ?>
  </div>
</div>
<?php require __DIR__ . '/../../includes/footer.php'; ?>
