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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $admin_pin = "1234"; // Same PIN as before
    
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
        $bot_id = isset($_POST['bot_id']) ? intval($_POST['bot_id']) : 0;
        
        switch ($action_type) {
            case 'stop_bot':
                if ($bot_id > 0) {
                    // Get bot details
                    $sql = "SELECT s.*, u.username, u.email, u.first_name, u.last_name, p.plan_name, p.daily_roi_percentage 
                            FROM user_bot_subscriptions s
                            LEFT JOIN users u ON s.user_id = u.id
                            LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                            WHERE s.id = $bot_id";
                    $result = mysqli_query($conn, $sql);
                    $bot = mysqli_fetch_assoc($result);
                    
                    // Get admin details for notification
                    $admin_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 1;
                    $admin_name = $_SESSION['admin_name'] ?? $_SESSION['first_name'] ?? 'System Administrator';
                    
                    // Get bot performance metrics
                    $total_profit = floatval($bot['total_profit'] ?? 0);
                    $trading_balance = floatval($bot['trading_balance'] ?? 0);
                    $success_rate = floatval($bot['success_rate'] ?? 0);
                    $total_trades = intval($bot['total_trades'] ?? 0);
                    
                    // Calculate bot runtime
                    $start_date = $bot['subscription_start'];
                    $end_date = date('Y-m-d');
                    $runtime_days = round((strtotime($end_date) - strtotime($start_date)) / (60 * 60 * 24), 1);
                    
                    // Update bot status to cancelled
                    $update_sql = "UPDATE user_bot_subscriptions SET status = 'cancelled', updated_at = NOW() WHERE id = $bot_id";
                    
                    if (mysqli_query($conn, $update_sql)) {
                        // Log activity
                        logAdminActivity(
                            'Bot Stopped',
                            "Stopped bot #$bot_id for user " . $bot['username'] . " (" . $bot['email'] . ")",
                            'Trading Bots',
                            $bot_id,
                            'user_bot_subscriptions'
                        );
                        
                        // Unlock user funds
                        $unlock_sql = "UPDATE users SET fund_balance = fund_balance + " . $bot['trading_balance'] . " WHERE id = " . $bot['user_id'];
                        mysqli_query($conn, $unlock_sql);
                        
                        // NOTIFICATION: Bot Stopped by Admin (USER)
                        $mail_subject = "Trading Bot Stopped by Admin";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $bot['first_name'] . "</span>,</h2>
                                            
                                            <p class='message'>
                                                Your trading bot has been <strong>stopped by our admin team</strong>. The bot is no longer active and your funds have been unlocked.
                                            </p>

                                            <!-- Bot Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Bot ID:</strong> BOT-" . $bot_id . "<br>
                                                    <strong>Bot Plan:</strong> " . $bot['plan_name'] . "<br>
                                                    <strong>Original Trading Balance:</strong> $" . number_format($trading_balance, 2) . "<br>
                                                    <strong>Total Profit Generated:</strong> $" . number_format($total_profit, 2) . "<br>
                                                    <strong>Total Trades:</strong> " . $total_trades . "<br>
                                                    <strong>Success Rate:</strong> " . $success_rate . "%<br>
                                                    <strong>Runtime:</strong> " . $runtime_days . " days<br>
                                                    <strong>Stopped By:</strong> " . $admin_name . " (Admin)<br>
                                                    <strong>Stop Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Bot Status:</strong> <span style='color: #dc3545; font-weight: bold;'>CANCELLED</span>
                                                </div>
                                            </div>

                                            <!-- Performance Summary -->
                                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #495057;'>📊 Bot Performance Summary</h4>
                                                <p style='color: #495057;'>
                                                    <strong>Initial Investment:</strong> $" . number_format($trading_balance, 2) . "<br>
                                                    <strong>Final Return:</strong> $" . number_format($trading_balance + $total_profit, 2) . "<br>
                                                    <strong>Net Profit/Loss:</strong> <span style='color: " . ($total_profit >= 0 ? '#28a745' : '#dc3545') . ";'>" . ($total_profit >= 0 ? '+' : '') . "$" . number_format($total_profit, 2) . "</span><br>
                                                    <strong>ROI:</strong> " . ($trading_balance > 0 ? round(($total_profit / $trading_balance) * 100, 2) : 0) . "%<br>
                                                    <strong>Daily Average Profit:</strong> $" . ($runtime_days > 0 ? number_format($total_profit / $runtime_days, 2) : '0.00') . "
                                                </p>
                                            </div>

                                            <!-- Funds Unlocked -->
                                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #0056b3;'>💰 Funds Unlocked</h4>
                                                <p style='color: #0056b3;'>
                                                    <strong>Amount Unlocked:</strong> $" . number_format($trading_balance + $total_profit, 2) . "<br>
                                                    <strong>Added to:</strong> Your Fund Balance<br>
                                                    <strong>Status:</strong> Available for withdrawal or new bot subscription
                                                </p>
                                            </div>

                                            <!-- Reason for Stopping -->
                                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #856404;'>ℹ️ Important Information</h4>
                                                <p style='color: #856404;'>
                                                    <strong>Why was my bot stopped?</strong><br>
                                                    Bots may be stopped by admin for the following reasons:<br>
                                                    • Policy compliance review<br>
                                                    • System maintenance or updates<br>
                                                    • Risk management protocols<br>
                                                    • Your account verification status<br>
                                                    • Detected unusual activity<br><br>
                                                    
                                                    If you have questions, please contact our support team.
                                                </p>
                                            </div>

                                            <!-- Next Steps -->
                                            <div class='next-steps'>
                                                <h3 style='color: #2c3e50;'>📋 What You Can Do Now</h3>
                                                <ul style='color: #6c757d;'>
                                                    <li><strong>Subscribe to another bot:</strong> Your unlocked funds are ready</li>
                                                    <li><strong>Withdraw funds:</strong> Transfer to your available balance</li>
                                                    <li><strong>Contact support:</strong> Get more information about this action</li>
                                                    <li><strong>View transaction history:</strong> See all bot activities</li>
                                                </ul>
                                            </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 Available Bots
                                                </a>
                                                <a href='" . $myUrl . "/withdraw.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #28a745; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                                    Withdraw Funds
                                                </a>
                                                <a href='" . $myUrl . "/support.php?subject=Bot%20Stopped%20-%20BOT-" . $bot_id . "' 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 Support
                                                </a>
                                            </div>

                                            <!-- Support Section -->
                                            <div class='support-section'>
                                                <p class='support-text'>We apologize for any inconvenience caused.</p>
                                                <a href='" . $myUrl . "/contact.php' class='support-link'>Contact Our Support Team</a>
                                            </div>
                                        </div>";

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

                        // NOTIFICATION: Bot Stopped by Admin (ADMIN)
                        $admin_mail_subject = "Bot Stopped - User Notification Sent";
                        $admin_mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Bot Stopped by Admin</h2>
                                                
                                                <p class='message'>
                                                    A trading bot has been manually stopped by an administrator. The user has been notified.
                                                </p>

                                                <!-- Bot Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Bot ID:</strong> BOT-" . $bot_id . "<br>
                                                        <strong>Bot Plan:</strong> " . $bot['plan_name'] . "<br>
                                                        <strong>User ID:</strong> " . $bot['user_id'] . "<br>
                                                        <strong>Username:</strong> " . $bot['username'] . "<br>
                                                        <strong>User Email:</strong> " . $bot['email'] . "<br>
                                                        <strong>Trading Balance:</strong> $" . number_format($trading_balance, 2) . "<br>
                                                        <strong>Total Profit:</strong> $" . number_format($total_profit, 2) . "<br>
                                                        <strong>Runtime:</strong> " . $runtime_days . " days<br>
                                                        <strong>Stopped By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                        <strong>Stop Time:</strong> " . date('F j, Y g:i A') . "<br>
                                                        <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>CANCELLED</span>
                                                    </div>
                                                </div>

                                                <!-- Action Summary -->
                                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #721c24;'>⚙️ Action Summary</h4>
                                                    <p style='color: #721c24;'>
                                                        <strong>✓ Bot status updated to 'cancelled'</strong><br>
                                                        <strong>✓ Funds unlocked: $" . number_format($trading_balance + $total_profit, 2) . "</strong><br>
                                                        <strong>✓ User notified via email</strong><br>
                                                        <strong>✓ Admin activity logged</strong>
                                                    </p>
                                                </div>

                                                <!-- Admin Actions -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/admin/bot-details.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>

                                                <!-- Notification Status -->
                                                <div class='support-section'>
                                                    <p class='support-text'>User notification sent successfully.</p>
                                                    <p style='color: #6c757d; font-size: 12px;'>
                                                        <strong>Notification Time:</strong> " . date('Y-m-d H:i:s') . "<br>
                                                        <strong>Notification Type:</strong> Bot Stopped Alert<br>
                                                        <strong>Template:</strong> mail_sender.php
                                                    </p>
                                                </div>
                                            </div>";

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Bot stopped successfully and funds unlocked! User has been notified.";
                    } else {
                        $error = "Failed to stop bot.";
                    }
                }
                break;
        }
    }
}


