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

// Check admin session
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';
$admin_role = $_SESSION['admin_role'] ?: 'admin';

// Get admin email for notification
$adminQuery = mysqli_query($conn, "SELECT email FROM users WHERE id='$admin_id'");
$adminData = mysqli_fetch_assoc($adminQuery);
$admin_email = $adminData['email'] ?? 'admin@system.com';

// PIN for confirmation
$admin_pin = "1234"; // Same PIN as before

// Handle actions
$action = isset($_GET['action']) ? $_GET['action'] : '';
$plan_id = isset($_GET['id']) ? intval($_GET['plan_id']) : 0;

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'add_plan':
                $plan_name = mysqli_real_escape_string($conn, $_POST['plan_name']);
                $plan_slug = mysqli_real_escape_string($conn, $_POST['plan_slug']);
                $plan_description = mysqli_real_escape_string($conn, $_POST['plan_description']);
                $subscription_fee = floatval($_POST['subscription_fee']);
                $min_trading_balance = floatval($_POST['min_trading_balance']);
                $max_trading_balance = !empty($_POST['max_trading_balance']) ? floatval($_POST['max_trading_balance']) : NULL;
                $daily_roi_percentage = floatval($_POST['daily_roi_percentage']);
                $trading_accuracy = floatval($_POST['trading_accuracy']);
                $markets_covered = intval($_POST['markets_covered']);
                $support_level = mysqli_real_escape_string($conn, $_POST['support_level']);
                $strategy_types = intval($_POST['strategy_types']);
                $has_machine_learning = isset($_POST['has_machine_learning']) ? 1 : 0;
                $has_multi_market = isset($_POST['has_multi_market']) ? 1 : 0;
                $has_strategy_blending = isset($_POST['has_strategy_blending']) ? 1 : 0;
                $has_dedicated_manager = isset($_POST['has_dedicated_manager']) ? 1 : 0;
                $has_api_access = isset($_POST['has_api_access']) ? 1 : 0;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                $sort_order = intval($_POST['sort_order']);
                
                // Check if slug already exists
                $check_sql = "SELECT id FROM trading_bot_plans WHERE plan_slug = '$plan_slug'";
                $check_result = mysqli_query($conn, $check_sql);
                if (mysqli_num_rows($check_result) > 0) {
                    $error = "Plan slug already exists. Please choose a different one.";
                } else {
                    $max_trading_value = $max_trading_balance ? "'$max_trading_balance'" : "NULL";
                    
                    $sql = "INSERT INTO trading_bot_plans (
                        plan_name, plan_slug, plan_description, subscription_fee, min_trading_balance, 
                        max_trading_balance, daily_roi_percentage, trading_accuracy, markets_covered, 
                        support_level, strategy_types, has_machine_learning, has_multi_market, 
                        has_strategy_blending, has_dedicated_manager, has_api_access, is_active, sort_order
                    ) VALUES (
                        '$plan_name', '$plan_slug', '$plan_description', '$subscription_fee', '$min_trading_balance',
                        $max_trading_value, '$daily_roi_percentage', '$trading_accuracy', '$markets_covered',
                        '$support_level', '$strategy_types', '$has_machine_learning', '$has_multi_market',
                        '$has_strategy_blending', '$has_dedicated_manager', '$has_api_access', '$is_active', '$sort_order'
                    )";
                    
                    if (mysqli_query($conn, $sql)) {
                        $plan_id = mysqli_insert_id($conn);
                        
                        // Log activity
                        logAdminActivity(
                            'Bot Plan Added',
                            "Added new bot plan: $plan_name ($$subscription_fee/month)",
                            'Trading Bots',
                            $plan_id,
                            'trading_bot_plans'
                        );
                        
                        // NOTIFICATION: Bot Plan Added (ADMIN)
                        $mail_subject = "New Trading Bot Plan Created";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>New Trading Bot Plan Created</h2>
                                            
                                            <p class='message'>
                                                A new trading bot plan has been added to the platform by an administrator.
                                            </p>

                                            <!-- Plan Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Plan ID:</strong> " . $plan_id . "<br>
                                                    <strong>Plan Name:</strong> " . $plan_name . "<br>
                                                    <strong>Plan Slug:</strong> " . $plan_slug . "<br>
                                                    <strong>Subscription Fee:</strong> $" . number_format($subscription_fee, 2) . "/month<br>
                                                    <strong>Min Balance:</strong> $" . number_format($min_trading_balance, 2) . "<br>
                                                    <strong>Max Balance:</strong> " . ($max_trading_balance ? '$' . number_format($max_trading_balance, 2) : 'Unlimited') . "<br>
                                                    <strong>Daily ROI:</strong> " . $daily_roi_percentage . "%<br>
                                                    <strong>Trading Accuracy:</strong> " . $trading_accuracy . "%<br>
                                                    <strong>Status:</strong> " . ($is_active ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "<br>
                                                    <strong>Created By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Created Date:</strong> " . date('F j, Y g:i A') . "
                                                </div>
                                            </div>

                                            <!-- Plan Features -->
                                            <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #495057;'>🤖 Bot Features</h4>
                                                <p style='color: #495057;'>
                                                    <strong>Markets Covered:</strong> " . $markets_covered . "<br>
                                                    <strong>Strategy Types:</strong> " . $strategy_types . "<br>
                                                    <strong>Support Level:</strong> " . ucfirst($support_level) . "<br>
                                                    <strong>Machine Learning:</strong> " . ($has_machine_learning ? '✅ Yes' : '❌ No') . "<br>
                                                    <strong>Multi-Market Trading:</strong> " . ($has_multi_market ? '✅ Yes' : '❌ No') . "<br>
                                                    <strong>Strategy Blending:</strong> " . ($has_strategy_blending ? '✅ Yes' : '❌ No') . "<br>
                                                    <strong>Dedicated Manager:</strong> " . ($has_dedicated_manager ? '✅ Yes' : '❌ No') . "<br>
                                                    <strong>API Access:</strong> " . ($has_api_access ? '✅ Yes' : '❌ No') . "
                                                </p>
                                            </div>

                                            <!-- Plan Description -->
                                            <div class='next-steps'>
                                                <h3 style='color: #2c3e50;'>📋 Plan Description</h3>
                                                <p style='color: #6c757d; background: white; padding: 15px; border: 1px solid #e9ecef; border-radius: 8px;'>
                                                    " . nl2br($plan_description) . "
                                                </p>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/edit-bot-plan.php?id=" . $plan_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;'>
                                                    Edit Plan
                                                </a>
                                                <a href='" . $myUrl . "/admin/bot-plans.php' 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 All Plans
                                                </a>
                                            </div>
                                        </div>";

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Bot plan added successfully!";
                    } else {
                        $error = "Failed to add bot plan: " . mysqli_error($conn);
                    }
                }
                break;
                
            case 'update_plan':
                $plan_id = intval($_POST['plan_id']);
                
                // Get old plan details before update
                $old_plan_sql = "SELECT * FROM trading_bot_plans WHERE id = $plan_id";
                $old_plan_result = mysqli_query($conn, $old_plan_sql);
                $old_plan = mysqli_fetch_assoc($old_plan_result);
                
                $plan_name = mysqli_real_escape_string($conn, $_POST['plan_name']);
                $plan_description = mysqli_real_escape_string($conn, $_POST['plan_description']);
                $subscription_fee = floatval($_POST['subscription_fee']);
                $min_trading_balance = floatval($_POST['min_trading_balance']);
                $max_trading_balance = !empty($_POST['max_trading_balance']) ? floatval($_POST['max_trading_balance']) : NULL;
                $daily_roi_percentage = floatval($_POST['daily_roi_percentage']);
                $trading_accuracy = floatval($_POST['trading_accuracy']);
                $markets_covered = intval($_POST['markets_covered']);
                $support_level = mysqli_real_escape_string($conn, $_POST['support_level']);
                $strategy_types = intval($_POST['strategy_types']);
                $has_machine_learning = isset($_POST['has_machine_learning']) ? 1 : 0;
                $has_multi_market = isset($_POST['has_multi_market']) ? 1 : 0;
                $has_strategy_blending = isset($_POST['has_strategy_blending']) ? 1 : 0;
                $has_dedicated_manager = isset($_POST['has_dedicated_manager']) ? 1 : 0;
                $has_api_access = isset($_POST['has_api_access']) ? 1 : 0;
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                $sort_order = intval($_POST['sort_order']);
                
                $max_trading_value = $max_trading_balance ? "'$max_trading_balance'" : "NULL";
                
                $sql = "UPDATE trading_bot_plans SET
                    plan_name = '$plan_name',
                    plan_description = '$plan_description',
                    subscription_fee = '$subscription_fee',
                    min_trading_balance = '$min_trading_balance',
                    max_trading_balance = $max_trading_value,
                    daily_roi_percentage = '$daily_roi_percentage',
                    trading_accuracy = '$trading_accuracy',
                    markets_covered = '$markets_covered',
                    support_level = '$support_level',
                    strategy_types = '$strategy_types',
                    has_machine_learning = '$has_machine_learning',
                    has_multi_market = '$has_multi_market',
                    has_strategy_blending = '$has_strategy_blending',
                    has_dedicated_manager = '$has_dedicated_manager',
                    has_api_access = '$has_api_access',
                    is_active = '$is_active',
                    sort_order = '$sort_order',
                    updated_at = NOW()
                    WHERE id = $plan_id";
                
                if (mysqli_query($conn, $sql)) {
                    // Log activity
                    logAdminActivity(
                        'Bot Plan Updated',
                        "Updated bot plan: $plan_name (ID: $plan_id)",
                        'Trading Bots',
                        $plan_id,
                        'trading_bot_plans'
                    );
                    
                    // NOTIFICATION: Bot Plan Updated (ADMIN)
                    $mail_subject = "Trading Bot Plan Updated";
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Trading Bot Plan Updated</h2>
                                        
                                        <p class='message'>
                                            A trading bot plan has been updated by an administrator.
                                        </p>

                                        <!-- Updated Plan Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Plan ID:</strong> " . $plan_id . "<br>
                                                <strong>Plan Name:</strong> " . $plan_name . "<br>
                                                <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Update Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                <strong>New Status:</strong> " . ($is_active ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "
                                            </div>
                                        </div>

                                        <!-- Changed Values -->
                                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                            <h4 style='color: #856404;'>📊 Updated Settings</h4>
                                            <table style='width: 100%; border-collapse: collapse;'>
                                                <tr>
                                                    <th style='text-align: left; padding: 5px;'>Setting</th>
                                                    <th style='text-align: left; padding: 5px;'>Previous</th>
                                                    <th style='text-align: left; padding: 5px;'>New</th>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 5px;'>Subscription Fee</td>
                                                    <td style='padding: 5px;'>$" . number_format($old_plan['subscription_fee'], 2) . "</td>
                                                    <td style='padding: 5px;'>$" . number_format($subscription_fee, 2) . "</td>
                                                </tr>
                                                <tr>
                                                    <td style='padding: 5px;'>Daily ROI</td>
                                                    <td style='padding: 5px;'>" . $old_plan['daily_roi_percentage'] . "%</td>
                                                    <td style='padding: 5px;'>" . $daily_roi_percentage . "%</td>
                                                </tr>
                                            </table>
                                        </div>

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

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Bot plan updated successfully!";
                } else {
                    $error = "Failed to update bot plan: " . mysqli_error($conn);
                }
                break;
                
            case 'delete_plan':
                $plan_id = intval($_POST['plan_id']);
                
                // Check if plan has active subscriptions
                $check_sql = "SELECT COUNT(*) as count FROM user_bot_subscriptions WHERE bot_plan_id = $plan_id AND status = 'active'";
                $check_result = mysqli_query($conn, $check_sql);
                $check_row = mysqli_fetch_assoc($check_result);
                
                if ($check_row['count'] > 0) {
                    $error = "Cannot delete plan with active subscriptions. Deactivate it instead.";
                } else {
                    // Get plan name before deletion
                    $plan_sql = "SELECT plan_name FROM trading_bot_plans WHERE id = $plan_id";
                    $plan_result = mysqli_query($conn, $plan_sql);
                    $plan_data = mysqli_fetch_assoc($plan_result);
                    $plan_name = $plan_data['plan_name'] ?: 'Unknown';
                    
                    // Soft delete (update is_active) instead of hard delete
                    $sql = "UPDATE trading_bot_plans SET is_active = 0, updated_at = NOW() WHERE id = $plan_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        // Log activity
                        logAdminActivity(
                            'Bot Plan Deleted',
                            "Deleted bot plan: $plan_name (ID: $plan_id)",
                            'Trading Bots',
                            $plan_id,
                            'trading_bot_plans'
                        );
                        
                        // NOTIFICATION: Bot Plan Deleted (ADMIN)
                        $mail_subject = "Trading Bot Plan Deactivated";
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Trading Bot Plan Deactivated</h2>
                                            
                                            <p class='message'>
                                                A trading bot plan has been deactivated by an administrator.
                                            </p>

                                            <!-- Deletion Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Plan ID:</strong> " . $plan_id . "<br>
                                                    <strong>Plan Name:</strong> " . $plan_name . "<br>
                                                    <strong>Deactivated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Deactivation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                    <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>DEACTIVATED</span>
                                                </div>
                                            </div>

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

                        // Send admin notification
                        require_once("../proccess/admin_mailer.php");
                        
                        $success = "Bot plan deactivated successfully!";
                    } else {
                        $error = "Failed to delete bot plan.";
                    }
                }
                break;
                
            case 'toggle_status':
                $plan_id = intval($_POST['plan_id']);
                $current_status = intval($_POST['current_status']);
                $new_status = $current_status ? 0 : 1;
                
                // Get plan name
                $plan_sql = "SELECT plan_name FROM trading_bot_plans WHERE id = $plan_id";
                $plan_result = mysqli_query($conn, $plan_sql);
                $plan_data = mysqli_fetch_assoc($plan_result);
                $plan_name = $plan_data['plan_name'] ?: 'Unknown';
                
                $sql = "UPDATE trading_bot_plans SET is_active = $new_status, updated_at = NOW() WHERE id = $plan_id";
                
                if (mysqli_query($conn, $sql)) {
                    $status_text = $new_status ? 'activated' : 'deactivated';
                    
                    // Log activity
                    logAdminActivity(
                        'Bot Plan Status Changed',
                        "$status_text bot plan ID: $plan_id - $plan_name",
                        'Trading Bots',
                        $plan_id,
                        'trading_bot_plans'
                    );
                    
                    // NOTIFICATION: Bot Plan Status Changed (ADMIN)
                    $mail_subject = "Bot Plan " . ucfirst($status_text);
                    $mail_message = "<!-- Content Section -->
                                    <div class='email-content'>
                                        <h2 class='greeting'>Bot Plan " . ucfirst($status_text) . "</h2>
                                        
                                        <p class='message'>
                                            Trading bot plan <strong>" . $plan_name . "</strong> has been " . $status_text . ".
                                        </p>

                                        <!-- Status Change Details -->
                                        <div class='details-section'>
                                            <div class='detail-box'>
                                                <strong>Plan ID:</strong> " . $plan_id . "<br>
                                                <strong>Plan Name:</strong> " . $plan_name . "<br>
                                                <strong>Previous Status:</strong> " . ($current_status ? 'Active' : 'Inactive') . "<br>
                                                <strong>New Status:</strong> " . ($new_status ? '<span style="color: #28a745;">Active</span>' : '<span style="color: #dc3545;">Inactive</span>') . "<br>
                                                <strong>Changed By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                <strong>Change Date:</strong> " . date('F j, Y g:i A') . "
                                            </div>
                                        </div>

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

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Bot plan $status_text successfully!";
                } else {
                    $error = "Failed to update plan status.";
                }
                break;
        }
    }
}

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';

