<?php
// api/admin_grant_action.php - 官方撥款引擎
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$input = json_decode(file_get_contents("php://input"), true);
$admin_id = $input['admin_id'];
$target_uid = intval($input['target_uid']);
$amount = intval($input['amount']);
$memo = $input['memo'];

try {
    // 1. 驗證天啟者
    $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
    $stmt->execute([$admin_id]);
    if ($stmt->fetchColumn() < 99) throw new Exception("權限不足");

    if ($amount <= 0) throw new Exception("金額必須大於 0");

    $pdo->beginTransaction();

    // 2. 加錢
    $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
    $stmt->execute([$amount, $target_uid]);

    // 3. 📝 寫入總帳 (關鍵)
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'ADMIN_GRANT', ?, ?)");
    $stmt->execute([$target_uid, $amount, "官方撥款: " . $memo]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "✅ 撥款成功！已寫入總帳。"]);

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