<?php
if (!defined('TONSUI_LOADED')) { define('TONSUI_LOADED', true); }
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) { header('Access-Control-Allow-Origin: ' . $origin); }
else if (!empty($_SERVER['HTTP_HOST'])) { $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https'; header('Access-Control-Allow-Origin: ' . $scheme . '://' . $_SERVER['HTTP_HOST']); }
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

requireAdmin(true);

try {
  $page = max(1, (int)($_GET['page'] ?? 1));
  $limit = min(100, max(1, (int)($_GET['limit'] ?? 25)));
  $offset = ($page - 1) * $limit;
  $q = trim($_GET['q'] ?? '');

  // Ensure table exists
  $pdo->exec("CREATE TABLE IF NOT EXISTS registration_audit (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    name VARCHAR(255) NULL,
    username VARCHAR(255) NULL,
    email VARCHAR(255) NULL,
    ip_address VARCHAR(64) NULL,
    user_agent TEXT NULL,
    location VARCHAR(255) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX (user_id)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

  $where = '';
  $params = [];
  if ($q !== '') {
    $where = "WHERE name LIKE ? OR username LIKE ? OR email LIKE ? OR ip_address LIKE ? OR location LIKE ?";
    $like = "%$q%";
    $params = [$like,$like,$like,$like,$like];
  }

  $countSql = "SELECT COUNT(*) AS c FROM registration_audit $where";
  $cstmt = $pdo->prepare($countSql);
  $cstmt->execute($params);
  $total = (int)($cstmt->fetch(PDO::FETCH_ASSOC)['c'] ?? 0);

  $sql = "SELECT id, user_id, name, username, email, ip_address, user_agent, location, created_at FROM registration_audit $where ORDER BY id DESC LIMIT $limit OFFSET $offset";
  $stmt = $pdo->prepare($sql);
  $stmt->execute($params);
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

  echo json_encode(['success' => true, 'page' => $page, 'limit' => $limit, 'total' => $total, 'items' => $rows]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
