<?php
declare(strict_types=1);

/**
 * /admin/users/index.php
 * Адмін: список користувачів + дії
 *
 * Оновлено:
 * - пошук по нікнейму та email
 * - окрема колонка/блок кількості постів
 * - окрема колонка/блок VM Coins
 * - показ антиспам-статусу та причини
 * - ручна кнопка: позначити бота / зняти мітку
 * - мобільні картки з компактним layout
 */

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

require_once __DIR__ . '/../_helpers.php';
require_once __DIR__ . '/../_sidebar.php';
require_once __DIR__ . '/../_csrf.php';
require_once __DIR__ . '/../../includes/security_antispam.php';

$pdo = db();

if (!function_exists('e')) {
    function e($v): string {
        if ($v === null) return '';
        if (is_array($v)) {
            $v = json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        } elseif (is_object($v)) {
            $v = method_exists($v, '__toString') ? (string)$v : json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        } else {
            $v = (string)$v;
        }
        if ($v === false) $v = '';
        return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('db_has_column')) {
    function db_has_column(PDO $pdo, string $table, string $col): bool {
        try {
            $st = $pdo->prepare('SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ? LIMIT 1');
            $st->execute([$table, $col]);
            return (bool)$st->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('admin_users_split_datetime')) {
    function admin_users_split_datetime(?string $value): array
    {
        $raw = trim((string)$value);
        if ($raw === '') {
            return ['', ''];
        }
        $ts = strtotime($raw);
        if ($ts === false) {
            return [$raw, ''];
        }
        return [date('Y-m-d', $ts), date('H:i:s', $ts)];
    }
}

if (!function_exists('admin_users_antispam_badge')) {
    function admin_users_antispam_badge(?string $status): string
    {
        return match ($status) {
            'bot' => 'text-bg-danger',
            'suspect' => 'text-bg-warning',
            default => 'text-bg-success',
        };
    }
}

$title = admin_tt('users', 'Користувачі', 'Пользователи', 'Users');
$meta_robots = 'noindex, nofollow, noarchive, nosnippet';
$meta_desc   = '';
$canonical   = function_exists('abs_url') ? abs_url('/admin/users/') : '/admin/users/';

if (!headers_sent()) {
    header('X-Robots-Tag: noindex, nofollow, noarchive, nosnippet', true);
}

$flash = admin_flash_take();
$hasUsers = admin_table_exists($pdo, 'users');
$activeCol = null;
$tokenCol  = null;

if ($hasUsers) {
    if (function_exists('admin_user_activation_fields')) {
        $fields = (array)admin_user_activation_fields($pdo);
        $activeCol = $fields['active_col'] ?? null;
        $tokenCol  = $fields['token_col'] ?? null;
    }
    if (!$activeCol && db_has_column($pdo, 'users', 'is_active')) {
        $activeCol = 'is_active';
    }
    if (!$tokenCol) {
        foreach (['activation_token_hash','activation_token','verify_token','verification_token','email_token','token'] as $c) {
            if (db_has_column($pdo, 'users', $c)) {
                $tokenCol = $c;
                break;
            }
        }
    }
}

$hasVmBalance = $hasUsers && db_has_column($pdo, 'users', 'vm_coins_balance');
$hasPosts = admin_table_exists($pdo, 'posts');
$hasFlags = antispam_flags_has_table($pdo);

$status = isset($_GET['status']) ? trim((string)$_GET['status']) : 'all';
if (!in_array($status, ['all', 'active', 'inactive'], true)) {
    $status = 'all';
}

$antispam = isset($_GET['antispam']) ? trim((string)$_GET['antispam']) : 'all';
if (!in_array($antispam, ['all', 'clean', 'suspect', 'bot'], true)) {
    $antispam = 'all';
}

$sort = isset($_GET['sort']) ? trim((string)$_GET['sort']) : 'desc';
if (!in_array($sort, ['asc', 'desc'], true)) {
    $sort = 'desc';
}

$q = trim((string)($_GET['q'] ?? ''));
if (mb_strlen($q, 'UTF-8') > 190) {
    $q = mb_substr($q, 0, 190, 'UTF-8');
}

$baseUrl = '/admin/users/';
$qsKeep = [
    'q'        => $q,
    'status'   => $status,
    'antispam' => $antispam,
    'sort'     => $sort,
];

$build_url = function(array $overrides = []) use ($baseUrl, $qsKeep): string {
    $qv = $qsKeep;
    foreach ($overrides as $k => $v) {
        if ($v === null) {
            unset($qv[$k]);
        } else {
            $qv[$k] = (string)$v;
        }
    }
    if (($qv['status'] ?? '') === 'all') unset($qv['status']);
    if (($qv['antispam'] ?? '') === 'all') unset($qv['antispam']);
    if (($qv['q'] ?? '') === '') unset($qv['q']);
    $str = http_build_query($qv);
    return $str ? ($baseUrl . '?' . $str) : $baseUrl;
};

$selfUrl = $build_url([]);
$selfUrlEnc = urlencode($selfUrl);

$users = [];
try {
    $selectCols = [
        'u.id',
        'u.email',
        'u.username',
        'u.role',
        'u.created_at',
    ];
    if ($activeCol) $selectCols[] = "u.`$activeCol` AS is_active";
    if ($tokenCol)  $selectCols[] = "u.`$tokenCol` AS act_token";
    if ($hasVmBalance) $selectCols[] = 'u.vm_coins_balance';
    if ($hasPosts) $selectCols[] = 'COALESCE(pcnt.post_count, 0) AS posts_count';
    if ($hasFlags) {
        $selectCols[] = 'saf.status AS antispam_status';
        $selectCols[] = 'saf.reason_text AS antispam_reason';
        $selectCols[] = 'saf.reason_code AS antispam_code';
        $selectCols[] = 'saf.last_detected_at AS antispam_at';
        $selectCols[] = 'saf.is_manual AS antispam_manual';
    }

    $joins = [];
    if ($hasPosts) {
        $joins[] = 'LEFT JOIN (SELECT user_id, COUNT(*) AS post_count FROM posts GROUP BY user_id) pcnt ON pcnt.user_id = u.id';
    }
    if ($hasFlags) {
        $joins[] = 'LEFT JOIN security_antispam_flags saf ON saf.user_id = u.id';
    }

    $where = [];
    $params = [];
    if ($activeCol && $status !== 'all') {
        $where[] = $status === 'active' ? "u.`$activeCol` = 1" : "u.`$activeCol` = 0";
    }
    if ($q !== '') {
        $where[] = '(u.username LIKE ? OR u.email LIKE ?)';
        $params[] = '%' . $q . '%';
        $params[] = '%' . $q . '%';
    }
    if ($hasFlags && $antispam !== 'all') {
        if ($antispam === 'clean') {
            $where[] = '(saf.user_id IS NULL OR saf.status IS NULL OR saf.status = "")';
        } else {
            $where[] = 'saf.status = ?';
            $params[] = $antispam;
        }
    }

    $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
    $orderSql = "ORDER BY u.created_at " . strtoupper($sort) . ', u.id ' . strtoupper($sort);
    $sql = 'SELECT ' . implode(",\n", $selectCols) . "\nFROM users u\n" . implode("\n", $joins) . "\n$whereSql\n$orderSql\nLIMIT 200";

    $st = $pdo->prepare($sql);
    $st->execute($params);
    $users = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $users = [];
}

$colspan = 8;
require __DIR__ . '/../../includes/header.php';
?>

<style>
  .admin-users-card{border:1px solid rgba(15,23,42,.08);border-radius:18px;box-shadow:0 8px 24px rgba(15,23,42,.05);overflow:hidden;background:#fff}
  .admin-users-filters{border:1px solid rgba(15,23,42,.08);border-radius:18px;box-shadow:0 8px 24px rgba(15,23,42,.04);background:#fff}
  .admin-users-table-wrap{display:block}
  .admin-users-mobile-list{display:none}
  .admin-users-table{width:100%;table-layout:auto;margin-bottom:0}
  .admin-users-table thead th{font-size:.95rem;font-weight:700;color:#0f172a;border-bottom:1px solid rgba(15,23,42,.10);white-space:nowrap;background:#fff;vertical-align:middle;padding:.72rem .5rem;text-align:center}
  .admin-users-table tbody td{vertical-align:middle;border-color:rgba(15,23,42,.08);padding:.8rem .5rem}
  .admin-users-col-id{width:72px}.admin-users-col-posts{width:95px}.admin-users-col-coins{width:110px}.admin-users-col-anti{width:180px}.admin-users-col-created{width:118px}.admin-users-col-actions{width:132px}
  .admin-users-id{font-weight:700;font-size:1rem;color:#0f172a;white-space:nowrap}
  .admin-users-identity-main{font-size:1rem;font-weight:700;color:#0f172a;line-height:1.18;word-break:break-word;overflow-wrap:anywhere}
  .admin-users-identity-email{font-size:.9rem;color:#64748b;line-height:1.22;margin-top:.22rem;word-break:break-word;overflow-wrap:anywhere}
  .admin-users-meta-box{display:flex;flex-direction:column;gap:.48rem}
  .admin-users-meta-item{display:flex;flex-direction:column;gap:.14rem;line-height:1.12}
  .admin-users-meta-label{font-size:.72rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em;color:#64748b;white-space:nowrap}
  .admin-users-meta .badge,.admin-users-antispam .badge{font-size:.82rem;padding:.35rem .56rem;border-radius:10px;white-space:nowrap}
  .admin-users-number{text-align:center;white-space:nowrap}
  .admin-users-number-value{display:inline-block;font-weight:800;font-size:1.05rem;color:#0f172a;line-height:1.1}
  .admin-users-created-date{display:block;font-weight:700;font-size:1rem;color:#0f172a;line-height:1.08;text-align:left}
  .admin-users-created-time{display:block;font-size:.82rem;color:#64748b;line-height:1.08;margin-top:.16rem;text-align:left}
  .admin-users-antispam-reason{display:block;font-size:.82rem;color:#64748b;line-height:1.22;margin-top:.3rem;word-break:break-word;overflow-wrap:anywhere}
  .admin-users-actions{text-align:right}
  .admin-users-actions-stack{display:inline-flex;flex-direction:column;align-items:stretch;gap:.35rem;width:120px;max-width:120px}
  .admin-users-actions-stack .btn{width:100%;white-space:normal;word-break:break-word;border-radius:12px;padding:.38rem .32rem;font-size:.9rem;line-height:1.08}
  .admin-users-empty{padding:1rem .75rem !important}
  @media (max-width:767.98px){
    .admin-users-table-wrap{display:none}
    .admin-users-mobile-list{display:block;padding:.8rem;background:#fff}
    .admin-users-mobile-card{border:1px solid rgba(15,23,42,.08);border-radius:18px;padding:14px;background:#fff;box-shadow:0 6px 20px rgba(15,23,42,.04)}
    .admin-users-mobile-card + .admin-users-mobile-card{margin-top:12px}
    .admin-users-mobile-top{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;margin-bottom:10px}
    .admin-users-mobile-id{flex:0 0 auto;min-width:54px;text-align:center;border:1px solid rgba(15,23,42,.08);border-radius:14px;padding:8px 10px;background:#f8fafc}
    .admin-users-mobile-id-label{display:block;font-size:.68rem;font-weight:700;text-transform:uppercase;color:#64748b;letter-spacing:.03em;line-height:1.1}
    .admin-users-mobile-id-value{display:block;margin-top:4px;font-size:1.1rem;font-weight:800;color:#0f172a;line-height:1.1}
    .admin-users-mobile-identity{flex:1 1 auto;min-width:0}
    .admin-users-mobile-name{font-size:1.02rem;font-weight:800;color:#0f172a;line-height:1.2;word-break:break-word;overflow-wrap:anywhere}
    .admin-users-mobile-email{margin-top:5px;font-size:.92rem;color:#64748b;line-height:1.3;word-break:break-word;overflow-wrap:anywhere}
    .admin-users-mobile-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:10px}
    .admin-users-mobile-box{border:1px solid rgba(15,23,42,.07);border-radius:14px;background:#f8fafc;padding:10px 11px;min-width:0}
    .admin-users-mobile-box-full{grid-column:1 / -1}
    .admin-users-mobile-label{display:block;font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em;color:#64748b;margin-bottom:6px;line-height:1.1}
    .admin-users-mobile-value{color:#0f172a;font-size:.98rem;font-weight:700;line-height:1.25;word-break:break-word;overflow-wrap:anywhere}
    .admin-users-mobile-actions{margin-top:12px;display:flex;flex-direction:column;gap:8px}
    .admin-users-mobile-actions .btn{width:100%;border-radius:14px;padding:.55rem .6rem;font-size:.95rem;line-height:1.15}
    .admin-users-mobile-actions form{margin:0}
  }
</style>

<div class="row g-3">
  <div class="col-lg-9">

    <div class="d-flex align-items-center justify-content-between mb-2">
      <h1 class="h4 mb-0"><?= e(admin_tt('users', 'Користувачі', 'Пользователи', 'Users')) ?></h1>
      <a class="btn btn-sm btn-outline-secondary" href="/admin/"><?= e(admin_tt('admin_dashboard', 'Дашборд', 'Дашборд', 'Dashboard')) ?></a>
    </div>

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

    <div class="card card-app p-3 mb-3 admin-users-filters">
      <form method="get" action="/admin/users/" class="row g-2 align-items-end">
        <div class="col-md-4">
          <label class="form-label small mb-1">Пошук</label>
          <input type="text" name="q" class="form-control form-control-sm" value="<?= e($q) ?>" placeholder="email або @username">
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1"><?= e(admin_tt('filter_status', 'Статус', 'Статус', 'Status')) ?></label>
          <select name="status" class="form-select form-select-sm" <?= $activeCol ? '' : 'disabled' ?>>
            <option value="all" <?= $status === 'all' ? 'selected' : '' ?>><?= e(admin_tt('filter_all', 'Всі', 'Все', 'All')) ?></option>
            <option value="active" <?= $status === 'active' ? 'selected' : '' ?>><?= e(admin_tt('active_list', 'Активовані', 'Активированные', 'Active')) ?></option>
            <option value="inactive" <?= $status === 'inactive' ? 'selected' : '' ?>><?= e(admin_tt('inactive_list', 'Не активовані', 'Не активированы', 'Inactive')) ?></option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1">Антиспам</label>
          <select name="antispam" class="form-select form-select-sm" <?= $hasFlags ? '' : 'disabled' ?>>
            <option value="all" <?= $antispam === 'all' ? 'selected' : '' ?>>Всі</option>
            <option value="clean" <?= $antispam === 'clean' ? 'selected' : '' ?>>Чисті</option>
            <option value="suspect" <?= $antispam === 'suspect' ? 'selected' : '' ?>>Підозрілі</option>
            <option value="bot" <?= $antispam === 'bot' ? 'selected' : '' ?>>Боти</option>
          </select>
        </div>
        <div class="col-md-2">
          <label class="form-label small mb-1"><?= e(admin_tt('sort_created', 'Сортування', 'Сортировка', 'Sort')) ?></label>
          <select name="sort" class="form-select form-select-sm">
            <option value="desc" <?= $sort === 'desc' ? 'selected' : '' ?>><?= e(admin_tt('sort_new', 'Спочатку нові', 'Сначала новые', 'Newest first')) ?></option>
            <option value="asc" <?= $sort === 'asc' ? 'selected' : '' ?>><?= e(admin_tt('sort_old', 'Спочатку старі', 'Сначала старые', 'Oldest first')) ?></option>
          </select>
        </div>
        <div class="col-md-2 d-grid">
          <button class="btn btn-sm btn-primary"><?= e(admin_tt('apply', 'Застосувати', 'Применить', 'Apply')) ?></button>
        </div>
      </form>
    </div>

    <div class="card card-app p-0 admin-users-card">
      <div class="table-responsive admin-users-table-wrap">
        <table class="table table-sm align-middle admin-users-table">
          <colgroup>
            <col class="admin-users-col-id"><col><col class="admin-users-col-posts"><col class="admin-users-col-coins"><col class="admin-users-col-anti"><col class="admin-users-col-created"><col class="admin-users-col-actions">
          </colgroup>
          <thead>
            <tr>
              <th>ID</th>
              <th><?= e(admin_tt('username_email', 'Нікнейм / Email', 'Никнейм / Email', 'Username / Email')) ?></th>
              <th>Пости</th>
              <th><?= e(admin_tt('vm_coins', 'VM Coins', 'VM Coins', 'VM Coins')) ?></th>
              <th>Антиспам</th>
              <th><?= e(admin_tt('created', 'Створено', 'Создан', 'Created')) ?></th>
              <th><?= e(admin_tt('admin_actions', 'Дії', 'Действия', 'Actions')) ?></th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$users): ?>
              <tr><td colspan="<?= (int)$colspan ?>" class="text-muted small admin-users-empty"><?= e(admin_tt('admin_no_data', 'Немає даних', 'Нет данных', 'No data')) ?></td></tr>
            <?php else: ?>
              <?php foreach ($users as $u): ?>
                <?php
                  $uid = (int)($u['id'] ?? 0);
                  $isActive = $activeCol ? (int)($u['is_active'] ?? 0) : null;
                  $hasToken = $tokenCol ? (trim((string)($u['act_token'] ?? '')) !== '') : false;
                  $balance = $hasVmBalance ? (int)($u['vm_coins_balance'] ?? 0) : 0;
                  $postsCount = $hasPosts ? (int)($u['posts_count'] ?? 0) : 0;
                  $antiStatus = trim((string)($u['antispam_status'] ?? ''));
                  $antiReason = trim((string)($u['antispam_reason'] ?? ''));
                  [$createdDate, $createdTime] = admin_users_split_datetime((string)($u['created_at'] ?? ''));
                  $username = trim((string)($u['username'] ?? ''));
                  $email = trim((string)($u['email'] ?? ''));
                  $coinsQuickLink = '/admin/coins/adjust.php?user_q=' . rawurlencode($username !== '' ? $username : (string)$uid) . '#manual-adjust';
                  $antiBadge = admin_users_antispam_badge($antiStatus === '' ? 'clean' : $antiStatus);
                  $antiLabel = $antiStatus === 'bot' ? 'Бот' : ($antiStatus === 'suspect' ? 'Підозрілий' : 'Чисто');
                ?>
                <tr>
                  <td class="admin-users-id"><?= $uid ?></td>
                  <td>
                    <div class="admin-users-identity-main">@<?= e($username) ?></div>
                    <div class="admin-users-identity-email"><?= e($email) ?></div>
                    <div class="admin-users-meta-box mt-2">
                      <div class="admin-users-meta-item">
                        <span class="admin-users-meta-label">Роль</span>
                        <div><span class="badge text-bg-secondary"><?= e((string)($u['role'] ?? '')) ?></span></div>
                      </div>
                      <?php if ($activeCol): ?>
                        <div class="admin-users-meta-item">
                          <span class="admin-users-meta-label">Статус</span>
                          <div>
                            <?php if ($isActive === 1): ?>
                              <span class="badge text-bg-success">Активний</span>
                            <?php else: ?>
                              <span class="badge text-bg-warning">Не активовано</span>
                            <?php endif; ?>
                          </div>
                        </div>
                      <?php endif; ?>
                    </div>
                  </td>
                  <td class="admin-users-number"><span class="admin-users-number-value"><?= $postsCount ?></span></td>
                  <td class="admin-users-number">
                    <?php if ($hasVmBalance): ?>
                      <span class="admin-users-number-value"><?= $balance ?></span>
                    <?php else: ?><span class="text-muted small">—</span><?php endif; ?>
                  </td>
                  <td class="admin-users-antispam">
                    <span class="badge <?= e($antiBadge) ?>"><?= e($antiLabel) ?></span>
                    <?php if ($antiReason !== ''): ?><span class="admin-users-antispam-reason"><?= e($antiReason) ?></span><?php endif; ?>
                  </td>
                  <td>
                    <span class="admin-users-created-date"><?= e($createdDate !== '' ? $createdDate : (string)($u['created_at'] ?? '')) ?></span>
                    <?php if ($createdTime !== ''): ?><span class="admin-users-created-time"><?= e($createdTime) ?></span><?php endif; ?>
                  </td>
                  <td class="admin-users-actions">
                    <div class="admin-users-actions-stack">
                      <a class="btn btn-sm btn-outline-primary" href="/admin/users/edit.php?id=<?= $uid ?>&back=<?= e($selfUrlEnc) ?>"><?= e(admin_tt('edit', 'Редагувати', 'Редактировать', 'Edit')) ?></a>
                      <?php if ($hasVmBalance): ?>
                        <a class="btn btn-sm btn-outline-dark" href="<?= e($coinsQuickLink) ?>">VM Coins</a>
                      <?php endif; ?>
                      <?php if ($hasFlags && $antiStatus === ''): ?>
                        <form method="post" action="/functional/security/anti_spam.php" class="m-0">
                          <?= admin_csrf_field() ?>
                          <input type="hidden" name="action" value="mark_user">
                          <input type="hidden" name="user_id" value="<?= $uid ?>">
                          <input type="hidden" name="status" value="bot">
                          <input type="hidden" name="back" value="<?= e($selfUrl) ?>">
                          <button class="btn btn-sm btn-outline-danger">Позначити бота</button>
                        </form>
                      <?php elseif ($hasFlags): ?>
                        <form method="post" action="/functional/security/anti_spam.php" class="m-0">
                          <?= admin_csrf_field() ?>
                          <input type="hidden" name="action" value="clear_user">
                          <input type="hidden" name="user_id" value="<?= $uid ?>">
                          <input type="hidden" name="back" value="<?= e($selfUrl) ?>">
                          <button class="btn btn-sm btn-outline-success">Зняти мітку</button>
                        </form>
                      <?php endif; ?>
                      <?php if ($activeCol && $isActive === 0): ?>
                        <form method="post" action="/admin/users/activate.php" class="m-0">
                          <?= admin_csrf_field() ?>
                          <input type="hidden" name="id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>">
                          <button class="btn btn-sm btn-outline-success"><?= e(admin_tt('activate', 'Активувати', 'Активировать', 'Activate')) ?></button>
                        </form>
                      <?php endif; ?>
                      <?php if ($activeCol && $isActive === 0 && $tokenCol): ?>
                        <form method="post" action="/admin/users/resend_activation.php" class="m-0">
                          <?= admin_csrf_field() ?>
                          <input type="hidden" name="id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>">
                          <button class="btn btn-sm btn-outline-secondary" <?= $hasToken ? '' : 'disabled' ?>><?= e(admin_tt('resend_activation', 'Надіслати активацію', 'Отправить активацию', 'Resend activation')) ?></button>
                        </form>
                      <?php endif; ?>
                      <form method="post" action="/admin/users/delete.php" class="m-0" onsubmit="return confirm('<?= e(admin_tt('admin_confirm_delete', 'Видалити користувача?', 'Удалить пользователя?', 'Delete user?')) ?>');">
                        <?= admin_csrf_field() ?>
                        <input type="hidden" name="id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>">
                        <button class="btn btn-sm btn-outline-danger"><?= e(admin_tt('delete', 'Видалити', 'Удалить', 'Delete')) ?></button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div class="admin-users-mobile-list">
        <?php foreach ($users as $u): ?>
          <?php
            $uid = (int)($u['id'] ?? 0);
            $isActive = $activeCol ? (int)($u['is_active'] ?? 0) : null;
            $hasToken = $tokenCol ? (trim((string)($u['act_token'] ?? '')) !== '') : false;
            $balance = $hasVmBalance ? (int)($u['vm_coins_balance'] ?? 0) : 0;
            $postsCount = $hasPosts ? (int)($u['posts_count'] ?? 0) : 0;
            $antiStatus = trim((string)($u['antispam_status'] ?? ''));
            $antiReason = trim((string)($u['antispam_reason'] ?? ''));
            [$createdDate, $createdTime] = admin_users_split_datetime((string)($u['created_at'] ?? ''));
            $username = trim((string)($u['username'] ?? ''));
            $email = trim((string)($u['email'] ?? ''));
            $coinsQuickLink = '/admin/coins/adjust.php?user_q=' . rawurlencode($username !== '' ? $username : (string)$uid) . '#manual-adjust';
            $antiBadge = admin_users_antispam_badge($antiStatus === '' ? 'clean' : $antiStatus);
            $antiLabel = $antiStatus === 'bot' ? 'Бот' : ($antiStatus === 'suspect' ? 'Підозрілий' : 'Чисто');
          ?>
          <div class="admin-users-mobile-card">
            <div class="admin-users-mobile-top">
              <div class="admin-users-mobile-id"><span class="admin-users-mobile-id-label">ID</span><span class="admin-users-mobile-id-value"><?= $uid ?></span></div>
              <div class="admin-users-mobile-identity"><div class="admin-users-mobile-name">@<?= e($username) ?></div><div class="admin-users-mobile-email"><?= e($email) ?></div></div>
            </div>
            <div class="admin-users-mobile-grid">
              <div class="admin-users-mobile-box"><span class="admin-users-mobile-label">Роль / Статус</span><div class="admin-users-mobile-value"><?= e((string)($u['role'] ?? '')) ?></div><?php if ($activeCol): ?><div class="mt-2"><span class="badge <?= $isActive === 1 ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $isActive === 1 ? 'Активний' : 'Не активовано' ?></span></div><?php endif; ?></div>
              <div class="admin-users-mobile-box"><span class="admin-users-mobile-label">Пости</span><div class="admin-users-mobile-value"><?= $postsCount ?></div></div>
              <div class="admin-users-mobile-box"><span class="admin-users-mobile-label">VM Coins</span><div class="admin-users-mobile-value"><?= $hasVmBalance ? $balance : '—' ?></div></div>
              <div class="admin-users-mobile-box"><span class="admin-users-mobile-label">Антиспам</span><div><span class="badge <?= e($antiBadge) ?>"><?= e($antiLabel) ?></span></div><?php if ($antiReason !== ''): ?><div class="text-muted small mt-2"><?= e($antiReason) ?></div><?php endif; ?></div>
              <div class="admin-users-mobile-box admin-users-mobile-box-full"><span class="admin-users-mobile-label">Створено</span><div class="admin-users-mobile-value"><?= e($createdDate !== '' ? $createdDate : (string)($u['created_at'] ?? '')) ?><?php if ($createdTime !== ''): ?><div class="text-muted fw-normal mt-1"><?= e($createdTime) ?></div><?php endif; ?></div></div>
            </div>
            <div class="admin-users-mobile-actions">
              <a class="btn btn-outline-primary" href="/admin/users/edit.php?id=<?= $uid ?>&back=<?= e($selfUrlEnc) ?>"><?= e(admin_tt('edit', 'Редагувати', 'Редактировать', 'Edit')) ?></a>
              <?php if ($hasVmBalance): ?><a class="btn btn-outline-dark" href="<?= e($coinsQuickLink) ?>">VM Coins</a><?php endif; ?>
              <?php if ($hasFlags && $antiStatus === ''): ?>
                <form method="post" action="/functional/security/anti_spam.php"><?= admin_csrf_field() ?><input type="hidden" name="action" value="mark_user"><input type="hidden" name="user_id" value="<?= $uid ?>"><input type="hidden" name="status" value="bot"><input type="hidden" name="back" value="<?= e($selfUrl) ?>"><button class="btn btn-outline-danger">Позначити бота</button></form>
              <?php elseif ($hasFlags): ?>
                <form method="post" action="/functional/security/anti_spam.php"><?= admin_csrf_field() ?><input type="hidden" name="action" value="clear_user"><input type="hidden" name="user_id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>"><button class="btn btn-outline-success">Зняти мітку</button></form>
              <?php endif; ?>
              <?php if ($activeCol && $isActive === 0): ?><form method="post" action="/admin/users/activate.php"><?= admin_csrf_field() ?><input type="hidden" name="id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>"><button class="btn btn-outline-success"><?= e(admin_tt('activate', 'Активувати', 'Активировать', 'Activate')) ?></button></form><?php endif; ?>
              <?php if ($activeCol && $isActive === 0 && $tokenCol): ?><form method="post" action="/admin/users/resend_activation.php"><?= admin_csrf_field() ?><input type="hidden" name="id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>"><button class="btn btn-outline-secondary" <?= $hasToken ? '' : 'disabled' ?>><?= e(admin_tt('resend_activation', 'Надіслати активацію', 'Отправить активацию', 'Resend activation')) ?></button></form><?php endif; ?>
              <form method="post" action="/admin/users/delete.php" onsubmit="return confirm('<?= e(admin_tt('admin_confirm_delete', 'Видалити користувача?', 'Удалить пользователя?', 'Delete user?')) ?>');"><?= admin_csrf_field() ?><input type="hidden" name="id" value="<?= $uid ?>"><input type="hidden" name="back" value="<?= e($selfUrl) ?>"><button class="btn btn-outline-danger"><?= e(admin_tt('delete', 'Видалити', 'Удалить', 'Delete')) ?></button></form>
            </div>
          </div>
        <?php endforeach; ?>
        <?php if (!$users): ?><div class="p-3 text-muted small"><?= e(admin_tt('admin_no_data', 'Немає даних', 'Нет данных', 'No data')) ?></div><?php endif; ?>
      </div>

      <div class="p-3">
        <?php if (!$activeCol): ?><div class="text-muted small">Примітка: у users не знайдено колонки активності. Кнопки активації не показуються.</div><?php endif; ?>
        <?php if ($activeCol && !$tokenCol): ?><div class="text-muted small <?= !$activeCol ? 'mt-2' : '' ?>">Примітка: у users не знайдено колонки токена. Кнопка повторної відправки не показується.</div><?php endif; ?>
        <?php if (!$hasFlags): ?><div class="text-muted small mt-2">Примітка: таблиця <span class="font-monospace">security_antispam_flags</span> ще не створена, тому антиспам-мітки поки не відображаються.</div><?php endif; ?>
      </div>
    </div>
  </div>
  <div class="col-lg-3"><?php admin_sidebar('users'); ?></div>
</div>

<?php require __DIR__ . '/../../includes/footer.php'; ?>
