<?php
include 'header.php';

$err = "";

if ($status == "Unverified") {
    echo customAlert('error', 'Please Verify Your KYC To Get full Access to the website');
    echo pageRedirect('4', 'status.php');
}

if ($_SERVER["REQUEST_METHOD"] == "POST" ) {
    $planId = text_input($_POST['plan']);
    $pay_method = text_input($_POST['pay_method']);
    $amount = text_input($_POST['amount']);
    $prof_perc = text_input($_POST['prof_perc']);
    $profit_interval = text_input($_POST['profit_interval']);

    $gp = mysqli_query($link, "SELECT * FROM  plans WHERE id = '$planId' ");
    if (mysqli_num_rows($gp) > 0) {
        $gp_row = mysqli_fetch_assoc($gp);
        $plan_name = $gp_row['plan_name'];
        $min_amount = $gp_row['min_amount'];
        $max_amount = $gp_row['max_amount'];
    }

    if(empty($amount)){
        $err = "Input the stake amount";
    }

    if ($amount > $max_amount) {
        $err = "Stake amount is higher than the maximum account for the selected plan";
    }

    if ($amount < $min_amount) {
        $err = "Stake amount is lower than the minimum account for the selected plan";
    }

    switch ($pay_method) {
        case 'Stellar':
            $v = $xlmbal; 
            break;
        case 'Ripple':
            $v = $xrpbal;
            break;
        case 'Bitcoin':
            $v = $btcbal;
            break;
        case 'Ethereum':
            $v = $ethbal;
            break;
        case 'Tether':
            $v = $usdtbal;
            break;
        case 'Dogecoin':
            $v = $dogebal;
            break;
        case 'Litecoin':
            $v = $ltcbal;
            break;
        case 'Shibainu':
            $v = $shibbal;
            break;
    }

    if ($amount > $v) {
        $err = "Insufficient funds to stake";
    }

    if(empty($err)){
        $start_date = date('d-m-Y H:i:s');
        $end_date  = date('d-m-Y H:i:s', strtotime(' + '.$profit_interval.' days'));
        $total_profit = ($prof_perc/100) * $amount;
        $insert = mysqli_query($link, "INSERT INTO stakes (`userId`, `planId`, `plan`, `coin`, `amount`, `percent`, `period`, `total_profit`, `start_date`, `end_date`, `status`, `date`) VALUES ('$userid', '$planId', '$plan_name', '$pay_method', '$amount', '$prof_perc', '$profit_interval', '$total_profit', '$start_date', '$end_date', 'Active', '$start_date' ) ");
        if($insert){

            switch ($pay_method) {
                case 'Stellar':
                    $cl = 'xlmbal';
                    break;
                case 'Ripple':
                    $cl = 'xrpbal';
                    break;
                case 'Bitcoin':
                    $cl = 'btcbal';
                    break;
                case 'Ethereum':
                    $cl = 'ethbal';
                    break;
                case 'Tether':
                    $cl = 'usdtbal';
                    break;
                case 'Dogecoin':
                    $cl = 'dogebal';
                    break;
                case 'Litecoin':
                    $cl = 'ltcbal';
                    break;
                case 'Shibainu':
                    $cl = 'shibbal';
                    break;
            }

            mysqli_query($link, "UPDATE users SET $cl = $cl - $amount WHERE id = '$userid' ");

            $subject = "New Staking";
            $body = "Dear $fullname
            <p>Your stake request has been submitted and it is active</p>

            <p><strong>Details below:</strong></p>

            <p>Plan Name - <strong>$plan_name</strong> </p>
            <p>Stake Amount - <strong>$amount USD</strong> </p>
            <p>Start Date - <strong>$start_date</strong> </p>
            <p>End Date - <strong>$end_date</strong> </p>
            <p>Estimated Return - <strong>$total_profit USD</strong> </p>
            <p>Proft Percent/Interval - <strong>$prof_perc/$profit_interval days</strong> </p>


            <p>Thank you for choosing $sitename. We look forward to serving you.</p> <br>

            <p>Best regards,</p>
            
            <p>$sitename</p>";

            sendMail($email,$subject,$body);

            $msg = "Your stake is active!";
        }
    }
}


?>

<?php

	if($err != ""){
		echo customAlert('error', $err);
	}

	if ($msg != "") {
		echo customAlert('success', $msg);
		echo pageRedirect('3', 'invest-history.php');
	}

?>

<div class="appHeader" style="background-color:#161129">
        <div class="left">
            <a href="#" class="headerButton" data-bs-toggle="modal" data-bs-target="#sidebarPanel"> <i class="fas fa-bars text-white"></i> </a>
        </div>
        <div class="pageTitle text-white">
            Invest
        </div>
        <div class="right">
				<a href="Notifications.php" class="headerButton"> <i class="fas fa-bell text-white"></i> <span class="badge badge-danger">0</span> </a>
				<a href="logout.php" class="headerButton"> <i class="fas fa-sign-out-alt text-white"></i></a>
        </div>
    </div>