// Set default date range
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
$bot_plan = isset($_GET['bot_plan']) ? intval($_GET['bot_plan']) : 0;
$status = isset($_GET['status']) ? $_GET['status'] : '';

// Get all bot plans for filter
$plans_sql = "SELECT id, plan_name FROM trading_bot_plans WHERE is_active = 1 ORDER BY sort_order";
$plans_result = mysqli_query($conn, $plans_sql);

// Build query for active subscriptions
$sql = "SELECT s.*, p.plan_name, p.daily_roi_percentage, p.trading_accuracy, 
               u.username, u.email,
               DATEDIFF(s.subscription_end, CURDATE()) as days_remaining
        FROM user_bot_subscriptions s
        LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
        LEFT JOIN users u ON s.user_id = u.id
        WHERE 1=1";

if ($status) {
    $sql .= " AND s.status = '$status'";
} else {
    $sql .= " AND s.status IN ('active', 'pending')";
}

if ($bot_plan > 0) {
    $sql .= " AND s.bot_plan_id = $bot_plan";
}

if ($start_date && $end_date) {
    $sql .= " AND s.subscription_start BETWEEN '$start_date' AND '$end_date'";
}

$sql .= " ORDER BY s.created_at DESC";

$result = mysqli_query($conn, $sql);

// Calculate overall statistics
$stats_sql = "SELECT 
                COUNT(*) as total_subscriptions,
                SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_subscriptions,
                SUM(CASE WHEN status = 'expired' THEN 1 ELSE 0 END) as expired_subscriptions,
                SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_subscriptions,
                SUM(trading_balance) as total_trading_balance,
                SUM(total_profit) as total_profit_generated,
                AVG(success_rate) as avg_success_rate
              FROM user_bot_subscriptions";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);

