prepare(" SELECT i.*, s.founder_id FROM investments i JOIN startups s ON i.startup_id = s.id WHERE i.status = 'approved' AND i.next_payment_date <= ? AND i.next_payment_date IS NOT NULL "); $stmt->execute([$now]); $dueInvestments = $stmt->fetchAll(); foreach ($dueInvestments as $inv) { $db->beginTransaction(); try { $amountToPay = $inv['monthly_dividend']; // Ensure we don't overpay if ($inv['paid_amount'] + $amountToPay > $inv['total_return']) { $amountToPay = $inv['total_return'] - $inv['paid_amount']; } if ($amountToPay > 0) { // 1. Deduct from founder $stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?"); $stmt->execute([$amountToPay, $inv['founder_id']]); // 2. Add to investor $stmt = $db->prepare("UPDATE users SET balance = balance + ? WHERE id = ?"); $stmt->execute([$amountToPay, $inv['investor_id']]); // 3. Update investment record $newPaidAmount = $inv['paid_amount'] + $amountToPay; $newStatus = ($newPaidAmount >= $inv['total_return']) ? 'completed' : 'approved'; $nextPayment = date('Y-m-d', strtotime($inv['next_payment_date'] . ' +1 month')); // If completed, clear next payment date if ($newStatus === 'completed') { $nextPayment = null; } $stmt = $db->prepare("UPDATE investments SET paid_amount = ?, status = ?, next_payment_date = ? WHERE id = ?"); $stmt->execute([$newPaidAmount, $newStatus, $nextPayment, $inv['id']]); // 4. Create a notification for both parties (Optional but good) $stmt = $db->prepare("INSERT INTO notifications (user_id, content) VALUES (?, ?)"); $stmt->execute([$inv['investor_id'], "You received a dividend payment of £" . number_format($amountToPay, 2) . " from " . $inv['id']]); $stmt->execute([$inv['founder_id'], "A dividend payment of £" . number_format($amountToPay, 2) . " was paid to an investor."]); } $db->commit(); } catch (Exception $e) { $db->rollBack(); // Log error or ignore for now } } }