<div class="container mt-5" style="margin-top: 120px!important;">
    <div class="row">
        <div class="col-lg-6 offset-lg-3">
            <div class="card">
                <div class="card-header">
                    <h5 class="card-title">Make a Stake</h5>
                </div>
                <div class="card-body">
                    <form method="POST">

                        <div class="form-group">
                            <label for="plan">Select Stake Plan:</label>
                            <input type="hidden" name="depAmount" id="depAmount">
                            <select class="form-control" id="plan" name="plan" required>
                                <option value="">Select Plan</option>
                                <?php
											  $select = mysqli_query($link, "SELECT * FROM  plans WHERE plan_status = 'Active' ");
											  if (mysqli_num_rows($select) > 0) {
												while ($row = mysqli_fetch_assoc($select)) {
												  $id = $row ['id'];
										?>
                           


                                <option value="<?php echo $row['id'] ?>" data-plan_id="<?php echo $row['id'] ?>" data-plan_name="<?php echo $row['plan_name']  ?>" data-min_amount="<?php echo $row['min_amount'] ?>" data-max_amount="<?php echo $row['max_amount']  ?>" data-profit_percentage="<?php echo $row['profit_percentage'] ?>" data-interval_period="<?php echo $row['interval_period'] ?>" data-time_period="<? echo $row['time_period'] ?>" data-plan_status="<?php echo $row['plan_status']  ?>" data-created_at="<?php echo $row['date'] ?>"> <?php echo $row['plan_name']  ?> - Min Amount: $<?php echo $row['min_amount'] ?> - Max Amount: $<?php echo $row['max_amount'] ?> - Profit Percentage: <?php echo $row['profit_percentage']  ?>%
                            
                            </option> 
                      
                                <?php }} ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="return_amount">Deposit Range</label>
                            <input type="text" class="form-control" id="deposit_range" name="deposit_range" readonly>
                        </div>

                        <div class="form-group">
                
                            <label for="return_amount">Choose Coin:</label>
                            <select class="form-control" id="pay_method" name="pay_method" required>
                                <option value="">Choose Coin</option>
                                <?php
											  $select = mysqli_query($link, "SELECT * FROM  wallets   ");
											  if (mysqli_num_rows($select) > 0) {
												while ($row = mysqli_fetch_assoc($select)) {
												  $id = $row ['id'];
										?>
                                        <option value="<?php echo $row['wallet_name'] ?>"><?php echo $row['wallet_name']  ?> (<?php echo $row['short_name'] ?>)</option>

                                        <?php }} ?>
                                
                            </select>

                           
                        </div>

                        <div class="form-group">
                            <label for="return_amount">Staking Amount:</label>
                            <input type="text" class="form-control" id="amount" name="amount" placeholder="Enter Deposit Amount" required>
                        </div>
                        <div class="form-group">
                            <label for="return_amount">Profit Percentage:</label>
                            <input type="text" class="form-control" id="prof_perc" name="prof_perc" readonly>
                        </div>
                        <!-- <div class="form-group">
                            <label for="return_amount">Return Amount per Interval ($):</label>
                            <input type="text" class="form-control" id="return_amount" name="return_amount" readonly>
                        </div> -->
                        <div class="form-group">
                            <label for="profit_interval">Profit Interval Period(Days):</label>
                            <input type="text" class="form-control" id="profit_interval" name="profit_interval" value="" readonly>
                        </div>
                        <!-- <div class="form-group">
                            <label for="current_date">Current Date (New York Time Zone):</label>
                            <input type="text" class="form-control" id="current_date" name="current_date" readonly>
                        </div>
                        <div class="form-group">
                            <label for="end_date">End Date:</label>
                            <input type="text" class="form-control" id="end_date" name="end_date" readonly>
                        </div> -->
                        <!--<div class="form-group">
                            <label for="next_profit_day">Next Profit Day:</label>
                            <input type="text" class="form-control" id="next_profit_day" name="next_profit_day" readonly>
                        </div>-->
                        <button type="submit" class="btn btn-primary" id="invest-btn" style="margin-top: 25px!important;">Stake</button>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById("plan").addEventListener("change", function() {
        // Get the selected plan's element
        var selectedPlan = document.getElementById("plan");
        var selectedOption = selectedPlan.options[selectedPlan.selectedIndex];

        // Access the custom data attributes
        let minAmount = parseFloat(selectedOption.getAttribute("data-min_amount"));
        let maxAmount = parseFloat(selectedOption.getAttribute("data-max_amount"));
        var prof_percentage = parseFloat(selectedOption.getAttribute("data-profit_percentage"));

        // document.getElementById("prof_perc").value = prof_percentage + "%";
        document.getElementById("prof_perc").value = prof_percentage;

        var intervalPeriod = parseInt(selectedOption.getAttribute("data-interval_period"));
        document.getElementById("profit_interval").value = intervalPeriod;
        var depositAmount = parseFloat(document.getElementById("amount").value);
        var timePeriod = parseInt(selectedOption.getAttribute("data-time_period"));

        // Calculate the end date by adding the time period to the current date
        var currentDate = new Date();
        var endDate = new Date(currentDate);
        endDate.setDate(currentDate.getDate() + timePeriod);

        // Calculate the next profit day by adding the interval period to the current date
        var nextProfitDate = new Date(currentDate);
        nextProfitDate.setDate(currentDate.getDate() + intervalPeriod);

        // Display the calculated values in the input fields
        var depositRangeInput = document.getElementById("deposit_range");
        var endDateInput = document.getElementById("end_date");
        var nextProfitDateInput = document.getElementById("next_profit_day");
        var returnAmountInput = document.getElementById("return_amount");
        var intervalPeriodInput = document.getElementById("interval_period");

        depositRangeInput.value = "Min Amount: $" + minAmount + " - Max Amount: $" + maxAmount;
        endDateInput.value = endDate.toISOString().slice(0, 10);
        nextProfitDateInput.value = nextProfitDate.toISOString().slice(0, 10);
        returnAmountInput.value = returnAmount.toFixed(2);


    });

    // Function to calculate return amount using AJAX
    function calculateReturnAmount() {

        var selectedPlan = document.getElementById("plan");
        var selectedOption = selectedPlan.options[selectedPlan.selectedIndex];
        var profitPercentage = parseFloat(selectedOption.getAttribute("data-profit_percentage"));
        var depositAmount = parseFloat(document.getElementById("amount").value); // Move this line inside the function

        var minAmount = parseFloat(selectedOption.getAttribute("data-min_amount"));
        var maxAmount = parseFloat(selectedOption.getAttribute("data-max_amount"));

        var selectedPlanCoin = document.getElementById("pay_method");
        var selectedOptionCoin = selectedPlanCoin.options[selectedPlanCoin.selectedIndex];
        document.getElementById("depAmount").value = parseFloat(selectedOptionCoin.getAttribute("data-amount"));

        // Check if depositAmount is a valid number
        if (!isNaN(depositAmount)) {

            if (depositAmount <= maxAmount && depositAmount >= minAmount) {

                console.log(minAmount, maxAmount);
                // Calculate the return amount per interval
                var returnAmount = depositAmount * (profitPercentage / 100);
                document.getElementById("invest-btn").disabled = false;

                // Display the calculated return amount
                var returnAmountInput = document.getElementById("return_amount");
                returnAmountInput.value = returnAmount.toFixed(2);
            } else {
                var returnAmountInput = document.getElementById("return_amount");
                returnAmountInput.value = "Staking Amount is invalid!";
                // Disable the submit button
                document.getElementById("invest-btn").disabled = true;
            }
        }
    }

    // Listen for changes in the deposit amount input field
    var depositAmountInput = document.getElementById("amount");
    depositAmountInput.addEventListener("input", calculateReturnAmount);


    // Function to format a date as YYYY-MM-DD
    function formatDate(date) {
        var yyyy = date.getFullYear().toString();
        var mm = (date.getMonth() + 1).toString().padStart(2, '0'); // January is 0!
        var dd = date.getDate().toString().padStart(2, '0');
        return yyyy + '-' + mm + '-' + dd;
    }

    // Function to get the current date in New York time zone
    function getCurrentDateInNewYork() {
        var newYorkTimeZoneOffset = -5 * 60; // New York is GMT-5
        var now = new Date();
        var newYorkDate = new Date(now.getTime() + (newYorkTimeZoneOffset * 60 * 1000));
        return newYorkDate;
    }

    // Get the "current_date" input element
    var currentDateInput = document.getElementById("current_date");

    // Set the value of the "current_date" input to the current date in New York time zone
    currentDateInput.value = formatDate(getCurrentDateInNewYork());
</script>

<style>
.sidebar-balance {
    background: #000000;
}.action-group {
    background: #000000;
}.modal-body.p-0 {
    background: white;
}ul.listview.flush.transparent.image-listview {
    background: white;
    box-shadow: 0 1px 3px 0 rgb(0 0 0 / 9%);
}body.dark-mode .image-listview>li a.item {
    color: #000000 !important;
}.icon-box.bg-primary {
    background: #000000 !important;
}span.badge.badge-primary {
    background: #000000 !important;
}



</style>




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