prepare("SELECT * FROM packages WHERE id = ?"); $stmt->execute([$package_id]); return $stmt->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { error_log("Error getting package details: " . $e->getMessage()); return false; } } // Function to get all packages function getAllPackages() { global $pdo; try { $stmt = $pdo->prepare("SELECT * FROM packages ORDER BY min_investment ASC"); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { error_log("Error getting all packages: " . $e->getMessage()); return []; } } // Function to check if user can invest in a package function canUserInvest($user_id, $package_id, $amount) { // Get package details $package = getPackageDetails($package_id); if (!$package) return false; // Check if amount is within package limits if ($amount < $package['min_investment'] || $amount > $package['max_investment']) { return false; } return true; } // Function to create a new investment function createInvestment($user_id, $package_id, $amount, $payment_method) { global $pdo; // Start transaction $pdo->beginTransaction(); try { // Get package details $package = getPackageDetails($package_id); if (!$package) { throw new Exception("Package not found"); } // Calculate end date $start_date = date('Y-m-d H:i:s'); $end_date = date('Y-m-d H:i:s', strtotime("+{$package['duration_days']} days")); // Calculate total expected earnings $total_earnings = $amount * ($package['daily_return'] / 100) * $package['duration_days']; // Insert investment record $stmt = $pdo->prepare("INSERT INTO user_investments (user_id, package_id, amount, start_date, end_date, total_earnings) VALUES (?, ?, ?, ?, ?, ?)"); $stmt->execute([$user_id, $package_id, $amount, $start_date, $end_date, $total_earnings]); $investment_id = $pdo->lastInsertId(); // Update user's current package if this is their first or highest investment $stmt = $pdo->prepare("SELECT MAX(amount) as max_investment FROM user_investments WHERE user_id = ? AND status = 'active'"); $stmt->execute([$user_id]); $result = $stmt->fetch(PDO::FETCH_ASSOC); $max_investment = $result ? $result['max_investment'] : 0; if ($amount >= $max_investment) { $stmt = $pdo->prepare("UPDATE users SET current_package_id = ?, package_start_date = ?, package_end_date = ? WHERE id = ?"); $stmt->execute([$package_id, $start_date, $end_date, $user_id]); } // Update user's total invested amount $stmt = $pdo->prepare("UPDATE users SET total_invested = total_invested + ? WHERE id = ?"); $stmt->execute([$amount, $user_id]); // Process payment based on method if ($payment_method === 'wallet') { // Deduct from user's balance $stmt = $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ? AND balance >= ?"); $stmt->execute([$amount, $user_id, $amount]); if ($stmt->rowCount() === 0) { throw new Exception("Insufficient balance"); } // Update session balance $_SESSION['balance'] -= $amount; } else if ($payment_method === 'mpesa') { // For demo purposes, we'll just log this error_log("M-Pesa payment initiated for user $user_id, amount: $amount"); } else if ($payment_method === 'bank') { // For demo purposes, we'll just log this error_log("Bank transfer initiated for user $user_id, amount: $amount"); } // Commit transaction $pdo->commit(); return $investment_id; } catch (Exception $e) { $pdo->rollBack(); error_log("Investment creation failed: " . $e->getMessage()); throw $e; } } // Function to get user's active investment function getUserActiveInvestment($user_id) { global $pdo; try { $stmt = $pdo->prepare(" SELECT ui.*, p.name as package_name, p.daily_return, p.duration_days FROM user_investments ui JOIN packages p ON ui.package_id = p.id WHERE ui.user_id = ? AND ui.status = 'active' AND ui.end_date > NOW() ORDER BY ui.amount DESC LIMIT 1 "); $stmt->execute([$user_id]); return $stmt->fetch(PDO::FETCH_ASSOC); } catch (PDOException $e) { error_log("Error getting user active investment: " . $e->getMessage()); return false; } } // Function to get user's daily products function getUserDailyProducts($user_id) { global $pdo; try { $stmt = $pdo->prepare(" SELECT up.*, p.name as product_name, p.description, p.value, p.image_url FROM user_products up JOIN products p ON up.product_id = p.id WHERE up.user_id = ? ORDER BY up.assigned_date DESC "); $stmt->execute([$user_id]); return $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { error_log("Error getting user daily products: " . $e->getMessage()); return []; } } // Handle package investment request if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) { $response = ['success' => false, 'message' => '']; try { if ($_POST['action'] === 'invest') { $package_id = intval($_POST['package_id']); $amount = floatval($_POST['amount']); $payment_method = $_POST['payment_method']; $user_id = $_SESSION['user_id']; // Validate investment if (canUserInvest($user_id, $package_id, $amount)) { $investment_id = createInvestment($user_id, $package_id, $amount, $payment_method); $response['success'] = true; $response['message'] = 'Investment successful!'; $response['investment_id'] = $investment_id; // Update session data $_SESSION['total_deposits'] += $amount; } else { $response['message'] = 'Invalid investment amount or package selection'; } } } catch (Exception $e) { $response['message'] = $e->getMessage(); } header('Content-Type: application/json'); echo json_encode($response); exit; } ?>