// Build query
$sql = "SELECT * FROM trading_bot_plans WHERE 1=1";

if ($filter_status === 'active') {
    $sql .= " AND is_active = 1";
} elseif ($filter_status === 'inactive') {
    $sql .= " AND is_active = 0";
}

if ($search) {
    $sql .= " AND (plan_name LIKE '%$search%' OR plan_description LIKE '%$search%' OR plan_slug LIKE '%$search%')";
}

$sql .= " ORDER BY sort_order ASC, id ASC";

// Execute query
$result = mysqli_query($conn, $sql);

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total_plans,
    SUM(is_active) as active_plans,
    SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive_plans,
    AVG(subscription_fee) as avg_fee,
    SUM(CASE WHEN has_machine_learning = 1 THEN 1 ELSE 0 END) as ml_plans,
    SUM(CASE WHEN has_dedicated_manager = 1 THEN 1 ELSE 0 END) as premium_plans
    FROM trading_bot_plans";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);
?>

<!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-robot me-2"></i>Trading Bot Plans Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPlanModal">
												<i class="fas fa-plus me-1"></i> Add New Plan
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['total_plans']; ?></h1>
														<p class="text-white mb-0">Total Plans</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['active_plans']; ?></h1>
														<p class="text-white mb-0">Active</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['inactive_plans']; ?></h1>
														<p class="text-white mb-0">Inactive</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['ml_plans']; ?></h1>
														<p class="text-white mb-0">AI/ML Plans</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo $stats['premium_plans']; ?></h1>
														<p class="text-white mb-0">Premium Plans</p>
													</div>
												</div>
											</div>
											<div class="col-xl-2 col-md-4 col-6">
												<div class="box bg-gradient-secondary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['avg_fee'], 2); ?></h1>
														<p class="text-white mb-0">Avg. Monthly Fee</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-8">
												<form method="GET" class="row">
													<div class="col-md-3">
														<div class="form-group">
															<select class="form-control" name="status" onchange="this.form.submit()">
																<option value="">All Status</option>
																<option value="active" <?php echo $filter_status == 'active' ? 'selected' : ''; ?>>Active Only</option>
																<option value="inactive" <?php echo $filter_status == 'inactive' ? 'selected' : ''; ?>>Inactive Only</option>
															</select>
														</div>
													</div>
													<div class="col-md-6">
														<div class="form-group">
															<input type="text" class="form-control" name="search" placeholder="Search plans..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-3">
														<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
														<?php if ($search || $filter_status): ?>
															<a href="bot_plans.php" class="btn btn-secondary">Clear</a>
														<?php endif; ?>
													</div>
												</form>
											</div>
											<div class="col-md-4 text-end">
												<div class="btn-group">
													<button type="button" class="btn btn-light dropdown-toggle" data-bs-toggle="dropdown">
														<i class="fas fa-download me-1"></i> Export
													</button>
													<div class="dropdown-menu">
														<a class="dropdown-item" href="export_bot_plans.php?format=csv&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-csv"></i> CSV</a>
														<a class="dropdown-item" href="export_bot_plans.php?format=excel&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-excel"></i> Excel</a>
														<a class="dropdown-item" href="export_bot_plans.php?format=pdf&status=<?php echo $filter_status; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-pdf"></i> PDF</a>
													</div>
												</div>
											</div>
										</div>
										
										<?php if (isset($success)): ?>
											<div class="alert alert-success alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
											</div>
										<?php endif; ?>
										
										<?php if (isset($error)): ?>
											<div class="alert alert-danger alert-dismissible fade show">
												<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
												<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
											</div>
										<?php endif; ?>
										
										<!-- Plans Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="plansTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>Plan Name</th>
														<th>Monthly Fee</th>
														<th>Min Balance</th>
														<th>Daily ROI</th>
														<th>Accuracy</th>
														<th>Features</th>
														<th>Status</th>
														<th>Sort</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($plan = mysqli_fetch_assoc($result)): ?>
															<?php
															$is_active = $plan['is_active'];
															$status_color = $is_active ? 'success' : 'danger';
															$status_text = $is_active ? 'Active' : 'Inactive';
															?>
															<tr>
																<td><?php echo $plan['id']; ?></td>
																<td>
																	<div>
																		<p class="mb-0 fw-500"><?php echo htmlspecialchars($plan['plan_name']); ?></p>
																		<small class="text-mute"><?php echo htmlspecialchars($plan['plan_slug']); ?></small>
																	</div>
																</td>
																<td>
																	<h4 class="fw-500 text-primary">$<?php echo number_format($plan['subscription_fee'], 2); ?></h4>
																	<small class="text-mute">per month</small>
																</td>
																<td>
																	<p class="mb-0">$<?php echo number_format($plan['min_trading_balance'], 2); ?></p>
																	<?php if ($plan['max_trading_balance']): ?>
																		<small class="text-mute">Max: $<?php echo number_format($plan['max_trading_balance'], 2); ?></small>
																	<?php else: ?>
																		<small class="text-mute">No max limit</small>
																	<?php endif; ?>
																</td>
																<td>
																	<h4 class="fw-500 text-success"><?php echo $plan['daily_roi_percentage']; ?>%</h4>
																	<small class="text-mute">daily</small>
																</td>
																<td>
																	<div class="progress" style="height: 20px;">
																		<div class="progress-bar bg-success" style="width: <?php echo $plan['trading_accuracy']; ?>%">
																			<?php echo $plan['trading_accuracy']; ?>%
																		</div>
																	</div>
																	<small class="text-mute">success rate</small>
																</td>
																<td>
																	<div class="d-flex flex-wrap gap-1">
																		<?php if ($plan['has_machine_learning']): ?>
																			<span class="badge bg-info" data-bs-toggle="tooltip" title="Machine Learning"><i class="fas fa-brain"></i></span>
																		<?php endif; ?>
																		<?php if ($plan['has_multi_market']): ?>
																			<span class="badge bg-primary" data-bs-toggle="tooltip" title="Multi-Market"><i class="fas fa-globe"></i></span>
																		<?php endif; ?>
																		<?php if ($plan['has_strategy_blending']): ?>
																			<span class="badge bg-warning" data-bs-toggle="tooltip" title="Strategy Blending"><i class="fas fa-cogs"></i></span>
																		<?php endif; ?>
																		<?php if ($plan['has_dedicated_manager']): ?>
																			<span class="badge bg-danger" data-bs-toggle="tooltip" title="Dedicated Manager"><i class="fas fa-headset"></i></span>
																		<?php endif; ?>
																		<?php if ($plan['has_api_access']): ?>
																			<span class="badge bg-dark" data-bs-toggle="tooltip" title="API Access"><i class="fas fa-code"></i></span>
																		<?php endif; ?>
																		<span class="badge bg-secondary" data-bs-toggle="tooltip" title="Markets: <?php echo $plan['markets_covered']; ?>">
																			<i class="fas fa-chart-line"></i> <?php echo $plan['markets_covered']; ?>
																		</span>
																	</div>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo $status_text; ?></span>
																</td>
																<td>
																	<span class="badge bg-light text-dark"><?php echo $plan['sort_order']; ?></span>
																</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="#" data-bs-toggle="modal" data-bs-target="#viewPlanModal" 
																			   data-plan-id="<?php echo $plan['id']; ?>"
																			   data-plan-name="<?php echo htmlspecialchars($plan['plan_name']); ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#editPlanModal" 
																			   data-plan-id="<?php echo $plan['id']; ?>"
																			   data-plan-data='<?php echo htmlspecialchars(json_encode($plan), ENT_QUOTES); ?>'>
																				<i class="fas fa-edit me-2"></i> Edit Plan
																			</a>
																			<form method="POST" class="d-inline">
																				<input type="hidden" name="action_type" value="toggle_status">
																				<input type="hidden" name="plan_id" value="<?php echo $plan['id']; ?>">
																				<input type="hidden" name="current_status" value="<?php echo $plan['is_active']; ?>">
																				<button type="submit" class="dropdown-item">
																					<i class="fas fa-power-off me-2"></i> 
																					<?php echo $plan['is_active'] ? 'Deactivate' : 'Activate'; ?>
																				</button>
																			</form>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $plan['id']; ?>, '<?php echo htmlspecialchars(addslashes($plan['plan_name'])); ?>')">
																				<i class="fas fa-trash me-2"></i> Delete Plan
																			</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 plans found</h5>
																<p class="text-mute">Try adjusting your search or add a new plan</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Adding New Plan -->
		<div class="modal fade" id="addPlanModal" tabindex="-1" aria-labelledby="addPlanModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addPlanModalLabel">Add New Bot Plan</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="add_plan">
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Plan Name <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="plan_name" required placeholder="e.g., AI Alpha">
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Plan Slug <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="plan_slug" required placeholder="e.g., ai-alpha" pattern="[a-z0-9-]+" title="Lowercase letters, numbers, and hyphens only">
										<small class="text-mute">URL-friendly version (lowercase, hyphens)</small>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Plan Description</label>
								<textarea class="form-control" name="plan_description" rows="3" placeholder="Describe this bot plan..."></textarea>
							</div>
							
							<div class="row">
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Monthly Fee ($) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="subscription_fee" step="0.01" min="0" required placeholder="500.00">
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Min Trading Balance ($) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="min_trading_balance" step="0.01" min="0" required placeholder="100.00">
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Max Trading Balance ($)</label>
										<input type="number" class="form-control" name="max_trading_balance" step="0.01" min="0" placeholder="Leave empty for no limit">
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Daily ROI (%) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="daily_roi_percentage" step="0.01" min="0" max="100" required placeholder="12.50">
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Trading Accuracy (%) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="trading_accuracy" step="0.01" min="0" max="100" required placeholder="88.00">
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Markets Covered <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="markets_covered" min="1" required placeholder="2">
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Support Level <span class="text-danger">*</span></label>
										<select class="form-control" name="support_level" required>
											<option value="Email">Email</option>
											<option value="Priority Email">Priority Email</option>
											<option value="24/7 Phone">24/7 Phone</option>
											<option value="Dedicated Manager">Dedicated Manager</option>
										</select>
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Strategy Types <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="strategy_types" min="1" required placeholder="3">
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Features</label>
								<div class="row">
									<div class="col-md-6">
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_machine_learning" id="mlCheck">
											<label class="form-check-label" for="mlCheck">
												<i class="fas fa-brain me-1"></i> Machine Learning
											</label>
										</div>
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_multi_market" id="multiMarketCheck">
											<label class="form-check-label" for="multiMarketCheck">
												<i class="fas fa-globe me-1"></i> Multi-Market
											</label>
										</div>
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_strategy_blending" id="strategyCheck">
											<label class="form-check-label" for="strategyCheck">
												<i class="fas fa-cogs me-1"></i> Strategy Blending
											</label>
										</div>
									</div>
									<div class="col-md-6">
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_dedicated_manager" id="managerCheck">
											<label class="form-check-label" for="managerCheck">
												<i class="fas fa-headset me-1"></i> Dedicated Manager
											</label>
										</div>
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_api_access" id="apiCheck">
											<label class="form-check-label" for="apiCheck">
												<i class="fas fa-code me-1"></i> API Access
											</label>
										</div>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Sort Order <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="sort_order" min="0" required value="0">
										<small class="text-mute">Lower numbers appear first</small>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Status</label>
										<select class="form-control" name="is_active">
											<option value="1" selected>Active</option>
											<option value="0">Inactive</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Add Plan</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Editing Plan -->
		<div class="modal fade" id="editPlanModal" tabindex="-1" aria-labelledby="editPlanModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="editPlanModalLabel">Edit Bot Plan</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="update_plan">
							<input type="hidden" name="plan_id" id="editPlanId">
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Plan Name <span class="text-danger">*</span></label>
										<input type="text" class="form-control" name="plan_name" id="editPlanName" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Plan Slug</label>
										<input type="text" class="form-control" id="editPlanSlug" disabled>
										<small class="text-mute">Slug cannot be changed</small>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Plan Description</label>
								<textarea class="form-control" name="plan_description" id="editPlanDescription" rows="3"></textarea>
							</div>
							
							<div class="row">
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Monthly Fee ($) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="subscription_fee" id="editSubscriptionFee" step="0.01" min="0" required>
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Min Trading Balance ($) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="min_trading_balance" id="editMinBalance" step="0.01" min="0" required>
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Max Trading Balance ($)</label>
										<input type="number" class="form-control" name="max_trading_balance" id="editMaxBalance" step="0.01" min="0">
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Daily ROI (%) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="daily_roi_percentage" id="editDailyROI" step="0.01" min="0" max="100" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Trading Accuracy (%) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="trading_accuracy" id="editTradingAccuracy" step="0.01" min="0" max="100" required>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Markets Covered <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="markets_covered" id="editMarketsCovered" min="1" required>
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Support Level <span class="text-danger">*</span></label>
										<select class="form-control" name="support_level" id="editSupportLevel" required>
											<option value="Email">Email</option>
											<option value="Priority Email">Priority Email</option>
											<option value="24/7 Phone">24/7 Phone</option>
											<option value="Dedicated Manager">Dedicated Manager</option>
										</select>
									</div>
								</div>
								<div class="col-md-4">
									<div class="mb-3">
										<label class="form-label">Strategy Types <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="strategy_types" id="editStrategyTypes" min="1" required>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Features</label>
								<div class="row">
									<div class="col-md-6">
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_machine_learning" id="editMlCheck">
											<label class="form-check-label" for="editMlCheck">
												<i class="fas fa-brain me-1"></i> Machine Learning
											</label>
										</div>
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_multi_market" id="editMultiMarketCheck">
											<label class="form-check-label" for="editMultiMarketCheck">
												<i class="fas fa-globe me-1"></i> Multi-Market
											</label>
										</div>
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_strategy_blending" id="editStrategyCheck">
											<label class="form-check-label" for="editStrategyCheck">
												<i class="fas fa-cogs me-1"></i> Strategy Blending
											</label>
										</div>
									</div>
									<div class="col-md-6">
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_dedicated_manager" id="editManagerCheck">
											<label class="form-check-label" for="editManagerCheck">
												<i class="fas fa-headset me-1"></i> Dedicated Manager
											</label>
										</div>
										<div class="form-check mb-2">
											<input class="form-check-input" type="checkbox" name="has_api_access" id="editApiCheck">
											<label class="form-check-label" for="editApiCheck">
												<i class="fas fa-code me-1"></i> API Access
											</label>
										</div>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Sort Order <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="sort_order" id="editSortOrder" min="0" required>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Status</label>
										<select class="form-control" name="is_active" id="editIsActive">
											<option value="1">Active</option>
											<option value="0">Inactive</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Admin PIN <span class="text-danger">*</span></label>
								<input type="password" class="form-control" name="admin_pin" required placeholder="Enter your 4-digit PIN">
								<small class="text-mute">Required for security confirmation</small>
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
							<button type="submit" class="btn btn-primary">Update Plan</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Viewing Plan Details -->
		<div class="modal fade" id="viewPlanModal" tabindex="-1" aria-labelledby="viewPlanModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewPlanModalLabel">Bot Plan Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="planDetails">
						<!-- Details 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>
		
		<!-- Hidden form for delete -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_plan">
			<input type="hidden" name="plan_id" id="deletePlanId">
			<input type="hidden" name="admin_pin" id="deletePin">
		</form>
		
		  
    
		
		
		  <?php include('includes/scripts.php') ?>
		
		<!-- SweetAlert2 -->
		<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
		
		<!-- DataTables -->
		<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
		<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
			$('#plansTable').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 tooltips
			$('[data-bs-toggle="tooltip"]').tooltip();
			
			// Edit Plan Modal
			$('#editPlanModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var planData = JSON.parse(button.data('plan-data'));
				var modal = $(this);
				
				// Fill form with plan data
				modal.find('#editPlanId').val(planData.id);
				modal.find('#editPlanName').val(planData.plan_name);
				modal.find('#editPlanSlug').val(planData.plan_slug);
				modal.find('#editPlanDescription').val(planData.plan_description);
				modal.find('#editSubscriptionFee').val(planData.subscription_fee);
				modal.find('#editMinBalance').val(planData.min_trading_balance);
				modal.find('#editMaxBalance').val(planData.max_trading_balance || '');
				modal.find('#editDailyROI').val(planData.daily_roi_percentage);
				modal.find('#editTradingAccuracy').val(planData.trading_accuracy);
				modal.find('#editMarketsCovered').val(planData.markets_covered);
				modal.find('#editSupportLevel').val(planData.support_level);
				modal.find('#editStrategyTypes').val(planData.strategy_types);
				modal.find('#editSortOrder').val(planData.sort_order);
				modal.find('#editIsActive').val(planData.is_active);
				
				// Checkboxes
				modal.find('#editMlCheck').prop('checked', planData.has_machine_learning == 1);
				modal.find('#editMultiMarketCheck').prop('checked', planData.has_multi_market == 1);
				modal.find('#editStrategyCheck').prop('checked', planData.has_strategy_blending == 1);
				modal.find('#editManagerCheck').prop('checked', planData.has_dedicated_manager == 1);
				modal.find('#editApiCheck').prop('checked', planData.has_api_access == 1);
				
				modal.find('.modal-title').text('Edit Plan: ' + planData.plan_name);
			});
			
			// View Plan Modal
			$('#viewPlanModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var planId = button.data('plan-id');
				var planName = button.data('plan-name');
				var modal = $(this);
				
				// Load plan details via AJAX
				$.ajax({
					url: 'ajax/get_plan_details.php',
					type: 'GET',
					data: { plan_id: planId },
					success: function(data) {
						modal.find('#planDetails').html(data);
						modal.find('.modal-title').text('Plan Details: ' + planName);
					},
					error: function() {
						modal.find('#planDetails').html('<div class="alert alert-danger">Failed to load plan details.</div>');
					}
				});
			});
			
			// Auto-refresh stats every 30 seconds
			setInterval(refreshStats, 30000);
		});
		
		// Refresh stats
		function refreshStats() {
			$.ajax({
				url: 'ajax/get_bot_plan_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total_plans);
						$('.bg-gradient-success .fw-500').text(stats.active_plans);
						$('.bg-gradient-warning .fw-500').text(stats.inactive_plans);
						$('.bg-gradient-info .fw-500').text(stats.ml_plans);
						$('.bg-gradient-danger .fw-500').text(stats.premium_plans);
						$('.bg-gradient-secondary .fw-500').text('$' + stats.avg_fee);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}
		
		// Confirm Delete with PIN
		function confirmDelete(planId, planName) {
			Swal.fire({
				title: 'Delete Plan?',
				html: `
					<p>Are you sure you want to delete <strong>${planName}</strong>?</p>
					<p class="text-danger">This will only deactivate the plan (soft delete).</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: 'Delete Plan',
				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 delete form
					document.getElementById('deletePlanId').value = planId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 8px;
			border-radius: 4px;
			font-size: 11px;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		.progress {
			border-radius: 10px;
		}
		.gap-1 {
			gap: 5px;
		}
		</style>
		
	</body>
</html>