<?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__ . '/../../functional/pages/_lib.php';

if (!function_exists('site_pages_admin_h')) {
    function site_pages_admin_h(?string $value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('site_pages_admin_t')) {
    function site_pages_admin_t(string $uk, string $ru, string $en): string
    {
        $lang = function_exists('lang') ? (string)lang() : (string)($_SESSION['lang'] ?? 'uk');
        return match ($lang) {
            'ru' => $ru,
            'en' => $en,
            default => $uk,
        };
    }
}

if (!function_exists('site_pages_admin_flash_set')) {
    function site_pages_admin_flash_set(string $type, string $message): void
    {
        $_SESSION['site_pages_admin_flash'] = [
            'type' => $type,
            'message' => $message,
        ];
    }
}

if (!function_exists('site_pages_admin_flash_get')) {
    function site_pages_admin_flash_get(): ?array
    {
        $flash = $_SESSION['site_pages_admin_flash'] ?? null;
        unset($_SESSION['site_pages_admin_flash']);
        return is_array($flash) ? $flash : null;
    }
}

if (!function_exists('site_pages_admin_csrf_token')) {
    function site_pages_admin_csrf_token(): string
    {
        if (function_exists('csrf_token')) {
            return (string)csrf_token();
        }

        if (empty($_SESSION['site_pages_admin_csrf'])) {
            $_SESSION['site_pages_admin_csrf'] = bin2hex(random_bytes(32));
        }

        return (string)$_SESSION['site_pages_admin_csrf'];
    }
}

if (!function_exists('site_pages_admin_csrf_check')) {
    function site_pages_admin_csrf_check(?string $token): bool
    {
        $token = (string)$token;

        if (function_exists('csrf_check')) {
            return (bool)csrf_check($token);
        }

        $sessionToken = (string)($_SESSION['site_pages_admin_csrf'] ?? '');
        return $sessionToken !== '' && hash_equals($sessionToken, $token);
    }
}

$pdo = vm_site_pages_db();
$me = function_exists('current_user') ? current_user() : null;
$adminUserId = (int)($me['id'] ?? 0);
$tableReady = vm_site_pages_table_exists($pdo);

$title = site_pages_admin_t('Текстові сторінки', 'Текстовые страницы', 'Text pages');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!site_pages_admin_csrf_check((string)($_POST['csrf'] ?? ''))) {
        site_pages_admin_flash_set('danger', site_pages_admin_t('Помилка CSRF.', 'Ошибка CSRF.', 'CSRF error.'));
        header('Location: /admin/pages/');
        exit;
    }

    if (!$tableReady) {
        site_pages_admin_flash_set(
            'danger',
            site_pages_admin_t(
                'Таблиця site_pages ще не створена. Спочатку виконай SQL.',
                'Таблица site_pages ещё не создана. Сначала выполни SQL.',
                'The site_pages table does not exist yet. Run the SQL first.'
            )
        );
        header('Location: /admin/pages/');
        exit;
    }

    $action = (string)($_POST['action'] ?? 'save');
    $id = (int)($_POST['id'] ?? 0);

    try {
        if ($action === 'delete') {
            vm_site_pages_delete($pdo, $id);
            site_pages_admin_flash_set(
                'success',
                site_pages_admin_t('Сторінку видалено.', 'Страница удалена.', 'Page deleted.')
            );
        } else {
            $payload = [
                'slug' => (string)($_POST['slug'] ?? ''),
                'title_uk' => (string)($_POST['title_uk'] ?? ''),
                'title_ru' => (string)($_POST['title_ru'] ?? ''),
                'title_en' => (string)($_POST['title_en'] ?? ''),
                'body_uk' => (string)($_POST['body_uk'] ?? ''),
                'body_ru' => (string)($_POST['body_ru'] ?? ''),
                'body_en' => (string)($_POST['body_en'] ?? ''),
                'show_in_footer' => isset($_POST['show_in_footer']) ? 1 : 0,
                'sort_order' => (int)($_POST['sort_order'] ?? 100),
                'is_active' => isset($_POST['is_active']) ? 1 : 0,
            ];

            $savedId = vm_site_pages_save($pdo, $payload, $adminUserId, $id);

            site_pages_admin_flash_set(
                'success',
                $id > 0
                    ? site_pages_admin_t('Сторінку оновлено.', 'Страница обновлена.', 'Page updated.')
                    : site_pages_admin_t('Сторінку створено.', 'Страница создана.', 'Page created.')
            );

            header('Location: /admin/pages/?edit=' . $savedId);
            exit;
        }
    } catch (Throwable $e) {
        site_pages_admin_flash_set(
            'danger',
            site_pages_admin_t(
                'Не вдалося зберегти сторінку: ',
                'Не удалось сохранить страницу: ',
                'Failed to save page: '
            ) . $e->getMessage()
        );
    }

    header('Location: /admin/pages/');
    exit;
}

