<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="js/jquery-2.2.4.min.js"></script>

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

$userid = $userID;
$new_bot_id = intval($_GET['new_bot_id']);

// Get active bot details
$activeBotQuery = mysqli_query($conn, "SELECT * FROM user_bot_subscriptions WHERE 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"
    }).then(() => {
        window.location.href = "trading_bots.php";
    });</script>';
    exit();
}

$activeBot = mysqli_fetch_array($activeBotQuery);
$active_bot_id = $activeBot['id'];
$active_trading_balance = floatval($activeBot['trading_balance']);

// Get user details for notification
$userSQL = mysqli_query($conn, "SELECT * FROM users WHERE id='$userid'");
$userRow = mysqli_fetch_array($userSQL);
$available_balance = floatval($userRow['available_balance']);
$fund_balance = floatval($userRow['fund_balance']);
$first_name = $userRow['first_name'];
$email = $userRow['email'];

// Get bot plan details for notification
$botPlanQuery = mysqli_query($conn, "SELECT * FROM user_bot_subscriptions ubs 
    JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id 
    WHERE ubs.id = '$active_bot_id'");
$botPlanData = mysqli_fetch_array($botPlanQuery);
$bot_plan_name = $botPlanData['plan_name'];

// Unlock old bot funds (move from fund_balance to available_balance)
$new_available_balance = $available_balance + $active_trading_balance;

// Update user balances
mysqli_query($conn, "UPDATE users SET 
    fund_balance = fund_balance - '$active_trading_balance',
    available_balance = '$new_available_balance'
    WHERE id = '$userid'");

// 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 transferred to your available balance.
                    </p>

                    <!-- Cancellation Details -->
                    <div class='details-section'>
                        <div class='detail-box'>
                            <strong>Cancelled Bot ID:</strong> BOT-" . $active_bot_id . "<br>
                            <strong>Bot Plan:</strong> " . $bot_plan_name . "<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>Previous Available Balance:</strong> $" . number_format($available_balance, 2) . "<br>
                            <strong>New Available Balance:</strong> $" . number_format($new_available_balance, 2) . "<br>
                            <strong>Current Fund Balance:</strong> $" . number_format($fund_balance - $active_trading_balance, 2) . "
                        </div>
                    </div>

                    <!-- Reason & Next Steps -->
                    <div class='next-steps'>
                        <h3 style='color: #2c3e50;'>Reason & Next Steps</h3>
                        <p style='color: #6c757d;'><strong>Reason:</strong> Switching to a new trading bot</p>
                        <p style='color: #6c757d;'>What happens next:</p>
                        <ul style='color: #6c757d;'>
                            <li>Your unlocked funds are now in available balance</li>
                            <li>You can withdraw these funds if needed</li>
                            <li>A new bot subscription will start automatically</li>
                            <li>Your trading history is preserved</li>
                        </ul>
                    </div>

                    <!-- Important Notes -->
                    <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                        <h4 style='color: #856404;'>⚠️ Important Notes</h4>
                        <ul style='color: #856404;'>
                            <li>Your cancelled bot will no longer trade or generate profits</li>
                            <li>Any pending profits have been processed</li>
                            <li>Subscription fee for cancelled bot is non-refundable</li>
                            <li>New bot subscription will require new subscription fee</li>
                        </ul>
                    </div>

                    <!-- Action Button -->
                    <div style='text-align: center; margin: 30px 0;'>
                        <a href='" . $myUrl . "/transactions.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 Transaction History
                        </a>
                    </div>

                    <!-- Support Section -->
                    <div class='support-section'>
                        <p class='support-text'>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");

// NOTIFICATION: Bot Cancelled (ADMIN)
$admin_mail_subject = "Bot Cancelled - User Switching Bots";
$admin_mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Trading Bot Cancelled</h2>
                        
                        <p class='message'>
                            A user has cancelled their active trading bot to switch to a new one.
                        </p>

                        <!-- Cancellation Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Cancelled Bot ID:</strong> BOT-" . $active_bot_id . "<br>
                                <strong>User ID:</strong> " . $userid . "<br>
                                <strong>User Name:</strong> " . $first_name . " " . $userRow['last_name'] . "<br>
                                <strong>User Email:</strong> " . $email . "<br>
                                <strong>Cancelled Bot Plan:</strong> " . $bot_plan_name . "<br>
                                <strong>Unlocked Amount:</strong> $" . number_format($active_trading_balance, 2) . "<br>
                                <strong>New Bot ID:</strong> " . $new_bot_id . " (to be subscribed)<br>
                                <strong>Cancellation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>New Available Balance:</strong> $" . number_format($new_available_balance, 2) . "
                            </div>
                        </div>

                        <!-- Bot Performance Summary -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>Cancelled Bot Performance</h3>
                            <p style='color: #6c757d;'>
                                Bot was active for " . (isset($botPlanData['subscription_start']) ? 
                                round((time() - strtotime($botPlanData['subscription_start'])) / (60 * 60 * 24)) . " days" : "N/A") . "<br>
                                Total Trades: " . ($botPlanData['total_trades'] ?? 0) . "<br>
                                Total Profit: $" . number_format($botPlanData['total_profit'] ?? 0, 2) . "<br>
                                Success Rate: " . ($botPlanData['success_rate'] ?? 0) . "%
                            </p>
                        </div>

                        <!-- Admin Actions -->
                        <div class='support-section'>
                            <p class='support-text'>Admin Actions:</p>
                            <a href='" . $myUrl . "/admin/bot-subscriptions.php?id=" . $active_bot_id . "' class='support-link'>View Cancelled Bot Details</a><br>
                            <a href='" . $myUrl . "/admin/users.php?id=" . $userid . "' class='support-link'>View User Profile</a>
                        </div>
                    </div>";

// Send admin notification
require_once("../proccess/admin_mailer.php");

echo '<script>
Swal.fire({
    icon: "success",
    title: "Bot Cancelled Successfully!",
    text: "Old bot cancelled and funds unlocked. Now subscribing to new bot...",
    timer: 2000,
    showConfirmButton: false
}).then(() => {
    // Auto-submit form for new bot
    let form = document.createElement("form");
    form.method = "POST";
    form.action = "subscribe_bot.php";
    
    let input = document.createElement("input");
    input.type = "hidden";
    input.name = "bot_id";
    input.value = "' . $new_bot_id . '";
    
    // Add cancel_active flag if needed
    let cancelInput = document.createElement("input");
    cancelInput.type = "hidden";
    cancelInput.name = "cancel_active";
    cancelInput.value = "1";
    
    let activeBotInput = document.createElement("input");
    activeBotInput.type = "hidden";
    activeBotInput.name = "active_bot_id";
    activeBotInput.value = "' . $active_bot_id . '";
    
    form.appendChild(input);
    form.appendChild(cancelInput);
    form.appendChild(activeBotInput);
    document.body.appendChild(form);
    form.submit();
});
</script>';
?>

<?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']);
}
?>