<?php
include 'header.php';

if (isset($_GET['email'])) {
    $email = $_GET['email'];
} else {
    $email = '';
}

$msg = "";
$err = "";

if (isset($_POST['submit'])) {
    // Fetch current prices
    function fetchCurrentPrices() {
        $apiUrl = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,ripple,stellar,dogecoin,litecoin,shiba-inu,binancecoin,solana,bitcoin-cash&vs_currencies=usd";
        $response = file_get_contents($apiUrl);
        return json_decode($response, true);
    }

    $currentPrices = fetchCurrentPrices();

    // Get user input
    $operation = $_POST['operation']; // Add or Subtract
    $amount_usd = floatval($link->real_escape_string($_POST['amount']));
    $selectedCoin = $_POST['selectCoin']; // Get selected coin (e.g., btcbal, ethbal, etc.)
    $method = $_POST['withdrawMethod']; // Get selected method

    // Fetch current balances from the database
    $sql = "SELECT * FROM users WHERE email = '$email'";
    $result = mysqli_query($link, $sql);
    $row = mysqli_fetch_assoc($result);

    // Determine the USD field for the selected coin
    $coin_usd_field = $selectedCoin . '_in_usd'; // e.g., btcbal_in_usd

    // Update the selected coin's USD balance based on operation
    $new_coin_usd_balance = $operation === 'add' ? $row[$coin_usd_field] + $amount_usd : $row[$coin_usd_field] - $amount_usd;

    // Calculate the equivalent coin amount based on the current price
    $coinPrice = 0;
    switch ($selectedCoin) {
        case 'btcbal':
            $coinPrice = $currentPrices['bitcoin']['usd'];
            break;
        case 'ethbal':
            $coinPrice = $currentPrices['ethereum']['usd'];
            break;
        case 'usdtbal':
            $coinPrice = 1; // USDT is 1:1 with USD
            break;
        case 'bnbbal':
            $coinPrice = $currentPrices['binancecoin']['usd'];
            break;
        case 'dogebal':
            $coinPrice = $currentPrices['dogecoin']['usd'];
            break;
        case 'ltcbal':
            $coinPrice = $currentPrices['litecoin']['usd'];
            break;
        case 'shibbal':
            $coinPrice = $currentPrices['shiba-inu']['usd'];
            break;
        case 'solanabal':
            $coinPrice = $currentPrices['solana']['usd'];
            break;
        case 'bchbal':
            $coinPrice = $currentPrices['bitcoin-cash']['usd'];
            break;
        case 'xlmbal':
            $coinPrice = $currentPrices['stellar']['usd'];
            break;
        case 'xrpbal':
            $coinPrice = $currentPrices['ripple']['usd'];
            break;
    }

    // Calculate the equivalent coin amount
    $coinAmount = $amount_usd / $coinPrice;
    // Ensure user has enough balance before subtracting
    if ($operation === 'subtract' && ($row[$coin_usd_field] < $amount_usd || $row[$selectedCoin] < $coinAmount || $row[$method] < $amount_usd)) {
        echo "<script>
            alert('Insufficient balance! Please enter a valid amount.');
            window.history.back();
        </script>";
        exit();
    }
    
    // Update the selected coin's USD balance based on operation
    $new_coin_usd_balance = $operation === 'add' ? $row[$coin_usd_field] + $amount_usd : $row[$coin_usd_field] - $amount_usd;
    $new_coin_balance = $operation === 'add' ? $row[$selectedCoin] + $coinAmount : $row[$selectedCoin] - $coinAmount;
    $new_method_balance = $operation === 'add' ? $row[$method] + $amount_usd : $row[$method] - $amount_usd;
    
    // Prepare SQL update statement
    $sql1 = "UPDATE users SET 
        $coin_usd_field = '$new_coin_usd_balance', 
        $selectedCoin = '$new_coin_balance'
        WHERE email = '$email'";
    
    if (mysqli_query($link, $sql1)) {
        echo "<script>
            alert('Fund Updated Successfully!');
            window.history.back();
        </script>";
    } else {
        echo "Error: " . mysqli_error($link);
    }

}

$sql = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);
    $username = $row['username'];
}
?>

