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

// Get theme preference
$theme = 'light';
if (isset($_COOKIE['theme'])) {
    $theme = $_COOKIE['theme'];
}

// Fetch user data
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 1;

// Fetch bot plans from database using mysqli_query
$botPlans = array();
$query = "SELECT * FROM trading_bot_plans WHERE is_active = 1 ORDER BY sort_order ASC";
$result = mysqli_query($conn, $query);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $botPlans[] = $row;
    }
    mysqli_free_result($result);
}

// Fetch user's active subscription
$activeSubscription = array();
$query = "SELECT ubs.*, tbp.plan_name, tbp.plan_slug 
          FROM user_bot_subscriptions ubs
          JOIN trading_bot_plans tbp ON ubs.bot_plan_id = tbp.id
          WHERE ubs.user_id = '$user_id' AND ubs.status = 'active'
          ORDER BY ubs.created_at DESC LIMIT 1";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $activeSubscription = mysqli_fetch_assoc($result);
}

// Calculate user stats
$totalProfit = 0;
$avgSuccessRate = 0;
$query = "SELECT 
            COALESCE(SUM(total_profit), 0) as total_profit,
            COALESCE(AVG(success_rate), 0) as avg_success_rate
          FROM user_bot_subscriptions 
          WHERE user_id = '$user_id'";
$result = mysqli_query($conn, $query);
if ($result && mysqli_num_rows($result) > 0) {
    $userStats = mysqli_fetch_assoc($result);
    $totalProfit = $userStats['total_profit'];
    $avgSuccessRate = $userStats['avg_success_rate'];
}

// Calculate days left for active subscription
$daysLeft = 0;
if (!empty($activeSubscription)) {
    $endDate = new DateTime($activeSubscription['subscription_end']);
    $currentDate = new DateTime();
    $interval = $endDate->diff($currentDate);
    $daysLeft = $interval->days;
}

// Get current plan ROI
$currentPlanRoi = '0.00';
if (!empty($activeSubscription)) {
    $planId = $activeSubscription['bot_plan_id'];
    foreach ($botPlans as $plan) {
        if ($plan['id'] == $planId) {
            $currentPlanRoi = $plan['daily_roi_percentage'];
            break;
        }
    }
}

// Get user fund balance from users table
$userQuery = "SELECT fund_balance, available_balance FROM users WHERE id = '$user_id'";
$userResult = mysqli_query($conn, $userQuery);
if ($userResult && mysqli_num_rows($userResult) > 0) {
    $userRow = mysqli_fetch_assoc($userResult);
    $fundBalance = isset($userRow['fund_balance']) ? floatval($userRow['fund_balance']) : 0;
    $availableBalance = isset($userRow['available_balance']) ? floatval($userRow['available_balance']) : 0;
} else {
    $fundBalance = 0;
    $availableBalance = 0;
}
?>

<!DOCTYPE html>
<html lang="en" data-bs-theme="<?php echo htmlspecialchars($theme); ?>">
    


