File size: 7,183 Bytes
0dff816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
<?php
// packages-backend.php

// Check if session is already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../../index.php');
    exit;
}

// Database connection
require_once '../../config.php';

// Function to get package details
function getPackageDetails($package_id) {
    global $pdo;
    try {
        $stmt = $pdo->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;
}
?>