<?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', '301 редіректи', '301 редиректы', '301 redirects');
$seoAdminActive = 'redirects';
$editId = (int)($_GET['edit'] ?? 0);
$editRow = $editId > 0 ? seo_admin_get_redirect($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('redirects.php'));
        exit;
    }

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

    try {
        if ($action === 'delete') {
            $old = seo_admin_get_redirect($pdo, $id) ?? [];
            seo_admin_delete_redirect($pdo, $id);
            seo_admin_add_log($pdo, $adminUserId, 'redirect', $id, 'redirect.delete', $old, []);
            seo_admin_set_flash('success', seo_admin_t('Редірект видалено.', 'Редирект удален.', 'Redirect deleted.'));
        } else {
            $payload = [
                'old_path'   => (string)($_POST['old_path'] ?? '/'),
                'target_url' => (string)($_POST['target_url'] ?? ''),
                'http_code'  => (int)($_POST['http_code'] ?? 301),
                'note'       => (string)($_POST['note'] ?? ''),
                'is_active'  => isset($_POST['is_active']) ? 1 : 0,
            ];
            $old = $id > 0 ? (seo_admin_get_redirect($pdo, $id) ?? []) : [];
            $savedId = seo_admin_save_redirect($pdo, $payload, $adminUserId, $id);
            seo_admin_add_log($pdo, $adminUserId, 'redirect', $savedId, $id > 0 ? 'redirect.update' : 'redirect.create', $old, $payload);
            seo_admin_set_flash('success', $id > 0 ? seo_admin_t('Редірект оновлено.', 'Редирект обновлен.', 'Redirect updated.') : seo_admin_t('Редірект створено.', 'Редирект создан.', 'Redirect created.'));
        }
    } catch (Throwable $e) {
        seo_admin_set_flash('danger', $e->getMessage() !== '' ? $e->getMessage() : seo_admin_t('Не вдалося зберегти редірект.', 'Не удалось сохранить редирект.', 'Failed to save redirect.'));
    }

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

$rows = seo_admin_redirects($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"><?= seo_admin_h(seo_admin_t('Старий шлях', 'Старый путь', 'Old path')) ?></label>
              <input type="text" class="form-control" name="old_path" value="<?= seo_admin_h((string)($editRow['old_path'] ?? '/old-path')) ?>" placeholder="/old-url">
            </div>
            <div class="mb-3">
              <label class="form-label"><?= seo_admin_h(seo_admin_t('Новий URL', 'Новый URL', 'New URL')) ?></label>
              <input type="text" class="form-control" name="target_url" value="<?= seo_admin_h((string)($editRow['target_url'] ?? '')) ?>" placeholder="/new-url або https://...">
            </div>
            <div class="mb-3">
              <label class="form-label">HTTP</label>
              <select class="form-select" name="http_code">
                <?php $curCode = (int)($editRow['http_code'] ?? 301); ?>
                <option value="301" <?= $curCode === 301 ? 'selected' : '' ?>>301</option>
                <option value="302" <?= $curCode === 302 ? 'selected' : '' ?>>302</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label"><?= seo_admin_h(seo_admin_t('Коментар', 'Комментарий', 'Note')) ?></label>
              <textarea class="form-control" rows="3" name="note"><?= seo_admin_h((string)($editRow['note'] ?? '')) ?></textarea>
            </div>
            <div class="mb-3 form-check">
              <input class="form-check-input" type="checkbox" name="is_active" id="seoRedirectActive" value="1" <?= !isset($editRow['is_active']) || !empty($editRow['is_active']) ? 'checked' : '' ?>>
              <label class="form-check-label" for="seoRedirectActive"><?= seo_admin_h(seo_admin_t('Активний редірект', 'Активный редирект', 'Active redirect')) ?></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('redirects.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('Список редіректів', 'Список редиректов', 'Redirect 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 redirects yet.')) ?></div>
          <?php else: ?>
            <div class="table-responsive">
              <table class="table table-sm align-middle mb-0">
                <thead>
                  <tr>
                    <th><?= seo_admin_h(seo_admin_t('Звідки', 'Откуда', 'From')) ?></th>
                    <th><?= seo_admin_h(seo_admin_t('Куди', 'Куда', 'To')) ?></th>
                    <th>HTTP</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $row): ?>
                  <tr>
                    <td>
                      <code><?= seo_admin_h((string)($row['old_path'] ?? '')) ?></code>
                      <div class="small text-muted"><?= !empty($row['is_active']) ? 'ON' : 'OFF' ?> · hits: <?= (int)($row['hit_count'] ?? 0) ?></div>
                    </td>
                    <td class="text-break"><?= seo_admin_h((string)($row['target_url'] ?? '')) ?></td>
                    <td><?= (int)($row['http_code'] ?? 301) ?></td>
                    <td class="text-nowrap">
                      <a class="btn btn-sm btn-outline-primary" href="<?= seo_admin_h(seo_admin_url('redirects.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 redirect?')) ?>');">
                        <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'; ?>
