<?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';
    
    // Get bot performance before pausing
    $performance_sql = "SELECT total_trades, total_profit, success_rate FROM user_bot_subscriptions WHERE id = $bot_id";
    $performance_result = mysqli_query($conn, $performance_sql);
    $performance_data = mysqli_fetch_assoc($performance_result);
    
    // Update bot status to pending (paused)
    $update_sql = "UPDATE user_bot_subscriptions SET status = 'pending', updated_at = NOW() WHERE id = $bot_id";
    
    if (mysqli_query($conn, $update_sql)) {
        // Log activity
        logAdminActivity(
            'Bot Paused',
            "Paused bot #$bot_id for user " . $bot['username'] . " (" . $bot['email'] . ")",
            'Trading Bots',
            $bot_id,
            'user_bot_subscriptions'
        );
        
        // NOTIFICATION: Bot Paused (USER)
        $mail_subject = "Trading Bot Paused";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Important: <span class='user-name'>" . $bot['first_name'] . "</span>,</h2>
                            
                            <p class='message'>
                                ⚠️ <strong>Your trading bot has been paused by our admin team.</strong><br>
                                The bot will temporarily stop trading until further notice.
                            </p>

                            <!-- Bot Pause 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>Pause Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Paused By:</strong> " . $admin_name . " (Admin)<br>
                                    <strong>Bot Status:</strong> <span style='color: #ffc107; font-weight: bold;'>PAUSED</span><br>
                                    <strong>Previous Status:</strong> <span style='color: #28a745;'>ACTIVE</span>
                                </div>
                            </div>

                            <!-- Bot Performance Summary -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>📊 Bot Performance Summary</h4>
                                <p style='color: #856404;'>
                                    <strong>Total Trades:</strong> " . ($performance_data['total_trades'] ?? 0) . "<br>
                                    <strong>Total Profit:</strong> $" . number_format($performance_data['total_profit'] ?? 0, 2) . "<br>
                                    <strong>Success Rate:</strong> " . ($performance_data['success_rate'] ?? 0) . "%<br>
                                    <strong>Trading Balance Protected:</strong> $" . number_format($bot['trading_balance'], 2) . "
                                </p>
                            </div>

                            <!-- What Pausing Means -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>⏸️ What Happens Now?</h3>
                                <p style='color: #6c757d;'>While your bot is paused:</p>
                                <ul style='color: #6c757d;'>
                                    <li>No new trades will be executed</li>
                                    <li>Existing positions remain as they are</li>
                                    <li>Your trading balance is secured</li>
                                    <li>No profits will be generated during pause</li>
                                    <li>Bot will not analyze market data</li>
                                </ul>
                            </div>

                            <!-- Common Reasons for Pausing -->
                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #495057;'>🔍 Possible Reasons for Pausing</h4>
                                <p style='color: #495057;'>
                                    Bots may be paused for:<br>
                                    • System maintenance or upgrades<br>
                                    • Risk management during high volatility<br>
                                    • Performance review and optimization<br>
                                    • Compliance or security checks<br>
                                    • User request or account review
                                </p>
                            </div>

                            <!-- Action Required -->
                            <div style='background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0c5460;'>📞 Need More Information?</h4>
                                <p style='color: #0c5460;'>
                                    If you have questions about why your bot was paused:<br>
                                    <strong>Support Team:</strong> <a href='" . $myUrl . "/support.php' style='color: #0c5460;'>Contact Support</a><br>
                                    <strong>Response Time:</strong> Typically within 2-4 business hours
                                </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 Bot Status
                                </a>
                                <a href='" . $myUrl . "/support.php?category=trading' 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;'>
                                    Contact Trading Support
                                </a>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>We're here to help you get back to trading as soon as possible.</p>
                                <p class='support-text'>Your funds remain safe and secure during this pause.</p>
                            </div>
                        </div>";

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

        // NOTIFICATION: Bot Paused (ADMIN)
        $admin_mail_subject = "Trading Bot Paused - BOT-" . $bot_id;
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>Trading Bot Paused</h2>
                                
                                <p class='message'>
                                    A trading bot has been paused by an administrator.
                                </p>

                                <!-- Bot Pause Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>Bot ID:</strong> BOT-" . $bot_id . "<br>
                                        <strong>User ID:</strong> " . $bot['user_id'] . "<br>
                                        <strong>User Name:</strong> " . $bot['first_name'] . " " . $bot['last_name'] . "<br>
                                        <strong>User Email:</strong> " . $bot['email'] . "<br>
                                        <strong>Bot Plan:</strong> " . $bot['plan_name'] . "<br>
                                        <strong>Trading Balance:</strong> $" . number_format($bot['trading_balance'], 2) . "<br>
                                        <strong>Paused By:</strong> " . $admin_name . " (Admin ID: " . $admin_id . ")<br>
                                        <strong>Pause Date:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Previous Status:</strong> Active<br>
                                        <strong>New Status:</strong> Paused<br>
                                        <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "
                                    </div>
                                </div>

                                <!-- Bot Statistics -->
                                <div class='next-steps'>
                                    <h3 style='color: #2c3e50;'>🤖 Bot Statistics</h3>
                                    <p style='color: #6c757d;'>
                                        <strong>Subscription Start:</strong> " . date('F j, Y', strtotime($bot['subscription_start'])) . "<br>
                                        <strong>Days Active:</strong> " . round((time() - strtotime($bot['subscription_start'])) / (60 * 60 * 24)) . " days<br>
                                        <strong>Total Trades:</strong> " . ($performance_data['total_trades'] ?? 0) . "<br>
                                        <strong>Total Profit:</strong> $" . number_format($performance_data['total_profit'] ?? 0, 2) . "<br>
                                        <strong>Success Rate:</strong> " . ($performance_data['success_rate'] ?? 0) . "%
                                    </p>
                                </div>

                                <!-- Admin Actions -->
                                <div style='text-align: center; margin: 30px 0;'>
                                    <a href='" . $myUrl . "/admin/bot-subscriptions.php?id=" . $bot_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        View Bot Details
                                    </a>
                                    <a href='" . $myUrl . "/admin/users.php?id=" . $bot['user_id'] . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        View User Profile
                                    </a>
                                </div>

                                <!-- System Information -->
                                <div class='support-section'>
                                    <p class='support-text'>Action logged in admin activities.</p>
                                    <p style='color: #6c757d; font-size: 12px;'>
                                        <strong>Table:</strong> user_bot_subscriptions<br>
                                        <strong>Field Updated:</strong> status<br>
                                        <strong>Timestamp:</strong> " . date('Y-m-d H:i:s') . "
                                    </p>
                                </div>
                            </div>";

        // Send admin notification
        require_once("../proccess/admin_mailer.php");
        
        echo json_encode(['success' => true, 'message' => 'Bot paused successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to pause bot']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid bot ID']);
}
?>