public function convert_loyalty() { $balance = $this->loyalty_balance(); global $config; $expiry = strtotime($config['loyalty']['expiry'], time()); while ($balance > 0) { $voucher = $balance; if ($voucher > 1000) { $voucher = 1000; } $balance -= $voucher; $value = $voucher * $config['loyalty']['cash_value']; // Let's do this inside a transaction mysql_query('BEGIN'); $discount = new DiscountCode(); $discount->code = strtoupper(md5(uniqid() . mt_rand())); $discount->description = "Loyalty Discount for {$this->nickname}: {$voucher}pts"; $discount->type = "monetary"; $discount->quantity = 1; $discount->active = true; $discount->value = $value; $discount->expires = $expiry; $discount->full_cart_discount = true; $discount->loyalty = true; if (!$discount->save()) { mysql_query('ROLLBACK'); throw new Error500('Unable to save discount', $discount); } $ld = new LoyaltyDiscount(); $ld->discount_id = $discount->id; $ld->user_id = $this->id; $ld->discount_id = $discount->id; $ld->points_cash_value = $value; $ld->points = $voucher; if (!$ld->save()) { mysql_query('ROLLBACK'); throw new Error500('Unable to save LoyaltyDiscount', $discount); } } // Mark all points as redeemed $id = mysql_real_escape_string($this->id); $awards = LoyaltyAward::find_all("users.id = '{$id}' AND loyalty_awards.redeemed = 0"); foreach ($awards as $award) { $award->redeemed = true; if (!$award->save()) { mysql_query('ROLLBACK'); throw new Error500('Unable to save LoyaltyAward', $award); } } mysql_query('COMMIT'); }