// Example: 1 point per 100 currency units
$customerId = $_POST['customer_id'];
$totalAmount = $_POST['total_amount'];
$transactionId = $lastInsertedTransactionId; // get after INSERT

$pointsEarned = floor($totalAmount / 100);

if ($pointsEarned > 0) {
    // Update customer's point balance
    $conn->query("UPDATE customers SET loyalty_points = loyalty_points + $pointsEarned WHERE id = $customerId");

    // Get new balance
    $newBalance = $conn->query("SELECT loyalty_points FROM customers WHERE id = $customerId")->fetch_assoc()['loyalty_points'];

    // Log
    $stmt = $conn->prepare("
        INSERT INTO loyalty_points_log (customer_id, transaction_id, points_earned, balance_after, action, remarks)
        VALUES (?, ?, ?, ?, 'earn', 'Auto-earned from sale')
    ");
    $stmt->bind_param("iiii", $customerId, $transactionId, $pointsEarned, $newBalance);
    $stmt->execute();
}
