<?php
// api/admin_users_action.php - 天啟者全知之眼 (含重置密碼、扣款與凍結)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];

// 🟢 GET: 撈取名單
if ($method === 'GET') {
    try {
        $sql = "SELECT id, username, email, level, coins, created_at FROM users ORDER BY level DESC, id ASC";
        $stmt = $pdo->query($sql);
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(["status" => "success", "data" => $data]);
    } catch (Exception $e) {
        echo json_encode(["status" => "error", "message" => "DB Error: " . $e->getMessage()]);
    }
    exit;
}

// 🔴 POST: 執行操作
if ($method === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    
    $admin_id = $input['admin_id'] ?? 0;
    $target_id = $input['target_id'] ?? 0;
    $action = $input['action'] ?? '';
    
    // 參數處理
    $new_level = isset($input['new_level']) ? intval($input['new_level']) : null;
    $amount = isset($input['amount']) ? intval($input['amount']) : 0;
    $reason = isset($input['reason']) ? $input['reason'] : '天啟者裁決';
    $new_password = isset($input['new_password']) ? trim($input['new_password']) : '';

    try {
        // 1. 權限檢查
        $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
        $stmt->execute([$admin_id]);
        if ($stmt->fetchColumn() < 99) throw new Exception("越權操作");

        $pdo->beginTransaction();

        if ($action === 'update_level') {
            if ($admin_id == $target_id && $new_level < 99) throw new Exception("統帥，請勿降級自己！");
            $stmt = $pdo->prepare("UPDATE users SET level = ? WHERE id = ?");
            $stmt->execute([$new_level, $target_id]);
            $statusText = ($new_level < 0) ? "❄️ 已凍結" : "LV.$new_level";
            $msg = "✅ 權限已更新為：$statusText";
            
        } else if ($action === 'deduct') {
            if ($amount <= 0) throw new Exception("金額必須大於 0");
            $stmt = $pdo->prepare("UPDATE users SET coins = coins - ? WHERE id = ?");
            $stmt->execute([$amount, $target_id]);
            $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'PENALTY', ?, ?)");
            $stmt->execute([$target_id, -$amount, "懲罰扣款: " . $reason]);
            $msg = "➖ 已扣除 $amount Z幣 (PENALTY)。";

        } else if ($action === 'reset_password') {
            // 🔑 重置密碼邏輯
            if (strlen($new_password) < 4) throw new Exception("新密碼太短");
            // 加密
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
            $stmt->execute([$hashed_password, $target_id]);
            $msg = "🔑 密碼已強制重置成功！";

        } else if ($action === 'delete') {
            if ($admin_id == $target_id) throw new Exception("統帥，請勿刪除自己！");
            $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$target_id]);
            $msg = "☠️ 帳號已抹除。";
        }

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => $msg]);

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "message" => $e->getMessage()]);
    }
    exit;
}
?>