
<?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']);

    // Credit user account
    $stmt = $conn->prepare("UPDATE users SET account_balance = account_balance + ? WHERE id = ?");
    $stmt->bind_param("di", $amount, $userId);
    
    if ($stmt->execute()) {
       $action_type = 'admin_credit';
        $formattedAmount = number_format($amount, 2);
        $description = "An admin has credited your account with \$$formattedAmount.";
        $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' => 'Account credited and log saved.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to credit account.']);
    }

    $stmt->close();
}
?>
