PNG IHDR x sBIT|d pHYs + tEXtSoftware www.inkscape.org< ,tEXtComment
<?php
// Turn off error output to screen so we don't break the JSON response
ini_set('display_errors', 0);
error_reporting(E_ALL);
session_start();
require_once('includes/connect.php');
require_once('includes/functions.php');
// Tell the browser we are sending JSON data back
header('Content-Type: application/json');
// 1. Check Authentication
if (!isset($_SESSION['Email'])) {
echo json_encode(['status' => 'error', 'message' => 'Your session has expired. Please log in again.']);
exit();
}
// 2. CSRF Token Validation
if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
echo json_encode(['status' => 'error', 'message' => 'Security token invalid. Please refresh the page and try again.']);
exit();
}
// 3. Fetch User Data
$user = GetMember1($_SESSION['Email']);
if (!$user) {
echo json_encode(['status' => 'error', 'message' => 'User account not found.']);
exit();
}
$userId = $user['ID'];
$userCapital = floatval($user['Capital']);
// 4. Sanitize and Validate POST Data
$planId = isset($_POST['plan_id']) ? intval($_POST['plan_id']) : 0;
$amount = isset($_POST['investment_amount']) ? floatval($_POST['investment_amount']) : 0;
if ($planId <= 0 || $amount <= 0) {
echo json_encode(['status' => 'error', 'message' => 'Invalid subscription parameters.']);
exit();
}
try {
// 5. Fetch the Subscription Plan from the database
$stmtPlan = $conn->prepare("SELECT * FROM subscription_plans WHERE id = ?");
$stmtPlan->bind_param("i", $planId);
$stmtPlan->execute();
$resPlan = $stmtPlan->get_result();
if ($resPlan->num_rows === 0) {
echo json_encode(['status' => 'error', 'message' => 'Subscription plan not found.']);
exit();
}
$plan = $resPlan->fetch_assoc();
$stmtPlan->close();
if ($plan['status'] !== 'active') {
echo json_encode(['status' => 'error', 'message' => 'This plan is currently inactive and cannot be purchased.']);
exit();
}
// 6. Validate Min / Max Investment Limits
$minInvestment = floatval($plan['min_investment']);
$maxInvestment = floatval($plan['max_investment']);
if ($amount < $minInvestment) {
echo json_encode(['status' => 'error', 'message' => 'The minimum investment for the ' . htmlspecialchars($plan['name']) . ' plan is ' . $user['sym'] . number_format($minInvestment, 2) . '.']);
exit();
}
if ($amount > $maxInvestment) {
echo json_encode(['status' => 'error', 'message' => 'The maximum investment for the ' . htmlspecialchars($plan['name']) . ' plan is ' . $user['sym'] . number_format($maxInvestment, 2) . '.']);
exit();
}
// 7. Check User's Available Capital
if ($amount > $userCapital) {
echo json_encode([
'status' => 'error',
'message' => 'Insufficient capital! You only have ' . htmlspecialchars($user['sym']) . number_format($userCapital, 2) . ' available.'
]);
exit();
}
// Start a database transaction so we don't accidentally deduct money without saving the record
$conn->begin_transaction();
// 8. Deduct the amount from the user's Capital
$newCapital = $userCapital - $amount;
$updateCapStmt = $conn->prepare("UPDATE members SET Capital = ? WHERE ID = ?");
$updateCapString = strval($newCapital); // Cast to string for legacy database compatibility
$updateCapStmt->bind_param("si", $updateCapString, $userId);
$updateCapStmt->execute();
$updateCapStmt->close();
// 9. Calculate Expiration Date and Insert into user_subscriptions table
$durationDays = intval($plan['duration_days']);
$expiresAt = date('Y-m-d H:i:s', strtotime("+$durationDays days"));
$roi = floatval($plan['roi_percentage']);
$insertSubStmt = $conn->prepare("INSERT INTO user_subscriptions (user_id, plan_id, amount_invested, expected_roi, status, expires_at) VALUES (?, ?, ?, ?, 'ACTIVE', ?)");
$insertSubStmt->bind_param("iidss", $userId, $planId, $amount, $roi, $expiresAt);
$insertSubStmt->execute();
$insertSubStmt->close();
// 10. Log record into Transactions table for accounting/history
$txType = 'SUBSCRIPTION';
$txMethod = "Plan: " . $plan['name'] . " (" . $durationDays . " Days)";
$txStatus = 'COMPLETED';
$negAmount = -$amount; // Display as a deduction in transaction history
$insertTxStmt = $conn->prepare("INSERT INTO transactions (user_id, type, amount, method, status) VALUES (?, ?, ?, ?, ?)");
$insertTxStmt->bind_param("isdss", $userId, $txType, $negAmount, $txMethod, $txStatus);
$insertTxStmt->execute();
$insertTxStmt->close();
// Commit changes to the database
$conn->commit();
// Send Success Response back to Javascript
echo json_encode([
'status' => 'success',
'message' => 'Successfully subscribed to the ' . htmlspecialchars($plan['name']) . ' plan!'
]);
} catch (Exception $e) {
$conn->rollback(); // Reverse the money deduction if the database insertion failed
echo json_encode(['status' => 'error', 'message' => 'System error: Could not process subscription.']);
}
?>
b IDATxytVսϓ22 A@IR:hCiZ[v*E:WũZA ^dQeQ @ !jZ'>gsV仿$|?g)&x-E