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

$bot_id = isset($_POST['bot_id']) ? intval($_POST['bot_id']) : 0;

if ($bot_id > 0) {
    // Get bot details
    $sql = "SELECT s.*, u.username, u.email, u.first_name, u.last_name, tbp.plan_name, tbp.daily_roi_percentage 
            FROM user_bot_subscriptions s
            LEFT JOIN users u ON s.user_id = u.id
            LEFT JOIN trading_bot_plans tbp ON s.bot_plan_id = tbp.id
            WHERE s.id = $bot_id";
    $result = mysqli_query($conn, $sql);
    $bot = mysqli_fetch_assoc($result);
    
    // Get admin details for notification
    $admin_id = $_SESSION['user_id'] ?? 0;
    $adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
    $adminData = mysqli_fetch_assoc($adminQuery);
    $admin_name = $adminData['first_name'] ?? 'Administrator';
    
    // Update bot status to active
    $update_sql = "UPDATE user_bot_subscriptions SET status = 'active', updated_at = NOW() WHERE id = $bot_id";
    
    if (mysqli_query($conn, $update_sql)) {
        // Log activity
        logAdminActivity(
            'Bot Activated',
            "Activated bot #$bot_id for user " . $bot['username'] . " (" . $bot['email'] . ")",
            'Trading Bots',
            $bot_id,
            'user_bot_subscriptions'
        );
        
        // NOTIFICATION: Bot Activated (USER)
        $mail_subject = "Trading Bot Activated - Ready to Trade!";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Congratulations <span class='user-name'>" . $bot['first_name'] . "</span>! 🎉</h2>
                            
                            <p class='message'>
                                Great news! Your trading bot has been <strong>activated by our admin team</strong> and is now ready to start trading!
                            </p>

                            <!-- Bot Activation Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Bot Subscription ID:</strong> BOT-" . $bot_id . "<br>
                                    <strong>Bot Plan:</strong> " . $bot['plan_name'] . "<br>
                                    <strong>Trading Balance:</strong> $" . number_format($bot['trading_balance'], 2) . "<br>
                                    <strong>Daily ROI:</strong> " . $bot['daily_roi_percentage'] . "%<br>
                                    <strong>Activation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Activated By:</strong> " . $admin_name . " (Admin)<br>
                                    <strong>Bot Status:</strong> <span style='color: #28a745; font-weight: bold;'>ACTIVE & TRADING</span>
                                </div>
                            </div>

                            <!-- What Happens Now -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>🤖 Your Bot is Now Live!</h3>
                                <p style='color: #6c757d;'>Here's what to expect:</p>
                                <ul style='color: #6c757d;'>
                                    <li>AI will start analyzing market data immediately</li>
                                    <li>Trades will be executed based on AI signals</li>
                                    <li>Profits will be added to your available balance daily</li>
                                    <li>You can monitor performance in real-time</li>
                                    <li>First profits should appear within 24 hours</li>
                                </ul>
                            </div>

                            <!-- Risk Management -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>📊 Risk Management</h4>
                                <p style='color: #856404;'>
                                    <strong>Your bot includes:</strong><br>
                                    • Stop-loss protection<br>
                                    • Risk-adjusted position sizing<br>
                                    • Market volatility filters<br>
                                    • 24/7 monitoring by our AI system
                                </p>
                            </div>

                            <!-- Action Buttons -->
                            <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: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View Active Bot
                                </a>
                                <a href='" . $myUrl . "/dashboard.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Go to Dashboard
                                </a>
                            </div>

                            <!-- Support Information -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>💡 Need Help?</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Bot Documentation:</strong> <a href='" . $myUrl . "/bot-guide.php' style='color: #0056b3;'>View Bot Guide</a><br>
                                    <strong>Performance Metrics:</strong> Available in your dashboard<br>
                                    <strong>Support:</strong> <a href='" . $myUrl . "/support.php' style='color: #0056b3;'>Contact Trading Support</a>
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Happy trading! 🚀</p>
                                <p class='support-text'>May the markets be in your favor!</p>
                            </div>
                        </div>";

        // Send user notification
        $user_email = $bot['email'];
        $first_name = $bot['first_name'];
        require_once("../proccess/mail_sender.php");

        echo json_encode(['success' => true, 'message' => 'Bot activated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to activate bot']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid bot ID']);
}
?>