
<?php
 require_once __DIR__ . '/config/config.php';
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = intval($_POST['user_id']);
    $amount = floatval($_POST['amount']);

    // Check if user exists
    $stmt = $conn->prepare("SELECT account_balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'User not found.']);
        exit;
    }

    // Check for sufficient balance
    if ($user['account_balance'] < $amount) {
        echo json_encode(['success' => false, 'message' => 'Insufficient balance.']);
        exit;
    }

    // Deduct from user balance
    $newBalance = $user['account_balance'] - $amount;
    $stmt = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
    $stmt->bind_param("di", $newBalance, $userId);
    
    if ($stmt->execute()) {
        // Insert into activity logs
        $action_type = 'admin_withdrawal';
        $formattedAmount = number_format($amount, 2);
        $description = "An admin has withdrawn \$$formattedAmount from your account for administrative purposes. 🛠️";
        $actor = "admin";
        $created_at = date('Y-m-d H:i:s');

        $logStmt = $conn->prepare("INSERT INTO activity_logs (user_id, actor, action_type, description, created_at) VALUES (?, ?, ?, ?, ?)");
        $logStmt->bind_param("issss", $userId, $actor, $action_type, $description, $created_at);
        $logStmt->execute();
        $logStmt->close();

        echo json_encode(['success' => true, 'message' => 'Withdrawal successful and logged.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to withdraw.']);
    }

    $stmt->close();
}
?>
