After INSERTing record(s) to payments_table (from paypal IPN),
$query = "SELECT sum(payments)
FROM payments_table
WHERE customer_id='{$customer_ID}'";
$result = mysql_query($query);
//get the value from result here
$query = "SELECT customer_id
FROM discounts_table
WHERE customer_id='{$customer_ID}'";
$result = mysql_query($query);
//if row > 1
//loop until reached a certain condition
THEN genarate a NEW discount code and insert record to discounts_table