<!-- Content wrapper scroll start -->
<div class="content-wrapper-scroll">
    <!-- Content wrapper start -->
    <div class="content-wrapper">
        <!-- Row start -->
        <div class="row">
            <div class="col-sm-12 col-12">
                <!-- Card start -->
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">Fund User</div> <br> <br> <br> <br>
                          <center><button class="btn btn-success mt-5" data-bs-toggle="modal" data-bs-target="#balanceModal">View User Balance</button></center>
                    </div>
                    <div class="card-body">
                        <!-- Row start -->
                        <form method="POST" action="">
                            <div class="row">
                            
                                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                                    <div class="mb-3">
                                        <label for="selectCoin" class="form-label">Select Coin</label>
                                        <select class="form-select" name="selectCoin" id="selectCoin">
                                            <option value="btcbal">Bitcoin (BTC)</option>
                                            <option value="ethbal">Ethereum (ETH)</option>
                                            <option value="usdtbal">Tether (USDT)</option>
                                            <option value="bnbbal">Binance Coin (BNB)</option>
                                            <option value="dogebal">Dogecoin (DODG)</option>
                                            <option value="ltcbal">Litecoin (LTC)</option>
                                            <option value="shibbal">Shiba Inu (SHIB)</option>
                                            <!--<option value="solanabal">Solana (SOL)</option>-->
                                            <!--<option value="bchbal">Bitcoin Cash (BCH)</option>-->
                                            <option value="xlmbal">Stellar (XML)</option>
                                            <option value="xrpbal">Ripple (XRP)</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                                    <div class="mb-3">
                                        <label for="inputNumber" class="form-label">Amount (in USDT)</label>
                                        <input type="number" class="form-control" name="amount" placeholder="Amount to add/subtract" required>
                                    </div>
                                </div>
                                
                                <!-- Add/Subtract radio buttons -->
                                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                                    <div class="mb-3">
                                        <label for="operation" class="form-label">Operation</label>
                                        <div>
                                            <input type="radio" id="add" name="operation" value="add" checked>
                                            <label for="add">Add</label>
                                            <input type="radio" id="subtract" name="operation" value="subtract">
                                            <label for="subtract">Subtract</label>
                                        </div>
                                    </div>
                                </div>
                                
                            </div>
                            <!-- Row end -->

                            <button class="btn btn-success" name="submit" type="submit">Submit</button>

                            <!-- Form actions footer end -->

                        </form>

                    </div>
                </div>
                <!-- Card end -->

            </div>

        </div>
        <!-- Row end -->

    </div>
    <!-- Content wrapper end -->
</div>
<!-- Content wrapper scroll end -->

 <!-- Modal -->
    <div class="modal fade" id="balanceModal" tabindex="-1" aria-labelledby="balanceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="balanceModalLabel">User Balances</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <ul class="list-group">
                        <li class="list-group-item"><strong>BTC Balance In USDT: </strong>$<?php echo number_format ($row['btcbal_in_usd'] , 2)  ?></li>
                        <li class="list-group-item"><strong>BNB Balance In USDT: </strong>$<?php echo number_format($row['bnbbal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>ETH Balance In USDT: </strong>$<?php echo number_format($row['ethbal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>USDT: </strong>$<?php echo number_format($row['usdtbal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>XLM Balance In USDT: </strong> $<?php echo number_format($row['xlmbal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>DOGE Balance In USDT: </strong>$<?php echo number_format($row['dogebal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>XRP Balance In USDT: </strong> $<?php echo number_format($row['btcbal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>LTC Balance In USDT: </strong>$<?php echo number_format($row['ltcbal_in_usd'] , 2) ?></li>
                        <li class="list-group-item"><strong>SHIB Balance In USDT: </strong>$<?php echo number_format($row['shibbal_in_usd'] , 2) ?></li>
                        <!--<li class="list-group-item"><strong>SOL Balance In USDT: </strong>$<?php echo number_format($row['solanabal_in_usd'] , 2) ?></li>-->
                        <!--<li class="list-group-item"><strong>BCH Balance In USDT: </strong>$<?php echo number_format($row['bchbal_in_usd'] , 2) ?></li>-->
                        
                        
                    </ul>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>


<?php 
include 'footer.php';
?>