<?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', 'SEO для окремих сторінок', 'SEO для отдельных страниц', 'SEO for specific pages');
$seoAdminActive = 'pages';
$editId = (int)($_GET['edit'] ?? 0);
$editRow = $editId > 0 ? seo_admin_get_page($pdo, $editId) : null;

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('pages.php'));
        exit;
    }

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

    try {
        if ($action === 'delete') {
            $old = seo_admin_get_page($pdo, $id) ?? [];
            seo_admin_delete_page($pdo, $id);
            seo_admin_add_log($pdo, $adminUserId, 'seo_page', $id, 'page.delete', $old, []);
            seo_admin_set_flash('success', seo_admin_t('SEO-сторінку видалено.', 'SEO-страница удалена.', 'SEO page deleted.'));
        } else {
            $payload = [
                'page_path'        => (string)($_POST['page_path'] ?? '/'),
                'page_title'       => (string)($_POST['page_title'] ?? ''),
                'meta_description' => (string)($_POST['meta_description'] ?? ''),
                'canonical_url'    => (string)($_POST['canonical_url'] ?? ''),
                'og_title'         => (string)($_POST['og_title'] ?? ''),
                'og_description'   => (string)($_POST['og_description'] ?? ''),
                'og_image'         => (string)($_POST['og_image'] ?? ''),
                'robots_directive' => (string)($_POST['robots_directive'] ?? 'index,follow'),
                'is_active'        => isset($_POST['is_active']) ? 1 : 0,
            ];
            $old = $id > 0 ? (seo_admin_get_page($pdo, $id) ?? []) : [];
            $savedId = seo_admin_save_page($pdo, $payload, $adminUserId, $id);
            seo_admin_add_log($pdo, $adminUserId, 'seo_page', $savedId, $id > 0 ? 'page.update' : 'page.create', $old, $payload);
            seo_admin_set_flash('success', $id > 0 ? seo_admin_t('SEO-сторінку оновлено.', 'SEO-страница обновлена.', 'SEO page updated.') : seo_admin_t('SEO-сторінку створено.', 'SEO-страница создана.', 'SEO page created.'));
        }
    } catch (Throwable $e) {
        seo_admin_set_flash('danger', seo_admin_t('Не вдалося зберегти SEO-сторінку.', 'Не удалось сохранить SEO-страницу.', 'Failed to save SEO page.'));
    }

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

$rows = seo_admin_pages($pdo, 200);

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="row g-3">
      <div class="col-12 col-xl-5">
        <div class="card card-app p-3 h-100">
          <h1 class="h5 mb-3"><?= seo_admin_h($title) ?></h1>
          <form method="post">
            <input type="hidden" name="csrf" value="<?= seo_admin_h(seo_admin_csrf_token_local()) ?>">
            <input type="hidden" name="id" value="<?= (int)($editRow['id'] ?? 0) ?>">

            <div class="mb-3">
              <label class="form-label">URL path</label>
              <input type="text" class="form-control" name="page_path" value="<?= seo_admin_h((string)($editRow['page_path'] ?? '/')) ?>" placeholder="/profile/ або /groups/sitepro">
            </div>
            <div class="mb-3">
              <label class="form-label">Title</label>
              <input type="text" class="form-control" name="page_title" value="<?= seo_admin_h((string)($editRow['page_title'] ?? '')) ?>">
            </div>
            <div class="mb-3">
              <label class="form-label">Meta description</label>
              <textarea class="form-control" rows="3" name="meta_description"><?= seo_admin_h((string)($editRow['meta_description'] ?? '')) ?></textarea>
            </div>
            <div class="mb-3">
              <label class="form-label">Canonical URL</label>
              <input type="text" class="form-control" name="canonical_url" value="<?= seo_admin_h((string)($editRow['canonical_url'] ?? '')) ?>">
            </div>
            <div class="mb-3">
              <label class="form-label">OG title</label>
              <input type="text" class="form-control" name="og_title" value="<?= seo_admin_h((string)($editRow['og_title'] ?? '')) ?>">
            </div>
            <div class="mb-3">
              <label class="form-label">OG description</label>
              <textarea class="form-control" rows="2" name="og_description"><?= seo_admin_h((string)($editRow['og_description'] ?? '')) ?></textarea>
            </div>
            <div class="mb-3">
              <label class="form-label">OG image</label>
              <input type="text" class="form-control" name="og_image" value="<?= seo_admin_h((string)($editRow['og_image'] ?? '')) ?>">
            </div>
            <div class="mb-3">
              <label class="form-label">Robots</label>
              <input type="text" class="form-control" name="robots_directive" value="<?= seo_admin_h((string)($editRow['robots_directive'] ?? 'index,follow')) ?>" placeholder="index,follow або noindex,nofollow">
            </div>
            <div class="mb-3 form-check">
              <input class="form-check-input" type="checkbox" name="is_active" id="seoPageActive" value="1" <?= !isset($editRow['is_active']) || !empty($editRow['is_active']) ? 'checked' : '' ?>>
              <label class="form-check-label" for="seoPageActive"><?= seo_admin_h(seo_admin_t('Активне правило', 'Активное правило', 'Active rule')) ?></label>
            </div>
            <div class="d-flex gap-2 flex-wrap">
              <button class="btn btn-primary" type="submit" name="action" value="save"><?= seo_admin_h($editRow ? seo_admin_t('Оновити', 'Обновить', 'Update') : seo_admin_t('Додати', 'Добавить', 'Add')) ?></button>
              <?php if ($editRow): ?>
                <a class="btn btn-outline-secondary" href="<?= seo_admin_h(seo_admin_url('pages.php')) ?>"><?= seo_admin_h(seo_admin_t('Скасувати редагування', 'Отменить редактирование', 'Cancel editing')) ?></a>
              <?php endif; ?>
            </div>
          </form>
        </div>
      </div>

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

          <?php if (!$rows): ?>
            <div class="text-muted small"><?= seo_admin_h(seo_admin_t('Поки що немає правил для окремих сторінок.', 'Пока нет правил для отдельных страниц.', 'There are no page-specific SEO rules yet.')) ?></div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm align-middle mb-0">
                <thead>
                  <tr>
                    <th>Path</th>
                    <th>Title</th>
                    <th><?= seo_admin_h(seo_admin_t('Статус', 'Статус', 'Status')) ?></th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $row): ?>
                  <tr>
                    <td><code><?= seo_admin_h((string)($row['page_path'] ?? '')) ?></code></td>
                    <td><?= seo_admin_h((string)($row['page_title'] ?? '')) ?></td>
                    <td><?= !empty($row['is_active']) ? '<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="<?= seo_admin_h(seo_admin_url('pages.php', ['edit' => (int)$row['id']])) ?>"><?= seo_admin_h(seo_admin_t('Редагувати', 'Редактировать', 'Edit')) ?></a>
                      <form method="post" class="d-inline" onsubmit="return confirm('<?= seo_admin_h(seo_admin_t('Видалити це правило?', 'Удалить это правило?', 'Delete this rule?')) ?>');">
                        <input type="hidden" name="csrf" value="<?= seo_admin_h(seo_admin_csrf_token_local()) ?>">
                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger" type="submit" name="action" value="delete"><?= seo_admin_h(seo_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('seo'); ?>
  </div>
</div>
<?php require __DIR__ . '/../../includes/footer.php'; ?>
