<?php
require_once __DIR__ . '/../config/db.php';

$action = $_GET['action'] ?? 'list';

// 1. List all users (Admin only)
if ($action === 'list') {
    requireAuth(['admin']);
    $stmt = $pdo->query("SELECT id, username, email, name, role, seller_level, shop_name, phone, points, is_banned, created_at FROM users ORDER BY id DESC");
    sendResponse(true, ['data' => $stmt->fetchAll()]);
}

// 2. Toggle seller level (Regular vs Corporate)
if ($action === 'toggle_seller_level' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuth(['admin']);
    $body = getJsonInput();
    $stmt = $pdo->prepare("UPDATE users SET seller_level = ? WHERE id = ? AND role = 'seller'");
    $stmt->execute([$body['level'], $body['user_id']]);
    sendResponse(true, 'อัปเดตระดับผู้ขายเรียบร้อย');
}

// 3. Ban / Unban User
if ($action === 'toggle_ban' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $admin = requireAuth(['admin']);
    $body = getJsonInput();
    $userId = $body['user_id'];
    $isBanned = (int)$body['is_banned'];
    $reason = $body['reason'] ?? 'ละเมิดข้อกำหนดการใช้งาน';

    $stmt = $pdo->prepare("UPDATE users SET is_banned = ? WHERE id = ?");
    $stmt->execute([$isBanned, $userId]);

    if ($isBanned) {
        $logStmt = $pdo->prepare("INSERT INTO banned_users (user_id, banned_by, reason) VALUES (?, ?, ?)");
        $logStmt->execute([$userId, $admin['id'], $reason]);
    }
    sendResponse(true, $isBanned ? 'ระงับการใช้งานบัญชีแล้ว' : 'ปลดระงับการใช้งานแล้ว');
}

// 4. Delete user permanently
if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    requireAuth(['admin']);
    $body = getJsonInput();
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    $stmt->execute([$body['user_id']]);
    sendResponse(true, 'ลบบัญชีผู้ใช้ถาวรเรียบร้อย');
}
