<?php
require_once __DIR__ . '/../admin_middleware.php';

// Requires 'manage_wallet' permission
verifyAdmin('manage_wallet');

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['user_id']) || !isset($data['amount'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing fields']);
    exit;
}

$target_id = $data['user_id'];
$amount = (int)$data['amount'];

try {
    // Transactional update
    $pdo->beginTransaction();

    // Update balance
    $stmt = $pdo->prepare("UPDATE i_users SET diamonds = diamonds + ? WHERE iuid = ?");
    $stmt->execute([$amount, $target_id]);

    // Record transaction log (optional but recommended)
    // $stmt = $pdo->prepare("INSERT INTO transactions ...");

    $pdo->commit();

    echo json_encode(['success' => true, 'message' => 'Diamonds added successfully']);

} catch (PDOException $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