<body class="dashboard">
    <div id="preloader" class="preloader-wrapper">
        <div class="loader">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>

    
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>
        <div class="content-body">
            <div class="container">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>AI Trading Bots</h3>
                                        <p class="mb-2">Choose your trading automation level</p>
                                    </div>
                                </div>
                                <div class="col-auto">
                                    <div class="breadcrumbs"><a href="#">Home </a>
                                        <span><i class="fi fi-rr-angle-small-right"></i></span>
                                        <a href="#">Trading Bots</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Bot Stats Summary -->
                <div class="row">
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Active Bot</h6>
                            <h3>
                                <?php echo !empty($activeSubscription['plan_name']) ? htmlspecialchars($activeSubscription['plan_name']) : 'None'; ?>
                                <?php if(!empty($activeSubscription)): ?>
                                    <span class="float-right text-success"><i class="fi fi-rr-check"></i></span>
                                <?php endif; ?>
                            </h3>
                            <p>
                                <?php if(!empty($activeSubscription)): ?>
                                    <span class="text-success">
                                        <i class="fi fi-rr-arrow-trend-up"></i>
                                        <?php echo htmlspecialchars($currentPlanRoi); ?>% Daily
                                    </span>
                                    <strong class="float-right"><?php echo $daysLeft; ?> Days Left</strong>
                                <?php else: ?>
                                    <span class="text-muted">No active bot</span>
                                <?php endif; ?>
                            </p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Total Bot Profit</h6>
                            <h3>$ <?php echo number_format($totalProfit, 2); ?>
                                <span class="float-right"><i class="fi fi-rr-robot"></i></span>
                            </h3>
                            <p>
                                <span class="text-success"><i class="fi fi-rr-arrow-trend-up"></i>2.47%</span>
                                Last month <strong>$<?php echo number_format($totalProfit * 0.3, 2); ?></strong>
                            </p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Trading Accuracy</h6>
                            <h3><?php echo number_format($avgSuccessRate, 1); ?>%</h3>
                            <p>
                                <span class="text-success"><i class="fi fi-rr-arrow-trend-up"></i>1.2%</span>
                                Last month <strong><?php echo number_format(max(0, $avgSuccessRate - 1), 1); ?>%</strong>
                            </p>
                        </div>
                    </div>
                    <div class="col-xl-3 col-lg-6 col-md-6 col-sm-6">
                        <div class="stat-widget-1">
                            <h6>Available for New Bot</h6>
                            <h3>$ <?php echo number_format($fundBalance, 2); ?></h3>
                            <p>
                                <button class="btn btn-primary btn-sm mt-2" onclick="location.href='wallets.php'"> 
                                    <i class="fi fi-rr-square-plus"></i> Add Funds
                                </button>
                            </p>
                        </div>
                    </div>
                </div>

                <!-- AI Trading Bot Plans -->
                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Available AI Trading Bots</h4>
                                <p class="mb-0">Upgrade your bot to access advanced trading features</p>
                            </div>
                            <div class="card-body">
                                <div id="result"></div>
                                <div class="row g-4">
                                    <?php 
                                    $index = 0;
                                    foreach($botPlans as $plan): 
                                        $isActive = (!empty($activeSubscription['plan_slug']) && $activeSubscription['plan_slug'] === $plan['plan_slug']);
                                        $isUpgradable = false;
                                        
                                        if(!empty($activeSubscription) && !$isActive) {
                                            // Find current plan order
                                            $currentPlanOrder = -1;
                                            foreach($botPlans as $i => $p) {
                                                if($p['plan_slug'] === $activeSubscription['plan_slug']) {
                                                    $currentPlanOrder = $i;
                                                    break;
                                                }
                                            }
                                            $isUpgradable = $index > $currentPlanOrder;
                                        }
                                        
                                        // Determine badge and icon
                                        $badgeClass = 'bg-primary';
                                        $iconClass = 'text-primary';
                                        $iconName = 'fi fi-rr-robot';
                                        
                                        if($index == 0) {
                                            $badgeClass = 'bg-primary';
                                            $iconClass = 'text-primary';
                                            $iconName = 'fi fi-rr-robot';
                                        } elseif($index == 1) {
                                            $badgeClass = 'bg-info';
                                            $iconClass = 'text-info';
                                            $iconName = 'fi fi-rr-brain-circuit';
                                        } elseif($index == 2) {
                                            $badgeClass = 'bg-warning';
                                            $iconClass = 'text-warning';
                                            $iconName = 'fi fi-rr-radar';
                                        } else {
                                            $badgeClass = 'bg-danger';
                                            $iconClass = 'text-danger';
                                            $iconName = 'fi fi-rr-stars';
                                        }
                                        
                                        // Determine subtitle
                                        $subtitles = array(
                                            'Entry Level Trading Bot',
                                            'Improved Learning & Speed',
                                            'Multi-Market Scanning',
                                            'Advanced Strategy Blending'
                                        );
                                        $subtitle = isset($subtitles[$index]) ? $subtitles[$index] : $plan['plan_description'];
                                        
                                        // Check if user can subscribe
                                        $canSubscribe = !$isActive;
                                        $buttonText = $isActive ? 'Currently Active' : ($isUpgradable ? 'Upgrade Now' : 'Subscribe Now');
                                        $buttonIcon = $isActive ? 'fi fi-rr-check' : ($isUpgradable ? 'fi fi-rr-arrow-up' : 'fi fi-rr-shopping-cart');
                                    ?>
                                    <div class="col-xl-3 col-lg-6 col-md-6">
                                        <div class="plan-card <?php echo $isActive ? 'active-plan' : ''; ?>">
                                            <div class="plan-header">
                                                <?php if($index == 0): ?>
                                                    <span class="plan-badge bg-primary">RECOMMENDED</span>
                                                <?php elseif($index == 1): ?>
                                                    <span class="plan-badge bg-info">POPULAR</span>
                                                <?php elseif($index == 2): ?>
                                                    <span class="plan-badge bg-warning">ADVANCED</span>
                                                <?php else: ?>
                                                    <span class="plan-badge bg-danger">PRO</span>
                                                <?php endif; ?>
                                                
                                                <div class="plan-icon" style="background-color: var(--bs-primary-bg-subtle)">
                                                    <i class="<?php echo $iconName; ?> <?php echo $iconClass; ?>" style="font-size: 30px !important"></i>
                                                </div>
                                                <h3 class="plan-title"><?php echo htmlspecialchars($plan['plan_name']); ?></h3>
                                                <p class="plan-subtitle"><?php echo $subtitle; ?></p>
                                            </div>
                                            <div class="plan-price">
                                                <h2>$<?php echo number_format($plan['subscription_fee'], 2); ?> 
                                                    <span class="text-muted">/ month</span>
                                                </h2>
                                                <p class="text-success">
                                                    <i class="fi fi-rr-arrow-trend-up"></i> 
                                                    <?php echo $plan['daily_roi_percentage']; ?>% Daily ROI
                                                </p>
                                                <small class="text-muted">
                                                    Min: $<?php echo number_format($plan['min_trading_balance'], 2); ?> | 
                                                    Max: <?php echo $plan['max_trading_balance'] ? '$' . number_format($plan['max_trading_balance'], 2) : 'Unlimited'; ?>
                                                </small>
                                            </div>
                                            <div class="plan-features">
                                                <ul>
                                                    <li>
                                                        <i class="fi fi-rr-check text-success"></i> 
                                                        Basic Market Analysis
                                                    </li>
                                                    <li>
                                                        <i class="fi fi-rr-check text-success"></i> 
                                                        24/7 Trading
                                                    </li>
                                                    <li>
                                                        <i class="fi fi-rr-check text-success"></i> 
                                                        Risk Management
                                                    </li>
                                                    <li>
                                                        <i class="fi fi-rr-check text-success"></i> 
                                                        <?php echo $plan['support_level']; ?> Support
                                                    </li>
                                                    <li>
                                                        <?php if($plan['has_machine_learning']): ?>
                                                            <i class="fi fi-rr-check text-success"></i> 
                                                            Machine Learning
                                                        <?php else: ?>
                                                            <i class="fi fi-rr-x text-muted"></i> 
                                                            Advanced Learning
                                                        <?php endif; ?>
                                                    </li>
                                                    <li>
                                                        <?php if($plan['has_multi_market']): ?>
                                                            <i class="fi fi-rr-check text-success"></i> 
                                                            Multi-Market (<?php echo $plan['markets_covered']; ?>+)
                                                        <?php else: ?>
                                                            <i class="fi fi-rr-x text-muted"></i> 
                                                            Multi-Market
                                                        <?php endif; ?>
                                                    </li>
                                                    <li>
                                                        <?php if($plan['has_strategy_blending']): ?>
                                                            <i class="fi fi-rr-check text-success"></i> 
                                                            Strategy Blending
                                                        <?php else: ?>
                                                            <i class="fi fi-rr-x text-muted"></i> 
                                                            Strategy Blending
                                                        <?php endif; ?>
                                                    </li>
                                                </ul>
                                            </div>
                                            <div class="plan-action">
                                                <?php if($isActive): ?>
                                                    <button class="btn btn-success btn-block" disabled>
                                                        <i class="fi fi-rr-check"></i> Currently Active
                                                    </button>
                                                <?php else: ?>
                                                    <button class="btn btn-primary btn-block" 
                                                            data-bs-toggle="modal" 
                                                            data-bs-target="#previewModal<?php echo $plan['id']; ?>">
                                                        <i class="<?php echo $buttonIcon; ?>"></i> <?php echo $buttonText; ?>
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Preview Modal for each plan -->
                                        <div class="modal fade" id="previewModal<?php echo $plan['id']; ?>" tabindex="-1">
                                            <div class="modal-dialog">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title">Subscribe to <?php echo htmlspecialchars($plan['plan_name']); ?></h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <div class="text-center mb-4">
                                                            <div class="plan-icon mb-3 mx-auto" style="background-color: var(--bs-primary-bg-subtle); width: 80px; height: 80px;">
                                                                <i class="<?php echo $iconName; ?> <?php echo $iconClass; ?>" style="font-size: 40px !important"></i>
                                                            </div>
                                                            <h4><?php echo htmlspecialchars($plan['plan_name']); ?></h4>
                                                            <p class="text-muted"><?php echo $subtitle; ?></p>
                                                        </div>
                                                        
                                                        <div class="subscription-details mb-4">
                                                            <div class="d-flex justify-content-between mb-2">
                                                                <span>Monthly Subscription:</span>
                                                                <strong>$<?php echo number_format($plan['subscription_fee'], 2); ?></strong>
                                                            </div>
                                                            <div class="d-flex justify-content-between mb-2">
                                                                <span>Daily ROI:</span>
                                                                <strong class="text-success"><?php echo $plan['daily_roi_percentage']; ?>%</strong>
                                                            </div>
                                                            <div class="d-flex justify-content-between mb-2">
                                                                <span>Minimum Balance Required:</span>
                                                                <strong>$<?php echo number_format($plan['min_trading_balance'], 2); ?></strong>
                                                            </div>
                                                            <div class="d-flex justify-content-between mb-2">
                                                                <span>Your Available Balance:</span>
                                                                <strong class="<?php echo $fundBalance >= $plan['min_trading_balance'] ? 'text-success' : 'text-danger'; ?>">
                                                                    $<?php echo number_format($fundBalance, 2); ?>
                                                                </strong>
                                                            </div>
                                                        </div>
                                                        
                                                        <?php if($fundBalance < $plan['min_trading_balance']): ?>
                                                        <div class="alert alert-warning">
                                                            <i class="fi fi-rr-exclamation me-2"></i>
                                                            <strong>Insufficient Balance!</strong><br>
                                                            You need <strong>$<?php echo number_format($plan['min_trading_balance'] - $fundBalance, 2); ?></strong> more to activate this bot.
                                                            <a href="wallets.php" type="button" class="btn btn-secondary right" >Top Up Wallet</a>
                                                        </div>
                                                        <?php endif; ?>
                                                        
                                                        <div class="alert alert-info">
                                                            <i class="fi fi-rr-info me-2"></i>
                                                            <small>
                                                                <strong>Note:</strong> The subscription fee will be deducted from your fund balance first. 
                                                                If your remaining balance meets the minimum requirement, the bot will be activated immediately. 
                                                                Otherwise, it will remain pending until you add more funds.
                                                            </small>
                                                        </div>
                                                    </div>
                                                    <!-- In your modal footer section for EACH plan -->
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <form class="subscribe-form" id="subscribeForm<?php echo $plan['id']; ?>">
                                                            <input type="hidden" name="bot_id" value="<?php echo $plan['id']; ?>" required>
                                                            <button type="submit" 
                                                                    class="btn btn-primary subscribe-btn" 
                                                                    <?php echo $fundBalance < $plan['min_trading_balance'] ? 'disabled' : ''; ?>>
                                                                <i class="fi fi-rr-shopping-cart"></i> Confirm Subscription
                                                            </button>
                                                        </form> 
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php 
                                    $index++;
                                    endforeach; 
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Bot Comparison Table -->
                <div class="row mt-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Bot Features Comparison</h4>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover">
                                        <thead>
                                            <tr>
                                                <th>Features</th>
                                                <?php foreach($botPlans as $plan): ?>
                                                <th><?php echo htmlspecialchars($plan['plan_name']); ?></th>
                                                <?php endforeach; ?>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td><strong>Monthly Fee</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td>$<?php echo number_format($plan['subscription_fee'], 2); ?></td>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <td><strong>Daily ROI</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td><?php echo $plan['daily_roi_percentage']; ?>%</td>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <td><strong>Trading Accuracy</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td><?php echo $plan['trading_accuracy']; ?>%</td>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <td><strong>Min Balance</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td>$<?php echo number_format($plan['min_trading_balance'], 2); ?></td>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <td><strong>Max Balance</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td><?php echo $plan['max_trading_balance'] ? '$' . number_format($plan['max_trading_balance'], 2) : 'Unlimited'; ?></td>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <td><strong>Markets Covered</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td><?php echo $plan['markets_covered']; ?></td>
                                                <?php endforeach; ?>
                                            </tr>
                                            <tr>
                                                <td><strong>Support Level</strong></td>
                                                <?php foreach($botPlans as $plan): ?>
                                                <td><?php echo $plan['support_level']; ?></td>
                                                <?php endforeach; ?>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include('includes/footer.php');?>
    </div>
   
    <!-- FIXED CSS for plan cards with proper theme variables -->
    <style>
        /* Plan Cards - Fixed for theme switching */
        .plan-card {
            border: 1px solid var(--bs-border-color);
            border-radius: var(--bs-border-radius-lg);
            padding: 1.5rem;
            height: 100%;
            transition: all 0.3s ease;
            background-color: var(--bs-card-bg, var(--bs-body-bg));
            position: relative;
        }
        
        .plan-card:hover {
            transform: translateY(-5px);
            box-shadow: var(--bs-box-shadow);
        }
        
        .plan-card.active-plan {
            border: 2px solid var(--bs-success);
            background: linear-gradient(135deg, 
                color-mix(in srgb, var(--bs-success) 10%, transparent) 0%, 
                var(--bs-card-bg, var(--bs-body-bg)) 100%);
        }
        
        .plan-header {
            text-align: center;
            margin-bottom: 1.5rem;
        }
        
        .plan-badge {
            position: absolute;
            top: 12px;
            right: 12px;
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .plan-icon {
            width: 60px;
            height: 60px;
            border-radius: var(--bs-border-radius);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1rem;
            background-color: var(--bs-primary-bg-subtle) !important;
        }
        
        .plan-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
            color: var(--bs-heading-color, inherit);
        }
        
        .plan-subtitle {
            color: var(--bs-secondary-color);
            font-size: 0.875rem;
        }
        
        .plan-price {
            text-align: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1.5rem;
            border-bottom: 1px solid var(--bs-border-color);
        }
        
        .plan-price h2 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            color: var(--bs-heading-color, inherit);
        }
        
        .plan-features ul {
            list-style: none;
            padding: 0;
            margin: 0 0 1.5rem 0;
        }
        
        .plan-features li {
            padding: 0.5rem 0;
            display: flex;
            align-items: center;
            color: var(--bs-body-color);
        }
        
        .plan-features i {
            margin-right: 0.75rem;
            font-size: 0.875rem;
        }
        
        .plan-action {
            margin-top: auto;
        }
        
        .plan-action .btn {
            width: 100%;
        }
        
        /* Subscription Details in Modal */
        .subscription-details {
            background: var(--bs-tertiary-bg);
            border-radius: var(--bs-border-radius);
            padding: 1rem;
            border: 1px solid var(--bs-border-color);
        }
        
        /* Theme-specific overrides for better contrast */
        [data-bs-theme="dark"] .plan-card {
            background-color: var(--bs-secondary-bg, #1f2937);
        }
        
        [data-bs-theme="dark"] .plan-card.active-plan {
            background: linear-gradient(135deg, 
                color-mix(in srgb, var(--bs-success) 20%, transparent) 0%, 
                var(--bs-secondary-bg, #1f2937) 100%);
        }
        
        [data-bs-theme="dark"] .text-muted {
            color: var(--bs-secondary-color) !important;
        }
        
        /* Ensure card inherits proper background */
        .card {
            background-color: var(--bs-card-bg, var(--bs-body-bg));
            border-color: var(--bs-border-color);
        }
        
        .card-header {
            background-color: var(--bs-card-cap-bg, var(--bs-secondary-bg));
            border-bottom-color: var(--bs-border-color);
            color: var(--bs-heading-color, inherit);
        }
        
        /* Table theming */
        .table {
            color: var(--bs-body-color);
            border-color: var(--bs-border-color);
        }
        
        .table th {
            background-color: var(--bs-secondary-bg);
            border-color: var(--bs-border-color);
            color: var(--bs-heading-color, inherit);
        }
        
        .table td {
            border-color: var(--bs-border-color);
        }
        
        .table-hover tbody tr:hover {
            background-color: var(--bs-tertiary-bg);
        }

        .modal-backdrop {
            display: none;
        }
    </style>
    
    <!-- AJAX Script for Subscription - Using Your EXACT Pattern -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <!-- AJAX Script for Subscription -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function () {
    // Handle form submission for all subscribe forms
    $(document).on('submit', '.subscribe-form', function (e) {
        e.preventDefault(); // stop page reload
        
        var form = $(this);
        var modal = form.closest('.modal');
        var planId = form.find('input[name="bot_id"]').val();
        var submitBtn = form.find('.subscribe-btn');
        
        // Disable button and show loading
        submitBtn.prop('disabled', true).html('<i class="fi fi-rr-spinner"></i> Processing...');
        
        $.ajax({
            url: "subscribe_bot.php",
            type: "POST",
            data: form.serialize(),
            dataType: 'html',
            success: function (response) {
                // Close the modal
                var bootstrapModal = bootstrap.Modal.getInstance(modal[0]);
                if (bootstrapModal) {
                    bootstrapModal.hide();
                }
                
                // Show response in result div
                $("#result").html(response);
                
                // Reload page after 2 seconds if success message shown
                setTimeout(function() {
                    if (response.includes('success') || response.includes('Success')) {
                        window.location.reload();
                    }
                }, 2000);
            },
            error: function () {
                $("#result").html('<div class="alert alert-danger">Something went wrong</div>');
                submitBtn.prop('disabled', false).html('<i class="fi fi-rr-shopping-cart"></i> Confirm Subscription');
            },
            complete: function() {
                // Re-enable button if not redirected
                setTimeout(function() {
                    submitBtn.prop('disabled', false).html('<i class="fi fi-rr-shopping-cart"></i> Confirm Subscription');
                }, 3000);
            }
        });
    });
    
    // Clear result div when modal is closed
    $('.modal').on('hidden.bs.modal', function () {
        $("#result").html('');
    });
});
</script>
            
</body>
</html>

<?php
// Close database connection
mysqli_close($conn);
?>