<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once dirname(__DIR__, 2) . '/jailbreakmc.php';

$DB_HOST = JBM_DB_BANS_HOST;
$DB_PORT = JBM_DB_BANS_PORT;
$DB_NAME = JBM_DB_BANS_NAME;
$DB_USER = JBM_DB_BANS_USER;
$DB_PASS = JBM_DB_BANS_PASS;

$type    = isset($_GET['type']) ? $_GET['type'] : 'bans';
$allowed = ['bans', 'mutes', 'warnings', 'kicks'];
if (!in_array($type, $allowed)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid type']);
    exit();
}

$tables = [
    'bans'     => 'litebans_bans',
    'mutes'    => 'litebans_mutes',
    'warnings' => 'litebans_warnings',
    'kicks'    => 'litebans_kicks',
];
$table = $tables[$type];

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$page   = max(1, intval($_GET['page'] ?? 1));
$limit  = min(100, intval($_GET['limit'] ?? 15));
$offset = ($page - 1) * $limit;

try {
    $dsn = "mysql:host=$DB_HOST;port=$DB_PORT;dbname=$DB_NAME;charset=utf8mb4";
    $pdo = new PDO($dsn, $DB_USER, $DB_PASS, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_TIMEOUT            => 5,
    ]);

    $where  = [];
    $params = [];

    if ($search !== '') {
        $where[]  = '(h.name LIKE ? OR b.banned_by_name LIKE ? OR b.reason LIKE ?)';
        $s = '%' . $search . '%';
        $params[] = $s; $params[] = $s; $params[] = $s;
    }

    if ($status === 'active')    $where[] = 'b.active = 1 AND (b.until = -1 OR b.until > UNIX_TIMESTAMP()*1000)';
    if ($status === 'expired')   $where[] = '(b.active = 0 OR (b.until != -1 AND b.until <= UNIX_TIMESTAMP()*1000))';
    if ($status === 'permanent') $where[] = 'b.active = 1 AND b.until = -1';

    $whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';
    $hasUntil = in_array($type, ['bans', 'mutes', 'warnings']);
    $untilCol = $hasUntil ? ', b.until' : '';

    $joinSQL = "LEFT JOIN (
        SELECT uuid, name FROM litebans_history
        WHERE (uuid, date) IN (
            SELECT uuid, MAX(date) FROM litebans_history GROUP BY uuid
        )
    ) h ON b.uuid = h.uuid";

    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM `$table` b $joinSQL $whereSQL");
    $countStmt->execute($params);
    $total = (int)$countStmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT b.id, COALESCE(h.name, b.uuid) AS player, b.uuid, b.reason,
               b.banned_by_name AS staff, b.time AS date_raw,
               b.active, b.server_scope AS server $untilCol
        FROM `$table` b
        $joinSQL
        $whereSQL
        ORDER BY b.time DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute($params);
    $rows = $stmt->fetchAll();

    $now     = time() * 1000;
    $results = array_map(function($r) use ($hasUntil, $now, $type) {
        $dateMs = (int)($r['date_raw'] ?? 0);
        $date   = $dateMs > 0 ? date('Y-m-d H:i', $dateMs / 1000) : '—';

        if ($type === 'kicks') {
            $status  = 'kicked';
            $expires = null;
        } elseif ($type === 'warnings') {
            $status  = $r['active'] ? 'warned' : 'expired';
            $expires = null;
        } else {
            $until   = isset($r['until']) ? (int)$r['until'] : 0;
            $status  = !$r['active'] ? 'expired' : ($until === -1 ? 'permanent' : ($until > $now ? 'active' : 'expired'));
            $expires = $until === -1 ? null : ($until > 0 ? date('Y-m-d', $until / 1000) : null);
        }

        // Map status to type expected by the frontend
        $frontendType = [
            'permanent' => 'permanent',
            'active'    => 'temporary',
            'expired'   => 'temporary',
            'kicked'    => 'kick',
            'warned'    => 'warning',
        ][$status] ?? 'permanent';

        if ($type === 'mutes') $frontendType = 'mute';

        return [
            'id'      => (int)$r['id'],
            'player'  => $r['player'] ?? 'Unknown',
            'uuid'    => $r['uuid']   ?? '',
            'type'    => $frontendType,
            'reason'  => $r['reason'] ?? 'No reason given',
            'staff'   => $r['staff']  ?? 'CONSOLE',
            'date'    => $date,
            'dateRaw' => $dateMs,
            'expires' => $expires,
            'status'  => $status,
            'server'  => $r['server'] ?? '*',
        ];
    }, $rows);

    echo json_encode([
        'total' => $total,
        'page'  => $page,
        'limit' => $limit,
        'pages' => (int)ceil($total / $limit),
        'data'  => $results,
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}