// Get profit by bot plan
$plan_profit_sql = "SELECT p.plan_name, 
                           COUNT(s.id) as subscription_count,
                           SUM(s.total_profit) as total_profit,
                           AVG(s.success_rate) as avg_success_rate
                    FROM trading_bot_plans p
                    LEFT JOIN user_bot_subscriptions s ON p.id = s.bot_plan_id
                    WHERE s.status IN ('active', 'expired')
                    GROUP BY p.id
                    ORDER BY p.sort_order";
$plan_profit_result = mysqli_query($conn, $plan_profit_sql);

// Get daily profit data for chart
$daily_profit_sql = "SELECT DATE(created_at) as date, 
                            SUM(amount) as total_profit
                     FROM bot_transactions 
                     WHERE transaction_type = 'profit' 
                     AND DATE(created_at) BETWEEN '$start_date' AND '$end_date'
                     GROUP BY DATE(created_at)
                     ORDER BY date";
$daily_profit_result = mysqli_query($conn, $daily_profit_sql);

// Get success rate by bot plan
$success_rate_sql = "SELECT p.plan_name,
                            COUNT(s.id) as trade_count,
                            AVG(s.success_rate) as avg_success_rate
                     FROM user_bot_subscriptions s
                     LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                     WHERE s.status IN ('active', 'expired')
                     AND s.success_rate > 0
                     GROUP BY p.id
                     ORDER BY p.sort_order";