$editId = (int)($_GET['edit'] ?? 0);
$editRow = ($tableReady && $editId > 0) ? vm_site_pages_find_by_id($pdo, $editId) : null;
$rows = $tableReady ? vm_site_pages_list_all($pdo) : [];
$flash = site_pages_admin_flash_get();

require __DIR__ . '/../../includes/header.php';
?>
<div class="row g-3">
  <div class="col-lg-9">
    <?php if ($flash): ?>
      <div class="alert alert-<?= site_pages_admin_h((string)($flash['type'] ?? 'info')) ?>">
        <?= site_pages_admin_h((string)($flash['message'] ?? '')) ?>
      </div>
    <?php endif; ?>

    <?php if (!$tableReady): ?>
      <div class="alert alert-warning">
        <?= site_pages_admin_h(site_pages_admin_t(
            'Таблиця site_pages ще не створена. Спочатку виконай SQL із повідомлення.',
            'Таблица site_pages ещё не создана. Сначала выполни SQL из сообщения.',
            'The site_pages table does not exist yet. Run the SQL from the message first.'
        )) ?>
      </div>
    <?php endif; ?>

    <div class="row g-3">
      <div class="col-12 col-xl-6">
        <div class="card card-app p-3 h-100">
          <div class="d-flex align-items-center justify-content-between gap-2 mb-3">
            <h1 class="h5 mb-0"><?= site_pages_admin_h($title) ?></h1>
            <?php if ($editRow): ?>
              <a
                class="btn btn-sm btn-outline-primary"
                target="_blank"
                rel="noopener"
                href="/functional/pages/view.php?slug=<?= rawurlencode((string)($editRow['slug'] ?? '')) ?>"
              >
                <?= site_pages_admin_h(site_pages_admin_t('Відкрити', 'Открыть', 'Open')) ?>
              </a>
            <?php endif; ?>
          </div>

          <form method="post">
            <input type="hidden" name="csrf" value="<?= site_pages_admin_h(site_pages_admin_csrf_token()) ?>">
            <input type="hidden" name="id" value="<?= (int)($editRow['id'] ?? 0) ?>">

            <div class="mb-3">
              <label class="form-label"><?= site_pages_admin_h(site_pages_admin_t('Slug', 'Slug', 'Slug')) ?></label>
              <input
                type="text"
                class="form-control"
                name="slug"
                value="<?= site_pages_admin_h((string)($editRow['slug'] ?? '')) ?>"
                placeholder="rules-vmeregi"
              >
              <div class="form-text">
                <?= site_pages_admin_h(site_pages_admin_t(
                    'Лише латиниця, цифри та дефіс.',
                    'Только латиница, цифры и дефис.',
                    'Latin letters, numbers and hyphen only.'
                )) ?>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Українська — <?= site_pages_admin_h(site_pages_admin_t('назва', 'название', 'title')) ?></label>
              <input type="text" class="form-control" name="title_uk" value="<?= site_pages_admin_h((string)($editRow['title_uk'] ?? '')) ?>">
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Русский — <?= site_pages_admin_h(site_pages_admin_t('назва', 'название', 'title')) ?></label>
              <input type="text" class="form-control" name="title_ru" value="<?= site_pages_admin_h((string)($editRow['title_ru'] ?? '')) ?>">
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">English — <?= site_pages_admin_h(site_pages_admin_t('назва', 'название', 'title')) ?></label>
              <input type="text" class="form-control" name="title_en" value="<?= site_pages_admin_h((string)($editRow['title_en'] ?? '')) ?>">
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Українська — <?= site_pages_admin_h(site_pages_admin_t('текст', 'текст', 'text')) ?></label>
              <textarea class="form-control" rows="8" name="body_uk"><?= site_pages_admin_h((string)($editRow['body_uk'] ?? '')) ?></textarea>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Русский — <?= site_pages_admin_h(site_pages_admin_t('текст', 'текст', 'text')) ?></label>
              <textarea class="form-control" rows="8" name="body_ru"><?= site_pages_admin_h((string)($editRow['body_ru'] ?? '')) ?></textarea>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">English — <?= site_pages_admin_h(site_pages_admin_t('текст', 'текст', 'text')) ?></label>
              <textarea class="form-control" rows="8" name="body_en"><?= site_pages_admin_h((string)($editRow['body_en'] ?? '')) ?></textarea>
            </div>

            <div class="row g-3">
              <div class="col-sm-4">
                <label class="form-label"><?= site_pages_admin_h(site_pages_admin_t('Порядок', 'Порядок', 'Sort order')) ?></label>
                <input
                  type="number"
                  class="form-control"
                  name="sort_order"
                  min="0"
                  value="<?= (int)($editRow['sort_order'] ?? 100) ?>"
                >
              </div>

              <div class="col-sm-8 d-flex flex-column justify-content-end">
                <div class="form-check mb-2">
                  <input
                    class="form-check-input"
                    type="checkbox"
                    name="show_in_footer"
                    id="showInFooter"
                    value="1"
                    <?= !isset($editRow['show_in_footer']) || !empty($editRow['show_in_footer']) ? 'checked' : '' ?>
                  >
                  <label class="form-check-label" for="showInFooter">
                    <?= site_pages_admin_h(site_pages_admin_t(
                        'Показувати у футері',
                        'Показывать в футере',
                        'Show in footer'
                    )) ?>
                  </label>
                </div>

                <div class="form-check">
                  <input
                    class="form-check-input"
                    type="checkbox"
                    name="is_active"
                    id="isActivePage"
                    value="1"
                    <?= !isset($editRow['is_active']) || !empty($editRow['is_active']) ? 'checked' : '' ?>
                  >
                  <label class="form-check-label" for="isActivePage">
                    <?= site_pages_admin_h(site_pages_admin_t(
                        'Активна сторінка',
                        'Активная страница',
                        'Active page'
                    )) ?>
                  </label>
                </div>
              </div>
            </div>

            <div class="d-flex gap-2 flex-wrap mt-4">
              <button class="btn btn-primary" type="submit" name="action" value="save">
                <?= site_pages_admin_h($editRow
                    ? site_pages_admin_t('Оновити', 'Обновить', 'Update')
                    : site_pages_admin_t('Створити', 'Создать', 'Create')) ?>
              </button>

              <?php if ($editRow): ?>
                <a class="btn btn-outline-secondary" href="/admin/pages/">
                  <?= site_pages_admin_h(site_pages_admin_t('Нова сторінка', 'Новая страница', 'New page')) ?>
                </a>
              <?php endif; ?>
            </div>
          </form>
        </div>
      </div>

      <div class="col-12 col-xl-6">
        <div class="card card-app p-3 h-100">
          <div class="d-flex align-items-center justify-content-between gap-2 mb-3">
            <div class="fw-semibold">
              <?= site_pages_admin_h(site_pages_admin_t('Список сторінок', 'Список страниц', 'Pages list')) ?>
            </div>
            <div class="text-muted small"><?= count($rows) ?></div>
          </div>

          <?php if (!$rows): ?>
            <div class="text-muted small">
              <?= site_pages_admin_h(site_pages_admin_t(
                  'Поки що сторінок немає.',
                  'Пока страниц нет.',
                  'There are no pages yet.'
              )) ?>
            </div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm align-middle mb-0">
                <thead>
                  <tr>
                    <th><?= site_pages_admin_h(site_pages_admin_t('Slug', 'Slug', 'Slug')) ?></th>
                    <th><?= site_pages_admin_h(site_pages_admin_t('Назва', 'Название', 'Title')) ?></th>
                    <th><?= site_pages_admin_h(site_pages_admin_t('Статус', 'Статус', 'Status')) ?></th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $row): ?>
                  <?php
                  $rowTitle = vm_site_pages_row_title($row);
                  $isFooter = !empty($row['show_in_footer']);
                  $isActive = !empty($row['is_active']);
                  ?>
                  <tr>
                    <td>
                      <code><?= site_pages_admin_h((string)($row['slug'] ?? '')) ?></code>
                    </td>
                    <td>
                      <div><?= site_pages_admin_h($rowTitle) ?></div>
                      <div class="small text-muted">
                        <?= $isFooter
                            ? site_pages_admin_h(site_pages_admin_t('Є у футері', 'Есть в футере', 'In footer'))
                            : site_pages_admin_h(site_pages_admin_t('Не у футері', 'Не в футере', 'Not in footer')) ?>
                      </div>
                    </td>
                    <td>
                      <?= $isActive
                          ? '<span class="badge bg-success">ON</span>'
                          : '<span class="badge bg-secondary">OFF</span>' ?>
                    </td>
                    <td class="text-nowrap">
                      <a class="btn btn-sm btn-outline-primary" href="/admin/pages/?edit=<?= (int)$row['id'] ?>">
                        <?= site_pages_admin_h(site_pages_admin_t('Редагувати', 'Редактировать', 'Edit')) ?>
                      </a>

                      <form method="post" class="d-inline" onsubmit="return confirm('<?= site_pages_admin_h(site_pages_admin_t(
                          'Видалити цю сторінку?',
                          'Удалить эту страницу?',
                          'Delete this page?'
                      )) ?>');">
                        <input type="hidden" name="csrf" value="<?= site_pages_admin_h(site_pages_admin_csrf_token()) ?>">
                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger" type="submit" name="action" value="delete">
                          <?= site_pages_admin_h(site_pages_admin_t('Видалити', 'Удалить', 'Delete')) ?>
                        </button>
                      </form>
                    </td>
                  </tr>
                <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

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