‰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
$poolId = isset($_POST['pool_id']) ? intval($_POST['pool_id']) : 0;
$amount = isset($_POST['investment_amount']) ? floatval($_POST['investment_amount']) : 0;

if ($poolId <= 0 || $amount <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid investment parameters.']);
    exit();
}

try {
    // 5. Verify the Mining Pool exists and is active
    $stmtPool = $conn->prepare("SELECT name, min_investment, status FROM mining_pools WHERE id = ?");
    $stmtPool->bind_param("i", $poolId);
    $stmtPool->execute();
    $resPool = $stmtPool->get_result();
    
    if ($resPool->num_rows === 0) {
        echo json_encode(['status' => 'error', 'message' => 'Mining pool not found.']);
        exit();
    }
    
    $pool = $resPool->fetch_assoc();
    $stmtPool->close();

    if ($pool['status'] !== 'active') {
        echo json_encode(['status' => 'error', 'message' => 'This mining pool is currently offline or inactive.']);
        exit();
    }

    $minInvestment = floatval($pool['min_investment']);
    if ($amount < $minInvestment) {
        echo json_encode(['status' => 'error', 'message' => 'The minimum investment for this pool is ' . $user['sym'] . number_format($minInvestment, 2) . '.']);
        exit();
    }

    // 6. Check Available Balance
    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_minings table
    $insertMineStmt = $conn->prepare("INSERT INTO user_minings (user_id, pool_id, amount_invested, status) VALUES (?, ?, ?, 'ACTIVE')");
    $insertMineStmt->bind_param("iid", $userId, $poolId, $amount);
    $insertMineStmt->execute();
    $insertMineStmt->close();

    // 9. (Optional) Insert record into Transactions table for accounting/history
    $txType = 'MINING_INVESTMENT';
    $txMethod = "Pool: " . $pool['name'];
    $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 joined ' . htmlspecialchars($pool['name']) . '! Your mining session has started.'
    ]);

} 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 investment.']);
}
?>