$success_rate_result = mysqli_query($conn, $success_rate_sql);
?>

<!DOCTYPE html>
<html lang="en">
	
	<body class="hold-transition dark-skin sidebar-mini theme-primary fixed">
		
		<div class="wrapper">
		  	<div id="loader"></div>
		  	
		  <?php include('includes/header.php') ?>

		  <?php include('includes/sidebar.php') ?>

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-chart-line me-2"></i>AI Bot Performance Analytics</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exportModal">
												<i class="fas fa-download me-1"></i> Export Report
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-3">
												<div class="form-group">
													<label>Start Date</label>
													<input type="date" class="form-control" id="startDate" value="<?php echo $start_date; ?>">
												</div>
											</div>
											<div class="col-md-3">
												<div class="form-group">
													<label>End Date</label>
													<input type="date" class="form-control" id="endDate" value="<?php echo $end_date; ?>">
												</div>
											</div>
											<div class="col-md-3">
												<div class="form-group">
													<label>Bot Plan</label>
													<select class="form-control" id="botPlanFilter">
														<option value="0">All Plans</option>
														<?php while ($plan = mysqli_fetch_assoc($plans_result)): ?>
															<option value="<?php echo $plan['id']; ?>" <?php echo $bot_plan == $plan['id'] ? 'selected' : ''; ?>>
																<?php echo htmlspecialchars($plan['plan_name']); ?>
															</option>
														<?php endwhile; ?>
													</select>
												</div>
											</div>
											<div class="col-md-3">
												<div class="form-group">
													<label>Status</label>
													<select class="form-control" id="statusFilter">
														<option value="">All Status</option>
														<option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
														<option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>Pending</option>
														<option value="expired" <?php echo $status == 'expired' ? 'selected' : ''; ?>>Expired</option>
														<option value="cancelled" <?php echo $status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
													</select>
												</div>
											</div>
										</div>
										<div class="row mb-20">
											<div class="col-md-12">
												<button class="btn btn-primary" onclick="applyFilters()">
													<i class="fas fa-filter me-1"></i> Apply Filters
												</button>
												<button class="btn btn-secondary" onclick="resetFilters()">
													<i class="fas fa-redo me-1"></i> Reset
												</button>
											</div>
										</div>
										
										<!-- Performance Stats Cards -->
										<div class="row mb-30">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['total_subscriptions'] ?: '0'; ?></h1>
														<p class="text-white mb-0">Total Subscriptions</p>
														<small class="text-white-50"><?php echo $stats['active_subscriptions']; ?> Active</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_profit_generated'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Profit Generated</p>
														<small class="text-white-50">All Time</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo number_format($stats['avg_success_rate'] ?: 0, 1); ?>%</h1>
														<p class="text-white mb-0">Average Success Rate</p>
														<small class="text-white-50">Across all bots</small>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_trading_balance'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Trading Balance</p>
														<small class="text-white-50">Currently deployed</small>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Charts Row -->
										<div class="row mb-30">
											<!-- Daily Profit Chart -->
											<div class="col-xl-8 col-lg-6">
												<div class="box b-1">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-line me-2"></i>Daily Profit Trend</h5>
													</div>
													<div class="box-body">
														<canvas id="dailyProfitChart" height="300"></canvas>
													</div>
												</div>
											</div>
											
											<!-- Success Rate by Plan -->
											<div class="col-xl-4 col-lg-6">
												<div class="box b-1">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-pie me-2"></i>Success Rate by Plan</h5>
													</div>
													<div class="box-body">
														<canvas id="successRateChart" height="300"></canvas>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Detailed Performance Table -->
										<div class="row">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-table me-2"></i>Bot Performance Details</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover table-bordered" id="performanceTable">
																<thead class="bg-light">
																	<tr>
																		<th>Bot ID</th>
																		<th>User</th>
																		<th>Plan</th>
																		<th>Status</th>
																		<th>Trading Balance</th>
																		<th>Total Profit</th>
																		<th>Success Rate</th>
																		<th>ROI %</th>
																		<th>Days Remaining</th>
																		<th>Actions</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($result) > 0): ?>
																		<?php while ($subscription = mysqli_fetch_assoc($result)): ?>
																			<?php
																			// Calculate ROI
																			$roi = $subscription['trading_balance'] > 0 ? 
																				   ($subscription['total_profit'] / $subscription['trading_balance']) * 100 : 0;
																			
																			// Status colors
																			$status_colors = [
																				'active' => 'success',
																				'pending' => 'warning',
																				'expired' => 'secondary',
																				'cancelled' => 'danger'
																			];
																			$status_color = $status_colors[$subscription['status']] ?: 'secondary';
																			
																			// ROI color
																			$roi_color = $roi > 0 ? 'success' : ($roi < 0 ? 'danger' : 'secondary');
																			?>
																			<tr>
																				<td><?php echo $subscription['id']; ?></td>
																				<td>
																					<p class="mb-0 fw-500"><?php echo htmlspecialchars($subscription['username']); ?></p>
																					<small class="text-mute"><?php echo htmlspecialchars($subscription['email']); ?></small>
																				</td>
																				<td>
																					<span class="badge bg-primary"><?php echo htmlspecialchars($subscription['plan_name']); ?></span>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $status_color; ?>">
																						<?php echo ucfirst($subscription['status']); ?>
																					</span>
																				</td>
																				<td class="fw-500">$<?php echo number_format($subscription['trading_balance'], 2); ?></td>
																				<td>
																					<span class="fw-500 <?php echo $subscription['total_profit'] > 0 ? 'text-success' : 'text-danger'; ?>">
																						$<?php echo number_format($subscription['total_profit'], 2); ?>
																					</span>
																				</td>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="progress flex-grow-1 me-2" style="height: 8px;">
																							<div class="progress-bar bg-success" 
																								 style="width: <?php echo min($subscription['success_rate'], 100); ?>%">
																							</div>
																						</div>
																						<span class="fw-500"><?php echo number_format($subscription['success_rate'], 1); ?>%</span>
																					</div>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $roi_color; ?>">
																						<?php echo number_format($roi, 2); ?>%
																					</span>
																				</td>
																				<td>
																					<?php if ($subscription['status'] == 'active'): ?>
																						<span class="badge bg-<?php echo $subscription['days_remaining'] > 7 ? 'success' : 'warning'; ?>">
																							<?php echo $subscription['days_remaining']; ?> days
																						</span>
																					<?php else: ?>
																						<span class="text-mute">-</span>
																					<?php endif; ?>
																				</td>
																				<td>
																					<div class="btn-group">
																						<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																							<i class="fas fa-cog"></i>
																						</button>
																						<div class="dropdown-menu">
																							<a class="dropdown-item" href="view_bot_details.php?id=<?php echo $subscription['id']; ?>">
																								<i class="fas fa-eye me-2"></i> View Details
																							</a>
																							<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#botStatsModal" data-bot-id="<?php echo $subscription['id']; ?>">
																								<i class="fas fa-chart-bar me-2"></i> Performance Stats
																							</a>
																							<?php if ($subscription['status'] == 'active'): ?>
																								<a class="dropdown-item text-warning" href="#" onclick="pauseBot(<?php echo $subscription['id']; ?>)">
																									<i class="fas fa-pause me-2"></i> Pause Bot
																								</a>
																							<?php elseif ($subscription['status'] == 'pending'): ?>
																								<a class="dropdown-item text-success" href="#" onclick="activateBot(<?php echo $subscription['id']; ?>)">
																									<i class="fas fa-play me-2"></i> Activate Bot
																								</a>
																							<?php endif; ?>
																							<div class="dropdown-divider"></div>
																							<a class="dropdown-item text-danger" href="#" onclick="stopBot(<?php echo $subscription['id']; ?>)">
																								<i class="fas fa-stop me-2"></i> Stop Bot
																							</a>
																						</div>
																					</div>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="10" class="text-center py-20">
																				<i class="fas fa-robot fa-2x text-mute mb-3"></i>
																				<h5>No bot subscriptions found</h5>
																				<p class="text-mute">Try adjusting your filters</p>
																			</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Plan-wise Profit Analysis -->
										<div class="row mt-30">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-bar me-2"></i>Plan-wise Performance Analysis</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Bot Plan</th>
																		<th>Active Subscriptions</th>
																		<th>Total Profit</th>
																		<th>Avg. Success Rate</th>
																		<th>Avg. ROI</th>
																		<th>Performance</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($plan_profit_result) > 0): ?>
																		<?php while ($plan = mysqli_fetch_assoc($plan_profit_result)): ?>
																			<?php
																			$performance = $plan['avg_success_rate'] > 90 ? 'Excellent' : 
																						  ($plan['avg_success_rate'] > 80 ? 'Good' : 
																						  ($plan['avg_success_rate'] > 70 ? 'Average' : 'Poor'));
																			$performance_color = $plan['avg_success_rate'] > 90 ? 'success' : 
																								($plan['avg_success_rate'] > 80 ? 'info' : 
																								($plan['avg_success_rate'] > 70 ? 'warning' : 'danger'));
																			?>
																			<tr>
																				<td class="fw-500"><?php echo htmlspecialchars($plan['plan_name']); ?></td>
																				<td><?php echo $plan['subscription_count']; ?></td>
																				<td class="fw-500 text-success">$<?php echo number_format($plan['total_profit'], 2); ?></td>
																				<td>
																					<div class="d-flex align-items-center">
																						<div class="progress flex-grow-1 me-2" style="height: 8px;">
																							<div class="progress-bar bg-info" style="width: <?php echo min($plan['avg_success_rate'], 100); ?>%"></div>
																						</div>
																						<span><?php echo number_format($plan['avg_success_rate'], 1); ?>%</span>
																					</div>
																				</td>
																				<td>
																					<?php
																					$avg_roi = $plan['total_profit'] > 0 ? ($plan['total_profit'] / ($plan['subscription_count'] * 1000)) * 100 : 0;
																					?>
																					<span class="badge bg-<?php echo $avg_roi > 0 ? 'success' : 'danger'; ?>">
																						<?php echo number_format($avg_roi, 2); ?>%
																					</span>
																				</td>
																				<td>
																					<span class="badge bg-<?php echo $performance_color; ?>">
																						<?php echo $performance; ?>
																					</span>
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="6" class="text-center py-20">No plan performance data available</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Bot Stats -->
		<div class="modal fade" id="botStatsModal" tabindex="-1" aria-labelledby="botStatsModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="botStatsModalLabel">Bot Performance Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="botStatsContent">
						<!-- Stats will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Export -->
		<div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="exportModalLabel">Export Performance Report</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body">
						<div class="mb-3">
							<label class="form-label">Export Format</label>
							<select class="form-control" id="exportFormat">
								<option value="csv">CSV</option>
								<option value="excel">Excel</option>
								<option value="pdf">PDF</option>
							</select>
						</div>
						<div class="mb-3">
							<label class="form-label">Date Range</label>
							<div class="row">
								<div class="col-md-6">
									<input type="date" class="form-control" id="exportStartDate" value="<?php echo $start_date; ?>">
								</div>
								<div class="col-md-6">
									<input type="date" class="form-control" id="exportEndDate" value="<?php echo $end_date; ?>">
								</div>
							</div>
						</div>
						<div class="mb-3">
							<label class="form-label">Include Data</label>
							<div class="form-check">
								<input class="form-check-input" type="checkbox" id="includeStats" checked>
								<label class="form-check-label" for="includeStats">Performance Statistics</label>
							</div>
							<div class="form-check">
								<input class="form-check-input" type="checkbox" id="includeDetails" checked>
								<label class="form-check-label" for="includeDetails">Bot Details</label>
							</div>
							<div class="form-check">
								<input class="form-check-input" type="checkbox" id="includeCharts">
								<label class="form-check-label" for="includeCharts">Charts (PDF only)</label>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
						<button type="button" class="btn btn-primary" onclick="exportReport()">Export Report</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Stop Bot Form -->
		<form method="POST" id="stopBotForm" style="display: none;">
			<input type="hidden" name="action_type" value="stop_bot">
			<input type="hidden" name="bot_id" id="stopBotId">
			<input type="hidden" name="admin_pin" id="stopBotPin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- Chart.js -->
		<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
		
		<script>
		$(document).ready(function() {
			// Initialize DataTable
			$('#performanceTable').DataTable({
				"pageLength": 25,
				"order": [[0, 'desc']],
				"language": {
					"search": "Search:",
					"lengthMenu": "Show _MENU_ entries",
					"info": "Showing _START_ to _END_ of _TOTAL_ entries",
					"paginate": {
						"first": "First",
						"last": "Last",
						"next": "Next",
						"previous": "Previous"
					}
				}
			});
			
			// Initialize charts
			initializeCharts();
			
			// Bot Stats Modal
			$('#botStatsModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var botId = button.data('bot-id');
				loadBotStats(botId);
			});
			
			// Auto-refresh charts every 60 seconds
			setInterval(function() {
				updateCharts();
			}, 60000);
		});
		
		// Initialize Charts
		function initializeCharts() {
			// Daily Profit Chart
			const dailyProfitCtx = document.getElementById('dailyProfitChart').getContext('2d');
			window.dailyProfitChart = new Chart(dailyProfitCtx, {
				type: 'line',
				data: {
					labels: [],
					datasets: [{
						label: 'Daily Profit',
						data: [],
						borderColor: '#667eea',
						backgroundColor: 'rgba(102, 126, 234, 0.1)',
						borderWidth: 2,
						fill: true,
						tension: 0.4
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							display: true
						},
						tooltip: {
							callbacks: {
								label: function(context) {
									return 'Profit: $' + context.parsed.y.toFixed(2);
								}
							}
						}
					},
					scales: {
						y: {
							beginAtZero: true,
							ticks: {
								callback: function(value) {
									return '$' + value;
								}
							}
						}
					}
				}
			});
			
			// Success Rate Chart
			const successRateCtx = document.getElementById('successRateChart').getContext('2d');
			window.successRateChart = new Chart(successRateCtx, {
				type: 'doughnut',
				data: {
					labels: [],
					datasets: [{
						data: [],
						backgroundColor: [
							'#667eea',
							'#f093fb',
							'#4facfe',
							'#43e97b',
							'#fa709a'
						],
						borderWidth: 1
					}]
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							position: 'bottom'
						}
					}
				}
			});
			
			// Load initial chart data
			loadChartData();
		}
		
		// Load Chart Data
		function loadChartData() {
			// Load daily profit data
			$.ajax({
				url: 'ajax/get_daily_profit.php',
				type: 'GET',
				data: {
					start_date: $('#startDate').val(),
					end_date: $('#endDate').val()
				},
				success: function(data) {
					var result = JSON.parse(data);
					if (result.success) {
						window.dailyProfitChart.data.labels = result.labels;
						window.dailyProfitChart.data.datasets[0].data = result.profits;
						window.dailyProfitChart.update();
					}
				}
			});
			
			// Load success rate data
			$.ajax({
				url: 'ajax/get_success_rate_data.php',
				type: 'GET',
				success: function(data) {
					var result = JSON.parse(data);
					if (result.success) {
						window.successRateChart.data.labels = result.labels;
						window.successRateChart.data.datasets[0].data = result.success_rates;
						window.successRateChart.update();
					}
				}
			});
		}
		
		// Update Charts
		function updateCharts() {
			loadChartData();
			
			// Show update notification
			Swal.fire({
				toast: true,
				position: 'top-end',
				icon: 'success',
				title: 'Charts Updated',
				showConfirmButton: false,
				timer: 1500
			});
		}
		
		// Apply Filters
		function applyFilters() {
			var startDate = $('#startDate').val();
			var endDate = $('#endDate').val();
			var botPlan = $('#botPlanFilter').val();
			var status = $('#statusFilter').val();
			
			var url = 'bot_performance.php?start_date=' + startDate + 
					 '&end_date=' + endDate + 
					 '&bot_plan=' + botPlan + 
					 '&status=' + status;
			
			window.location.href = url;
		}
		
		// Reset Filters
		function resetFilters() {
			$('#startDate').val('<?php echo date('Y-m-d', strtotime('-30 days')); ?>');
			$('#endDate').val('<?php echo date('Y-m-d'); ?>');
			$('#botPlanFilter').val('0');
			$('#statusFilter').val('');
			applyFilters();
		}
		
		// Load Bot Stats
		function loadBotStats(botId) {
			$.ajax({
				url: 'ajax/get_bot_stats.php',
				type: 'GET',
				data: { bot_id: botId },
				success: function(data) {
					$('#botStatsContent').html(data);
				}
			});
		}
		
		// Pause Bot
		function pauseBot(botId) {
			Swal.fire({
				title: 'Pause Bot?',
				text: 'The bot will stop trading but subscription will remain active.',
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Yes, pause it!'
			}).then((result) => {
				if (result.isConfirmed) {
					$.ajax({
						url: 'ajax/pause_bot.php',
						type: 'POST',
						data: { bot_id: botId },
						success: function(response) {
							var result = JSON.parse(response);
							if (result.success) {
								Swal.fire(
									'Paused!',
									'The bot has been paused.',
									'success'
								).then(() => {
									location.reload();
								});
							} else {
								Swal.fire(
									'Error!',
									result.message,
									'error'
								);
							}
						}
					});
				}
			});
		}
		
		// Activate Bot
		function activateBot(botId) {
			Swal.fire({
				title: 'Activate Bot?',
				text: 'The bot will start trading immediately.',
				icon: 'question',
				showCancelButton: true,
				confirmButtonColor: '#3085d6',
				cancelButtonColor: '#d33',
				confirmButtonText: 'Yes, activate it!'
			}).then((result) => {
				if (result.isConfirmed) {
					$.ajax({
						url: 'ajax/activate_bot.php',
						type: 'POST',
						data: { bot_id: botId },
						success: function(response) {
							var result = JSON.parse(response);
							if (result.success) {
								Swal.fire(
									'Activated!',
									'The bot has been activated.',
									'success'
								).then(() => {
									location.reload();
								});
							} else {
								Swal.fire(
									'Error!',
									result.message,
									'error'
								);
							}
						}
					});
				}
			});
		}
		
		// Stop Bot with PIN confirmation
		function stopBot(botId) {
			Swal.fire({
				title: 'Stop Bot?',
				html: `
					<p>This will permanently stop the bot and cancel the subscription.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Stop Bot',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the stop bot form
					document.getElementById('stopBotId').value = botId;
					document.getElementById('stopBotPin').value = result.value.pin;
					document.getElementById('stopBotForm').submit();
				}
			});
		}
		
		// Export Report
		function exportReport() {
			var format = $('#exportFormat').val();
			var startDate = $('#exportStartDate').val();
			var endDate = $('#exportEndDate').val();
			var includeStats = $('#includeStats').is(':checked') ? 1 : 0;
			var includeDetails = $('#includeDetails').is(':checked') ? 1 : 0;
			var includeCharts = $('#includeCharts').is(':checked') ? 1 : 0;
			
			var url = 'ajax/export_bot_performance.php?format=' + format +
					 '&start_date=' + startDate +
					 '&end_date=' + endDate +
					 '&include_stats=' + includeStats +
					 '&include_details=' + includeDetails +
					 '&include_charts=' + includeCharts;
			
			window.open(url, '_blank');
			$('#exportModal').modal('hide');
		}
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_bot_performance_stats.php',
				type: 'GET',
				data: {
					start_date: '<?php echo $start_date; ?>',
					end_date: '<?php echo $end_date; ?>',
					bot_plan: '<?php echo $bot_plan; ?>',
					status: '<?php echo $status; ?>'
				},
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total_subscriptions);
						$('.bg-gradient-success .fw-500').text('$' + stats.total_profit);
						$('.bg-gradient-warning .fw-500').text(stats.avg_success_rate + '%');
						$('.bg-gradient-info .fw-500').text('$' + stats.total_balance);
					}
				}
			});
		}, 30000); // 30 seconds
		</script>
		
		<style>
		.box {
			border-radius: 10px;
			overflow: hidden;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.progress {
			border-radius: 10px;
		}
		</style>
		
	</body>
</html>