<?php 
session_start();
include('includes/session.php');

$userid = $userID;

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 

    // Check if this is a bot switch request
    if (isset($_POST['cancel_active']) && $_POST['cancel_active'] == '1') {
        // Handle bot switching
        $new_planid = intval($_POST['bot_id']);
        $active_bot_id = intval($_POST['active_bot_id']);
        
        // 1. Cancel old bot
        $activeBotQuery = mysqli_query($conn, "SELECT * FROM user_bot_subscriptions WHERE id='$active_bot_id' AND user_id='$userid' AND status='active'");
        if (mysqli_num_rows($activeBotQuery) == 0) {
            echo "<script>Swal.fire({
                icon: 'error',
                title: 'No Active Bot',
                text: 'No active bot found to cancel'
            });</script>";
            exit();
        }
        
        $activeBot = mysqli_fetch_array($activeBotQuery);
        $active_trading_balance = floatval($activeBot['trading_balance']);
        
        // Get user current balances
        $userSQL = mysqli_query($conn, "SELECT * FROM users WHERE id='$userid'");
        $userRow = mysqli_fetch_array($userSQL);
        $fund_balance = floatval($userRow['fund_balance']);
        $email = $userRow['email'];
        $first_name = $userRow['first_name'];
        
        // Unlock old bot funds - move from locked to available fund_balance
        // When bot is cancelled, the trading_balance is already in fund_balance
        // We just need to mark it as unlocked by cancelling the bot
        // fund_balance stays the same
        
        // Cancel old bot
        mysqli_query($conn, "UPDATE user_bot_subscriptions SET 
            status = 'cancelled',
            updated_at = NOW()
            WHERE id = '$active_bot_id'");
        
        // Record unlock transaction
        $unlock_desc = "Funds unlocked from cancelled bot subscription";
        mysqli_query($conn, 
            "INSERT INTO transactions 
            (user_id, type, amount, description, status, currency, created_at) 
            VALUES 
            ('$userid', 'credit', '$active_trading_balance', '$unlock_desc', 'completed', 'USDT', NOW())");
        
        // NOTIFICATION: Bot Cancelled (User)
        $mail_subject = "Trading Bot Cancelled";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                            
                            <p class='message'>
                                Your active trading bot has been cancelled as requested. The trading balance has been unlocked and is now available in your fund balance.
                            </p>

                            <!-- Cancellation Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Cancelled Bot ID:</strong> BOT-" . $active_bot_id . "<br>
                                    <strong>Unlocked Amount:</strong> $" . number_format($active_trading_balance, 2) . "<br>
                                    <strong>Cancellation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>New Available Balance:</strong> $" . number_format($fund_balance + $active_trading_balance, 2) . "
                                </div>
                            </div>

                            <!-- Next Steps -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>What's Next?</h3>
                                <p style='color: #6c757d;'>You can now:</p>
                                <ul style='color: #6c757d;'>
                                    <li>Subscribe to a new trading bot</li>
                                    <li>Withdraw your unlocked funds</li>
                                    <li>View your transaction history</li>
                                </ul>
                            </div>

                            <!-- Action Button -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/trading_bots.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #007bff; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                    View Trading Bots
                                </a>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Have questions about bot cancellation?</p>
                                <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Our Support Team</a>
                            </div>
                        </div>";

        // Send user notification
        require_once("../proccess/mail_sender.php");

        // Now continue with new bot subscription
        $planid = $new_planid;
        
    } else {
        // Normal subscription (not switching)
        $planid = intval($_POST['bot_id']);
    }
    
    // ============================================
    // NORMAL SUBSCRIPTION PROCESS
    // ============================================
    
    // Validate bot plan exists and is active
    $trandingBot = mysqli_query($conn, "SELECT * FROM trading_bot_plans WHERE id='$planid' AND is_active = 1");
    
    if (mysqli_num_rows($trandingBot) == 0) {
        echo "<script>Swal.fire({
            icon: 'error',
            title: 'Bot Plan Not Found',
            text: 'Selected bot plan not found or inactive'
        });</script>";
        exit();
    }
    
    $botRow = mysqli_fetch_array($trandingBot);
    
    $plan_name = $botRow['plan_name'];
    $subscription_fee = floatval($botRow['subscription_fee']);
    $min_trading_balance = floatval($botRow['min_trading_balance']);
    $max_trading_balance = $botRow['max_trading_balance'] ? floatval($botRow['max_trading_balance']) : 0;
    $trading_accuracy = $botRow['trading_accuracy'];
    $daily_roi_percentage = $botRow['daily_roi_percentage'];
    
    // Get user current balances
    $userSQL = mysqli_query($conn, "SELECT * FROM users WHERE id='$userid'");
    $userRow = mysqli_fetch_array($userSQL);
    
    $fund_balance = floatval($userRow['fund_balance']);
    $referral_paid = intval($userRow['referral_paid']);
    $referred_by = intval($userRow['referred_by']);
    $first_name = $userRow['first_name'];
    $email = $userRow['email'];
    $last_name = $userRow['last_name'];
    
    // Check if user already has active bot (for normal subscription)
    if (!isset($_POST['cancel_active'])) {
        $activeBotQuery = mysqli_query($conn, "SELECT * FROM user_bot_subscriptions WHERE user_id='$userid' AND status = 'active'");
        
        if (mysqli_num_rows($activeBotQuery) > 0) {
            $activeBot = mysqli_fetch_array($activeBotQuery);
            $active_plan_id = $activeBot['bot_plan_id'];
            $active_bot_id = $activeBot['id'];
            
            // If trying to subscribe to same bot plan
            if ($active_plan_id == $planid) {
                echo "<script>Swal.fire({
                    icon: 'error',
                    title: 'Already Subscribed',
                    text: 'You are already subscribed to this bot plan!'
                });</script>";
                exit();
            }
            
            // Ask user if they want to switch bots
            echo "<script>
            Swal.fire({
                icon: 'warning',
                title: 'Active Bot Found',
                html: 'You already have an active trading bot.<br><br>Do you want to cancel it and switch to this new bot?',
                showCancelButton: true,
                confirmButtonText: 'Yes, Switch Bot',
                cancelButtonText: 'No, Keep Current',
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33'
            }).then((result) => {
                if (result.isConfirmed) {
                    // User wants to switch
                    let formData = new FormData();
                    formData.append('bot_id', '$planid');
                    formData.append('cancel_active', '1');
                    formData.append('active_bot_id', '$active_bot_id');
                    
                    // Submit to same page
                    fetch('subscribe_bot.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.text())
                    .then(data => {
                        document.body.innerHTML = data;
                    });
                } else {
                    // User doesn't want to switch
                    window.location.href = 'trading_bots.php';
                }
            });
            </script>";
            exit();
        }
    }
    
    // CHECK SUBSCRIPTION FEE BALANCE
    if ($subscription_fee > $fund_balance) {
        echo '<script>Swal.fire({
            icon: "error",
            title: "Insufficient Balance",
            html: "Insufficient fund balance for subscription fee!<br><br>" +
                  "<strong>Required:</strong> $' . number_format($subscription_fee, 2) . '<br>" +
                  "<strong>Your Fund Balance:</strong> $' . number_format($fund_balance, 2) . '<br><br>" +
                  "Please add more funds to your trading balance."
        });</script>';
        exit();
    }
    
    // DEDUCT SUBSCRIPTION FEE
    $remaining_balance = $fund_balance - $subscription_fee;
    
    // DETERMINE BOT STATUS
    if ($remaining_balance >= $min_trading_balance) {
        $status = 'active';
        $trading_balance = $remaining_balance;
        
        // Check if exceeds maximum trading balance
        if ($max_trading_balance > 0 && $remaining_balance > $max_trading_balance) {
            $trading_balance = $max_trading_balance;
            // Excess remains in fund_balance (not moved to available_balance)
            $excess = $remaining_balance - $max_trading_balance;
            // fund_balance stays as $remaining_balance (excess stays in fund_balance)
        }
    } else {
        $status = 'pending';
        $trading_balance = $remaining_balance;
        $needed_amount = $min_trading_balance - $remaining_balance;
    }
    
    // UPDATE USER FUND BALANCE
    // When bot is active, entire remaining balance stays in fund_balance
    // When bot is pending, entire remaining balance stays in fund_balance
    mysqli_query($conn, "UPDATE users SET fund_balance = '$remaining_balance' WHERE id = '$userid'");
    
    // CREATE BOT SUBSCRIPTION
    $date = date('Y-m-d H:i:s');
    $subscription_start = date('Y-m-d');
    $subscription_end = date('Y-m-d', strtotime('+30 days'));
    
    mysqli_query($conn, 
        "INSERT INTO user_bot_subscriptions 
        (user_id, bot_plan_id, trading_balance, subscription_start, subscription_end, 
         auto_renew, status, success_rate, total_profit, total_trades, created_at)
        VALUES 
        ('$userid', '$planid', '$trading_balance', '$subscription_start', '$subscription_end', 
         1, '$status', '$trading_accuracy', 0.00, 0, '$date')");
    
    $subscription_id = mysqli_insert_id($conn);
    
    // RECORD SUBSCRIPTION FEE TRANSACTION
    $fee_description = 'Monthly subscription fee for ' . mysqli_real_escape_string($conn, $plan_name);
    mysqli_query($conn, 
        "INSERT INTO transactions 
        (user_id, type, amount, description, status, currency, created_at) 
        VALUES 
        ('$userid', 'debit', '$subscription_fee', '$fee_description', 'completed', 'USDT', '$date')");
    
    // RECORD BOT TRANSACTION
    mysqli_query($conn,
        "INSERT INTO bot_transactions 
        (subscription_id, transaction_date, transaction_type, amount, description, created_at)
        VALUES 
        ('$subscription_id', '$subscription_start', 'fee', '$subscription_fee', 'Monthly subscription fee', '$date')");
    
    // IF BOT IS ACTIVE, RECORD BALANCE LOCK
    if ($status == 'active') {
        $lock_description = 'Funds locked for trading bot: $' . number_format($trading_balance, 2);
        mysqli_query($conn,
            "INSERT INTO bot_transactions 
            (subscription_id, transaction_date, transaction_type, amount, description, created_at)
            VALUES 
            ('$subscription_id', '$subscription_start', 'balance_lock', '$trading_balance', '$lock_description', '$date')");
    }
    
    // PROCESS REFERRAL BONUS
    $referral_bonus_given = false;
    $referral_bonus_amount = 0;
    
    if ($status == 'active' && $referral_paid == 0 && $referred_by > 0) {
        $refQuery = mysqli_query($conn, "SELECT * FROM referral_settings WHERE is_active = 1");
        if (mysqli_num_rows($refQuery) > 0) {
            $refRow = mysqli_fetch_array($refQuery);
            $bot_bonus = floatval($refRow['bot_bonus']);
            
            if ($bot_bonus > 0) {
                $referrerSQL = mysqli_query($conn, "SELECT * FROM users WHERE id='$referred_by'");
                if (mysqli_num_rows($referrerSQL) > 0) {
                    $referrerRow = mysqli_fetch_array($referrerSQL);
                    $referrer_email = $referrerRow['email'];
                    $referrer_name = $referrerRow['first_name'];
                    
                    // Update referrer's referral balance
                    $current_ref_balance = floatval($referrerRow['referral_balance']);
                    $new_ref_balance = $current_ref_balance + $bot_bonus;
                    
                    mysqli_query($conn, 
                        "UPDATE users SET referral_balance = '$new_ref_balance' WHERE id = '$referred_by'");
                    
                    // Mark referral as paid for this user
                    mysqli_query($conn, "UPDATE users SET referral_paid = 1 WHERE id = '$userid'");
                    
                    // Record referral transaction
                    $ref_description = 'Referral bonus for bot subscription: ' . mysqli_real_escape_string($conn, $plan_name);
                    mysqli_query($conn, 
                        "INSERT INTO referral_transactions 
                        (referrer_id, referred_id, transaction_type, amount, description, created_at) 
                        VALUES 
                        ('$referred_by', '$userid', 'bot_bonus', '$bot_bonus', '$ref_description', '$date')");
                    
                    // Also record as regular transaction for referrer
                    $ref_transaction_desc = 'Referral bonus from ' . mysqli_real_escape_string($conn, $first_name) . "'s bot subscription";
                    mysqli_query($conn, 
                        "INSERT INTO transactions 
                        (user_id, type, amount, description, status, currency, created_at) 
                        VALUES 
                        ('$referred_by', 'credit', '$bot_bonus', '$ref_transaction_desc', 'completed', 'USDT', '$date')");
                    
                    $referral_bonus_given = true;
                    $referral_bonus_amount = $bot_bonus;
                    
                    // NOTIFICATION: Referral Bonus Received (Referrer)
                    $mail_subject = "Referral Bonus Received";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Congratulations <span class='user-name'>" . $referrer_name . "</span>! 🎉</h2>
                                        
                                        <p class='message'>
                                            You've received a referral bonus because " . $first_name . " " . $last_name . " subscribed to a trading bot!
                                        </p>

                                        <!-- Bonus Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Referral Bonus:</strong> $" . number_format($bot_bonus, 2) . "<br>
                                                <strong>Referred User:</strong> " . $first_name . " " . $last_name . "<br>
                                                <strong>Bot Plan:</strong> " . $plan_name . "<br>
                                                <strong>Bonus Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>New Referral Balance:</strong> $" . number_format($new_ref_balance, 2) . "
                                            </div>
                                        </div>

                                        <!-- How to Use -->
                                        <div class='next-steps'>
                                            <h3 style='color: #2c3e50;'>How to Use Your Bonus</h3>
                                            <p style='color: #6c757d;'>You can:</p>
                                            <ul style='color: #6c757d;'>
                                                <li>Withdraw your referral earnings</li>
                                                <li>Use it to subscribe to trading bots</li>
                                                <li>Keep accumulating with more referrals</li>
                                            </ul>
                                        </div>

                                        <!-- Action Button -->
                                        <div style='text-align: center; margin: 30px 0;'>
                                            <a href='" . $myUrl . "/referrals.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #007bff; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                View Referral Dashboard
                                            </a>
                                        </div>

                                        <!-- Support Section -->
                                        <div class='support-section'>
                                            <p class='support-text'>Thank you for referring quality users!</p>
                                            <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Support</a>
                                        </div>
                                    </div>";

                    // Send referral notification
                    $user_email = $referrer_email;
                    $first_name = $referrer_name;
                    require_once("../proccess/mail_sender.php");
                }
            }
        }
    }
    
    // NOTIFICATION: Bot Subscription Created (USER)
    $mail_subject = "Trading Bot Subscription " . ($status == 'active' ? "Activated" : "Created");
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            " . ($status == 'active' ? 
                                "🎉 <strong>Your trading bot is now active!</strong> The AI will start trading immediately." : 
                                "✅ <strong>Your bot subscription has been created!</strong> Add funds to activate it.") . "
                        </p>

                        <!-- Subscription Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Bot Subscription ID:</strong> SUB-" . $subscription_id . "<br>
                                <strong>Bot Plan:</strong> " . $plan_name . "<br>
                                <strong>Subscription Fee:</strong> $" . number_format($subscription_fee, 2) . "<br>
                                <strong>Trading Balance:</strong> $" . number_format($trading_balance, 2) . "<br>
                                " . ($status == 'pending' ? 
                                "<strong>Additional Needed:</strong> <span style='color: #dc3545;'>$" . number_format($needed_amount, 2) . "</span><br>" : "") . "
                                <strong>Daily ROI:</strong> " . $daily_roi_percentage . "%<br>
                                <strong>Trading Accuracy:</strong> " . $trading_accuracy . "%<br>
                                <strong>Status:</strong> <span style='color: " . ($status == 'active' ? '#28a745' : '#ffc107') . "; font-weight: bold;'>" . strtoupper($status) . "</span><br>
                                <strong>Subscription Date:</strong> " . date('F j, Y g:i A') . "
                            </div>
                        </div>

                        " . ($status == 'active' ? "
                        <!-- Active Bot Info -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>🤖 Your Bot is Now Trading</h3>
                            <p style='color: #6c757d;'>What to expect:</p>
                            <ul style='color: #6c757d;'>
                                <li>Daily profits added to your available balance</li>
                                <li>Trade notifications in your dashboard</li>
                                <li>Monthly performance reports</li>
                                <li>Auto-renewal on " . date('F j, Y', strtotime('+30 days')) . "</li>
                            </ul>
                        </div>" : "
                        <!-- Pending Activation Info -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>⚠️ Action Required</h3>
                            <p style='color: #6c757d;'>To activate your bot, add <strong>$" . number_format($needed_amount, 2) . "</strong> to your fund balance.</p>
                            <ul style='color: #6c757d;'>
                                <li>Minimum required: $" . number_format($min_trading_balance, 2) . "</li>
                                <li>Current fund balance: $" . number_format($remaining_balance, 2) . "</li>
                                <li>Bot will activate automatically when balance reaches minimum</li>
                            </ul>
                        </div>") . "

                        <!-- Action Button -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/trading_bots.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #007bff; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                " . ($status == 'active' ? "View Active Bot" : "Add Funds") . "
                            </a>
                        </div>

                        " . ($referral_bonus_given ? "
                        <!-- Referral Bonus Section -->
                        <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #155724;'>🎁 Referral Bonus Earned!</h4>
                            <p style='color: #155724;'>
                                Your referrer received a $" . number_format($referral_bonus_amount, 2) . " bonus because of your subscription!
                                Thank you for being part of our community.
                            </p>
                        </div>" : "") . "

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with your trading bot?</p>
                            <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Our Support Team</a>
                        </div>
                    </div>";

    // Send user notification
    require_once("../proccess/mail_sender.php");

    // NOTIFICATION: Bot Subscription Created (ADMIN)
    $admin_mail_subject = "New Bot Subscription - " . ($status == 'active' ? "ACTIVE" : "PENDING");
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>New Trading Bot Subscription</h2>
                            
                            <p class='message'>
                                A user has " . ($status == 'active' ? "activated" : "created") . " a new trading bot subscription.
                            </p>

                            <!-- Subscription Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Subscription ID:</strong> SUB-" . $subscription_id . "<br>
                                    <strong>User ID:</strong> " . $userid . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>User Email:</strong> " . $email . "<br>
                                    <strong>Bot Plan:</strong> " . $plan_name . "<br>
                                    <strong>Subscription Fee:</strong> $" . number_format($subscription_fee, 2) . "<br>
                                    <strong>Trading Balance:</strong> $" . number_format($trading_balance, 2) . "<br>
                                    <strong>Daily ROI:</strong> " . $daily_roi_percentage . "%<br>
                                    <strong>Status:</strong> <span style='color: " . ($status == 'active' ? '#28a745' : '#ffc107') . "; font-weight: bold;'>" . strtoupper($status) . "</span><br>
                                    <strong>Subscription Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Subscription End:</strong> " . date('F j, Y', strtotime('+30 days')) . "
                                </div>
                            </div>

                            <!-- Admin Actions -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Admin Actions</h3>
                                <p style='color: #6c757d;'>" . ($status == 'pending' ? 
                                    "This bot is pending activation. User needs to add $" . number_format($needed_amount, 2) . " more." : 
                                    "Bot is active and trading. Monitor performance in admin panel.") . "</p>
                            </div>

                            <!-- Admin Links -->
                            <div class='support-section'>
                                <p class='support-text'>Manage this subscription:</p>
                                <a href='" . $myUrl . "/admin/bot-subscriptions.php?id=" . $subscription_id . "' class='support-link'>View in Admin Panel</a>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    // SHOW SUCCESS MESSAGE
    if ($status == 'active') {
        $success_html = '<div class=\"text-start\">' .
              '<strong>✅ Bot Plan:</strong> ' . htmlspecialchars($plan_name) . '<br>' .
              '<strong>💰 Subscription Fee:</strong> $' . number_format($subscription_fee, 2) . '<br>' .
              '<strong>🔒 Trading Balance Locked:</strong> $' . number_format($trading_balance, 2) . '<br>' .
              '<strong>📈 Daily ROI:</strong> ' . $daily_roi_percentage . '%<br>' .
              '<strong>📊 Trading Accuracy:</strong> ' . $trading_accuracy . '%<br><br>' .
              '<div class=\"alert alert-success\">' .
              '<strong>Status:</strong> <span class=\"fw-bold\">ACTIVE</span><br>' .
              'Your bot is now trading! Profits will be added to your available balance daily.' .
              '</div></div>';
        
        echo "<script>Swal.fire({
            icon: 'success',
            title: 'Bot Subscription Successful! 🎉',
            html: '$success_html',
            confirmButtonText: 'OK'
        }).then(() => {
            window.location.href = 'trading_bots.php';
        });</script>";
    } else {
        $warning_html = '<div class=\"text-start\">' .
              '<strong>🤖 Bot Plan:</strong> ' . htmlspecialchars($plan_name) . '<br>' .
              '<strong>💰 Subscription Fee:</strong> $' . number_format($subscription_fee, 2) . ' (paid)<br>' .
              '<strong>💵 Current Fund Balance:</strong> $' . number_format($remaining_balance, 2) . '<br><br>' .
              '<div class=\"alert alert-warning\">' .
              '<strong>Status:</strong> <span class=\"fw-bold\">PENDING ACTIVATION</span>' .
              '</div><br>' .
              '<strong>📋 Action Required:</strong><br>' .
              'Add <strong class=\"text-danger\">$' . number_format($needed_amount, 2) . '</strong> ' .
              'to your fund balance to activate the bot.<br>' .
              'Minimum trading balance required: <strong>$' . number_format($min_trading_balance, 2) . '</strong><br><br>' .
              '<div class=\"alert alert-info\">' .
              '💡 <strong>Go to \"Add Funds\" to deposit more USDT to your fund balance.</strong>' .
              '</div></div>';
        
        echo "<script>Swal.fire({
            icon: 'warning',
            title: 'Bot Subscription Created ⚠️',
            html: '$warning_html',
            confirmButtonText: 'OK'
        }).then(() => {
            window.location.href = 'trading_bots.php';
        });</script>";
    }
    
} else {
    echo "<script>Swal.fire({
        icon: 'error',
        title: 'Invalid Request',
        text: 'Invalid request method'
    });</script>";
}

mysqli_close($conn);
?>



<?php
if (isset($_SESSION['swal'])) {
    echo "
    <script>
        Swal.fire({
            icon: '{$_SESSION['swal']['icon']}',
            title: '{$_SESSION['swal']['title']}',
            text: '{$_SESSION['swal']['text']}'
        });
    </script>
    ";
    unset($_SESSION['swal']);
}
?>