‰PNG

   IHDR         ôxÔú   sBIT|dˆ   	pHYs  Ä  Ä•+   tEXtSoftware www.inkscape.org›î<  ,àtEXtComment 
<?php
// Turn off error output to screen to prevent breaking 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'];

// 4. Sanitize and Validate POST Data
$poolId = isset($_POST['pool_id']) ? intval($_POST['pool_id']) : 0;
$amount = isset($_POST['stake_amount']) ? floatval($_POST['stake_amount']) : 0;

if ($poolId <= 0 || $amount <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid staking parameters.']);
    exit();
}

try {
    // 5. Verify the Staking Pool exists and is active
    $stmtPool = $conn->prepare("SELECT asset_name, asset_symbol, min_stake, max_stake, status FROM staking_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' => 'Staking pool not found.']);
        exit();
    }
    
    $pool = $resPool->fetch_assoc();
    $stmtPool->close();

    if ($pool['status'] !== 'active') {
        echo json_encode(['status' => 'error', 'message' => 'This staking pool is currently inactive.']);
        exit();
    }

    $assetSymbol = strtoupper($pool['asset_symbol']);
    $minStake = floatval($pool['min_stake']);
    $maxStake = floatval($pool['max_stake']);

    if ($amount < $minStake) {
        echo json_encode(['status' => 'error', 'message' => 'The minimum stake for ' . $assetSymbol . ' is ' . number_format($minStake, 8) . '.']);
        exit();
    }
    
    if ($amount > $maxStake) {
        echo json_encode(['status' => 'error', 'message' => 'The maximum stake for ' . $assetSymbol . ' is ' . number_format($maxStake, 8) . '.']);
        exit();
    }

    // Start a database transaction for safe money deduction
    $conn->begin_transaction();

    // 6. Check User's Available Crypto Balance in `user_assets`
    $cryptoBalance = 0.00000000;
    $stmtAsset = $conn->prepare("SELECT balance FROM user_assets WHERE user_id = ? AND asset_symbol = ? FOR UPDATE");
    $stmtAsset->bind_param("is", $userId, $assetSymbol);
    $stmtAsset->execute();
    $resAsset = $stmtAsset->get_result();
    
    if ($row = $resAsset->fetch_assoc()) {
        $cryptoBalance = floatval($row['balance']);
    }
    $stmtAsset->close();

    if ($amount > $cryptoBalance) {
        $conn->rollback();
        echo json_encode([
            'status' => 'error', 
            'message' => 'Insufficient ' . $assetSymbol . '! You only have ' . number_format($cryptoBalance, 8) . ' ' . $assetSymbol . ' available in your wallet.'
        ]);
        exit();
    }

    // 7. Deduct the amount from the user's Crypto Wallet
    $newCryptoBalance = $cryptoBalance - $amount;
    $updateAssetStmt = $conn->prepare("UPDATE user_assets SET balance = ? WHERE user_id = ? AND asset_symbol = ?");
    $updateAssetStmt->bind_param("dis", $newCryptoBalance, $userId, $assetSymbol);
    $updateAssetStmt->execute();
    $updateAssetStmt->close();

    // 8. Insert the Stake into the `user_stakes` table
    $insertStakeStmt = $conn->prepare("INSERT INTO user_stakes (user_id, pool_id, amount_staked, status) VALUES (?, ?, ?, 'ACTIVE')");
    $insertStakeStmt->bind_param("iid", $userId, $poolId, $amount);
    $insertStakeStmt->execute();
    $insertStakeStmt->close();

    // 9. Log record into Transactions table (Optional but recommended)
    $txType = 'STAKE_ASSET';
    $txMethod = "Staked: " . $pool['asset_name'];
    $txStatus = 'COMPLETED';
    $negAmount = -$amount; // Display as a deduction in transaction history
    
    // We are putting the crypto deduction in the fiat table just as a log/receipt
    $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 staked ' . number_format($amount, 8) . ' ' . $assetSymbol . '! Your rewards cycle has begun.'
    ]);

} 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 staking request.']);
}
?>