‰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 (Security against forged requests)
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
$projectId = isset($_POST['project_id']) ? intval($_POST['project_id']) : 0;
$amount = isset($_POST['investment_amount']) ? floatval($_POST['investment_amount']) : 0;
$duration = isset($_POST['duration_selection']) ? trim($_POST['duration_selection']) : '';

if ($projectId <= 0 || $amount <= 0 || empty($duration)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid investment parameters. Please check your inputs.']);
    exit();
}

try {
    // 5. Verify the Real Estate Project exists and is open
    $stmtProject = $conn->prepare("SELECT title, min_investment, roi_percentage, status FROM real_estate_projects WHERE id = ?");
    $stmtProject->bind_param("i", $projectId);
    $stmtProject->execute();
    $resProject = $stmtProject->get_result();
    
    if ($resProject->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'Project not found.']);
        exit();
    }
    
    $project = $resProject->fetch_assoc();
    $stmtProject->close();

    if ($project['status'] !== 'open') {
        echo json_encode(['status' => 'error', 'message' => 'This project is currently closed to new investors.']);
        exit();
    }

    $minInvestment = floatval($project['min_investment']);
    if ($amount < $minInvestment) {
        echo json_encode(['status' => 'error', 'message' => 'The minimum investment for this project is ' . $user['sym'] . number_format($minInvestment, 2) . '.']);
        exit();
    }

    // 6. Check Available Balance (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();

    // 7. 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();

    // 8. Insert the Investment into the user_realestate_investments table
    $roi = floatval($project['roi_percentage']);
    $insertInvStmt = $conn->prepare("INSERT INTO user_realestate_investments (user_id, project_id, amount_invested, duration_selected, expected_roi, status) VALUES (?, ?, ?, ?, ?, 'ACTIVE')");
    $insertInvStmt->bind_param("iidsd", $userId, $projectId, $amount, $duration, $roi);
    $insertInvStmt->execute();
    $insertInvStmt->close();

    // 9. Insert record into Transactions table for accounting/history
    $txType = 'REAL_ESTATE_INVESTMENT';
    $txMethod = "Project: " . $project['title'];
    $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 invested in ' . htmlspecialchars($project['title']) . '! Your portfolio has been updated.'
    ]);

} 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 your investment.']);
}
?>