<?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';

// PIN for confirmation
$admin_pin = "1234"; // Change this to a secure PIN

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

// Status colors
$status_colors = array(
    'active' => 'success',
    'pending' => 'warning',
    'expired' => 'danger',
    'cancelled' => 'secondary'
);

// 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'] : '';
    $target_id = isset($_POST['subscription_id']) ? intval($_POST['subscription_id']) : 0;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        // Get subscription details for notifications
        $sub_details_sql = "SELECT s.*, u.id as user_id, u.first_name, u.last_name, u.email, p.plan_name, p.daily_roi_percentage 
                           FROM user_bot_subscriptions s
                           LEFT JOIN users u ON s.user_id = u.id
                           LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                           WHERE s.id = $target_id";
        $sub_details_result = mysqli_query($conn, $sub_details_sql);
        $subscription_data = mysqli_fetch_assoc($sub_details_result);
        
        switch ($action_type) {
            case 'update_status':
                $new_status = isset($_POST['status']) ? $_POST['status'] : '';
                $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
                $old_status = $subscription_data['status'];
                
                if ($target_id > 0 && in_array($new_status, ['active', 'pending', 'expired', 'cancelled'])) {
                    $sql = "UPDATE user_bot_subscriptions SET status = '$new_status', updated_at = NOW() WHERE id = $target_id";
                    if (mysqli_query($conn, $sql)) {
                        // Log activity
                        logAdminActivity(
                            'Bot Subscription Status Updated',
                            "Changed subscription ID $target_id status from $old_status to $new_status. Reason: $reason",
                            'Trading Bots',
                            $target_id,
                            'user_bot_subscriptions'
                        );
                        
                        // NOTIFICATION: Bot Status Changed (USER)
                        if ($subscription_data['email']) {
                            if ($new_status == 'active') {
                                $mail_subject = "Your Trading Bot is Now Active!";
                                $mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Hello <span class='user-name'>" . $subscription_data['first_name'] . "</span>,</h2>
                                                    
                                                    <p class='message'>
                                                        Great news! Your trading bot has been <strong>activated</strong> by our admin team and is now ready to start trading!
                                                    </p>

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

                                                    <!-- Admin Note -->
                                                    " . ($reason ? "
                                                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                        <h4 style='color: #0056b3;'>📝 Admin Note</h4>
                                                        <p style='color: #0056b3;'>" . $reason . "</p>
                                                    </div>" : "") . "

                                                    <!-- Action Button -->
                                                    <div style='text-align: center; margin: 30px 0;'>
                                                        <a href='" . $myUrl . "/trading_bots.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                            View Your Bot
                                                        </a>
                                                    </div>
                                                </div>";
                            } elseif ($new_status == 'cancelled') {
                                $mail_subject = "Your Trading Bot Has Been Cancelled";
                                $mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Hello <span class='user-name'>" . $subscription_data['first_name'] . "</span>,</h2>
                                                    
                                                    <p class='message'>
                                                        Your trading bot subscription has been <strong>cancelled</strong> by our admin team.
                                                    </p>

                                                    <!-- Cancellation Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Bot Subscription ID:</strong> BOT-" . $target_id . "<br>
                                                            <strong>Bot Plan:</strong> " . $subscription_data['plan_name'] . "<br>
                                                            <strong>Cancellation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                            <strong>Reason:</strong> " . ($reason ?: 'Administrative action') . "<br>
                                                            <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>CANCELLED</span>
                                                        </div>
                                                    </div>

                                                    <!-- Support Section -->
                                                    <div class='support-section'>
                                                        <p class='support-text'>If you have questions about this cancellation, please contact support.</p>
                                                        <a href='" . $myUrl . "/support.php' class='support-link'>Contact Support</a>
                                                    </div>
                                                </div>";
                            } elseif ($new_status == 'expired') {
                                $mail_subject = "Your Trading Bot Has Expired";
                                $mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Hello <span class='user-name'>" . $subscription_data['first_name'] . "</span>,</h2>
                                                    
                                                    <p class='message'>
                                                        Your trading bot subscription has <strong>expired</strong>. Please renew to continue trading.
                                                    </p>

                                                    <!-- Expiry Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Bot Subscription ID:</strong> BOT-" . $target_id . "<br>
                                                            <strong>Bot Plan:</strong> " . $subscription_data['plan_name'] . "<br>
                                                            <strong>Expiry Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                            <strong>Status:</strong> <span style='color: #ffc107; font-weight: bold;'>EXPIRED</span>
                                                        </div>
                                                    </div>

                                                    <!-- Renewal Button -->
                                                    <div style='text-align: center; margin: 30px 0;'>
                                                        <a href='" . $myUrl . "/trading_bots.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                            Renew Subscription
                                                        </a>
                                                    </div>
                                                </div>";
                            }
                            
                            if (isset($mail_subject) && isset($mail_message)) {
                                $user_email = $subscription_data['email'];
                                $first_name = $subscription_data['first_name'];
                                require_once("../proccess/mail_sender.php");
                            }
                        }
                        
                        $success = "Subscription status updated successfully!";
                    } else {
                        $error = "Failed to update subscription status.";
                    }
                }
                break;
                
            case 'update_balance':
                $balance_type = isset($_POST['balance_type']) ? $_POST['balance_type'] : '';
                $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
                $note = isset($_POST['note']) ? mysqli_real_escape_string($conn, $_POST['note']) : '';
                $old_balance = $subscription_data['trading_balance'];
                
                if ($target_id > 0 && $amount > 0) {
                    if ($balance_type == 'add') {
                        $sql = "UPDATE user_bot_subscriptions SET trading_balance = trading_balance + $amount WHERE id = $target_id";
                        $action_desc = "Added $$amount to trading balance";
                        $new_balance = $old_balance + $amount;
                    } else {
                        $sql = "UPDATE user_bot_subscriptions SET trading_balance = trading_balance - $amount WHERE id = $target_id";
                        $action_desc = "Deducted $$amount from trading balance";
                        $new_balance = $old_balance - $amount;
                    }
                    
                    if (mysqli_query($conn, $sql)) {
                        // Add transaction record
                        $sub_sql = "SELECT user_id FROM user_bot_subscriptions WHERE id = $target_id";
                        $sub_result = mysqli_query($conn, $sub_sql);
                        $sub_data = mysqli_fetch_assoc($sub_result);
                        $user_id = $sub_data['user_id'] ?: 0;
                        
                        if ($user_id > 0) {
                            $txn_type = $balance_type == 'add' ? 'deposit' : 'withdrawal';
                            $txn_sql = "INSERT INTO bot_transactions (subscription_id, transaction_date, transaction_type, amount, description, created_at) 
                                       VALUES ($target_id, CURDATE(), 'fee', $amount, 'Admin manual adjustment: $note', NOW())";
                            mysqli_query($conn, $txn_sql);
                        }
                        
                        // Log activity
                        logAdminActivity(
                            'Bot Subscription Balance Updated',
                            "$action_desc for subscription ID $target_id. Note: $note",
                            'Trading Bots',
                            $target_id,
                            'user_bot_subscriptions'
                        );
                        
                        // NOTIFICATION: Balance Updated (USER)
                        if ($subscription_data['email']) {
                            $mail_subject = "Trading Bot Balance Updated";
                            $mail_message = "<!-- Content Section -->
                                            <div class='email-content'>
                                                <h2 class='greeting'>Hello <span class='user-name'>" . $subscription_data['first_name'] . "</span>,</h2>
                                                
                                                <p class='message'>
                                                    Your trading bot's balance has been updated by our admin team.
                                                </p>

                                                <!-- Balance Update Details -->
                                                <div class='details-section'>
                                                    <div class='detail-box'>
                                                        <strong>Bot Subscription ID:</strong> BOT-" . $target_id . "<br>
                                                        <strong>Bot Plan:</strong> " . $subscription_data['plan_name'] . "<br>
                                                        <strong>Update Type:</strong> " . ($balance_type == 'add' ? 'Addition' : 'Deduction') . "<br>
                                                        <strong>Amount:</strong> <span style='color: " . ($balance_type == 'add' ? '#28a745' : '#dc3545') . ";'>" . ($balance_type == 'add' ? '+' : '-') . "$" . number_format($amount, 2) . "</span><br>
                                                        <strong>Previous Balance:</strong> $" . number_format($old_balance, 2) . "<br>
                                                        <strong>New Balance:</strong> $" . number_format($new_balance, 2) . "<br>
                                                        <strong>Update Date:</strong> " . date('F j, Y g:i A') . "
                                                    </div>
                                                </div>

                                                <!-- Admin Note -->
                                                " . ($note ? "
                                                <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                    <h4 style='color: #0056b3;'>📝 Admin Note</h4>
                                                    <p style='color: #0056b3;'>" . $note . "</p>
                                                </div>" : "") . "

                                                <!-- View Balance Button -->
                                                <div style='text-align: center; margin: 30px 0;'>
                                                    <a href='" . $myUrl . "/bot-details.php?id=" . $target_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                        View Bot Details
                                                    </a>
                                                </div>
                                            </div>";

                            $user_email = $subscription_data['email'];
                            $first_name = $subscription_data['first_name'];
                            require_once("../proccess/mail_sender.php");
                        }
                        
                        $success = "Subscription balance updated successfully!";
                    } else {
                        $error = "Failed to update subscription balance.";
                    }
                }
                break;
                
            case 'extend_subscription':
                $days = isset($_POST['days']) ? intval($_POST['days']) : 30;
                $note = isset($_POST['note']) ? mysqli_real_escape_string($conn, $_POST['note']) : '';
                $old_end = $subscription_data['subscription_end'];
                
                if ($target_id > 0 && $days > 0) {
                    // Get current subscription end date
                    $get_sql = "SELECT subscription_end FROM user_bot_subscriptions WHERE id = $target_id";
                    $get_result = mysqli_query($conn, $get_sql);
                    $sub_data = mysqli_fetch_assoc($get_result);
                    
                    if ($sub_data) {
                        $current_end = $sub_data['subscription_end'];
                        $new_end = date('Y-m-d', strtotime("$current_end + $days days"));
                        
                        $sql = "UPDATE user_bot_subscriptions SET subscription_end = '$new_end', updated_at = NOW() WHERE id = $target_id";
                        
                        if (mysqli_query($conn, $sql)) {
                            // Log activity
                            logAdminActivity(
                                'Bot Subscription Extended',
                                "Extended subscription ID $target_id by $days days. New end date: $new_end. Note: $note",
                                'Trading Bots',
                                $target_id,
                                'user_bot_subscriptions'
                            );
                            
                            // NOTIFICATION: Subscription Extended (USER)
                            if ($subscription_data['email']) {
                                $mail_subject = "Your Trading Bot Subscription Has Been Extended";
                                $mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Hello <span class='user-name'>" . $subscription_data['first_name'] . "</span>,</h2>
                                                    
                                                    <p class='message'>
                                                        Good news! Your trading bot subscription has been <strong>extended by " . $days . " days</strong>.
                                                    </p>

                                                    <!-- Extension Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Bot Subscription ID:</strong> BOT-" . $target_id . "<br>
                                                            <strong>Bot Plan:</strong> " . $subscription_data['plan_name'] . "<br>
                                                            <strong>Extension Days:</strong> " . $days . " days<br>
                                                            <strong>Previous End Date:</strong> " . date('F j, Y', strtotime($current_end)) . "<br>
                                                            <strong>New End Date:</strong> " . date('F j, Y', strtotime($new_end)) . "<br>
                                                            <strong>Extension Date:</strong> " . date('F j, Y g:i A') . "
                                                        </div>
                                                    </div>

                                                    <!-- Admin Note -->
                                                    " . ($note ? "
                                                    <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                        <h4 style='color: #0056b3;'>📝 Admin Note</h4>
                                                        <p style='color: #0056b3;'>" . $note . "</p>
                                                    </div>" : "") . "

                                                    <!-- View Subscription Button -->
                                                    <div style='text-align: center; margin: 30px 0;'>
                                                        <a href='" . $myUrl . "/bot-details.php?id=" . $target_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                            View Subscription
                                                        </a>
                                                    </div>
                                                </div>";

                                $user_email = $subscription_data['email'];
                                $first_name = $subscription_data['first_name'];
                                require_once("../proccess/mail_sender.php");
                            }
                            
                            $success = "Subscription extended by $days days!";
                        } else {
                            $error = "Failed to extend subscription.";
                        }
                    }
                }
                break;
                
            case 'delete_subscription':
                if ($target_id > 0) {
                    // Get subscription info before deletion
                    $sub_sql = "SELECT s.*, u.username, u.email, u.first_name, p.plan_name 
                               FROM user_bot_subscriptions s
                               LEFT JOIN users u ON s.user_id = u.id
                               LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                               WHERE s.id = $target_id";
                    $sub_result = mysqli_query($conn, $sub_sql);
                    $sub_data = mysqli_fetch_assoc($sub_result);
                    
                    if ($sub_data) {
                        $username = $sub_data['username'] ?: '';
                        $plan_name = $sub_data['plan_name'] ?: '';
                        $user_email = $sub_data['email'] ?: '';
                        $first_name = $sub_data['first_name'] ?: '';
                        
                        // Update status to cancelled
                        $sql = "UPDATE user_bot_subscriptions SET status = 'cancelled', updated_at = NOW() WHERE id = $target_id";
                        
                        if (mysqli_query($conn, $sql)) {
                            // Log activity
                            logAdminActivity(
                                'Bot Subscription Cancelled',
                                "Cancelled subscription ID $target_id for user $username ($plan_name)",
                                'Trading Bots',
                                $target_id,
                                'user_bot_subscriptions'
                            );
                            
                            // NOTIFICATION: Subscription Cancelled (USER)
                            if ($user_email) {
                                $mail_subject = "Your Trading Bot Subscription Has Been Cancelled";
                                $mail_message = "<!-- Content Section -->
                                                <div class='email-content'>
                                                    <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                                                    
                                                    <p class='message'>
                                                        Your trading bot subscription has been cancelled by our admin team.
                                                    </p>

                                                    <!-- Cancellation Details -->
                                                    <div class='details-section'>
                                                        <div class='detail-box'>
                                                            <strong>Bot Subscription ID:</strong> BOT-" . $target_id . "<br>
                                                            <strong>Bot Plan:</strong> " . $plan_name . "<br>
                                                            <strong>Cancellation Date:</strong> " . date('F j, Y g:i A') . "<br>
                                                            <strong>Status:</strong> <span style='color: #dc3545; font-weight: bold;'>CANCELLED</span>
                                                        </div>
                                                    </div>

                                                    <!-- What Happens Next -->
                                                    <div class='next-steps'>
                                                        <h3 style='color: #2c3e50;'>📋 What Happens Next?</h3>
                                                        <p style='color: #6c757d;'>
                                                            • The bot will stop all trading activities<br>
                                                            • Your trading balance has been unlocked<br>
                                                            • You can subscribe to a new bot anytime
                                                        </p>
                                                    </div>

                                                    <!-- Support Section -->
                                                    <div class='support-section'>
                                                        <p class='support-text'>If you have questions, please contact our support team.</p>
                                                        <a href='" . $myUrl . "/support.php' class='support-link'>Contact Support</a>
                                                    </div>
                                                </div>";

                                require_once("../proccess/mail_sender.php");
                            }
                            
                            $success = "Subscription has been cancelled!";
                        } else {
                            $error = "Failed to cancel subscription.";
                        }
                    }
                }
                break;
        }
    }
}

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

// Build query
$sql = "SELECT s.*, u.username, u.email, u.phone, p.plan_name, p.subscription_fee, p.daily_roi_percentage
        FROM user_bot_subscriptions s
        LEFT JOIN users u ON s.user_id = u.id
        LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
        WHERE 1=1";

$count_sql = "SELECT COUNT(*) as total 
              FROM user_bot_subscriptions s
              LEFT JOIN users u ON s.user_id = u.id
              WHERE 1=1";

// Apply filters
if ($filter_status) {
    $sql .= " AND s.status = '$filter_status'";
    $count_sql .= " AND s.status = '$filter_status'";
}

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

if ($search) {
    $sql .= " AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%' OR p.plan_name LIKE '%$search%')";
    $count_sql .= " AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%' OR p.plan_name LIKE '%$search%')";
}

// Get counts for stats
$stats_sql = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = 'expired' THEN 1 ELSE 0 END) as expired,
                SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled,
                SUM(trading_balance) as total_balance,
                SUM(total_profit) as total_profit
              FROM user_bot_subscriptions";
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats);

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

// Add sorting
$sql .= " ORDER BY s.created_at DESC";

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

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

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

		  	<!-- Content Wrapper. Contains page content -->
			<div class="content-wrapper">
				<div class="container-full">
					<!-- Main content -->
					<section class="content">
						<div class="row">
							<div class="col-12">
								<div class="box">
									<div class="box-header">
										<h4 class="box-title"><i class="fas fa-robot me-2"></i>Bot Subscriptions Management</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addSubscriptionModal">
												<i class="fas fa-plus me-1"></i> Add Subscription
											</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'] ?: 0; ?></h1>
														<p class="text-white mb-0">Total Subscriptions</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'] ?: 0; ?></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['pending'] ?: 0; ?></h1>
														<p class="text-white mb-0">Pending</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['expired'] ?: 0; ?></h1>
														<p class="text-white mb-0">Expired</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 number_format($stats['total_balance'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Balance</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['total_profit'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Profit</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-9">
												<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</option>
																<option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																<option value="expired" <?php echo $filter_status == 'expired' ? 'selected' : ''; ?>>Expired</option>
																<option value="cancelled" <?php echo $filter_status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<select class="form-control" name="plan" onchange="this.form.submit()">
																<option value="0">All Plans</option>
																<?php while ($plan = mysqli_fetch_assoc($plans_result)): ?>
																	<option value="<?php echo $plan['id']; ?>" <?php echo $filter_plan == $plan['id'] ? 'selected' : ''; ?>>
																		<?php echo htmlspecialchars($plan['plan_name']); ?>
																	</option>
																<?php endwhile; ?>
															</select>
														</div>
													</div>
													<div class="col-md-4">
														<div class="form-group">
															<input type="text" class="form-control" name="search" placeholder="Search user or plan..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-2">
														<button type="submit" class="btn btn-primary"><i class="fas fa-search me-1"></i> Search</button>
														<?php if ($search || $filter_status || $filter_plan): ?>
															<a href="bot_subscriptions.php" class="btn btn-secondary mt-1">Clear</a>
														<?php endif; ?>
													</div>
												</form>
											</div>
											<div class="col-md-3 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_subscriptions.php?format=csv&status=<?php echo $filter_status; ?>&plan=<?php echo $filter_plan; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-csv"></i> CSV</a>
														<a class="dropdown-item" href="export_subscriptions.php?format=excel&status=<?php echo $filter_status; ?>&plan=<?php echo $filter_plan; ?>&search=<?php echo urlencode($search); ?>"><i class="fas fa-file-excel"></i> Excel</a>
														<a class="dropdown-item" href="export_subscriptions.php?format=pdf&status=<?php echo $filter_status; ?>&plan=<?php echo $filter_plan; ?>&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; ?>
										
										<!-- Subscriptions Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="subscriptionsTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>User</th>
														<th>Plan</th>
														<th>Trading Balance</th>
														<th>Profit</th>
														<th>Status</th>
														<th>Period</th>
														<th>Auto Renew</th>
														<th>Created</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($subscription = mysqli_fetch_assoc($result)): ?>
															<?php
															$status_color = isset($status_colors[$subscription['status']]) ? $status_colors[$subscription['status']] : 'secondary';
															$created_date = date('M d, Y', strtotime($subscription['created_at']));
															$start_date = date('M d, Y', strtotime($subscription['subscription_start']));
															$end_date = date('M d, Y', strtotime($subscription['subscription_end']));
															
															// Calculate days remaining
															$today = new DateTime();
															$end = new DateTime($subscription['subscription_end']);
															$interval = $today->diff($end);
															$days_remaining = $interval->invert ? 0 : $interval->days;
															
															// Calculate expected daily profit
															$daily_profit = ($subscription['trading_balance'] * $subscription['daily_roi_percentage']) / 100;
															?>
															<tr>
																<td><?php echo $subscription['id']; ?></td>
																<td>
																	<div class="d-flex align-items-center">
																		<div class="me-10">
																			<div class="bg-primary rounded-circle w-40 h-40 d-flex align-items-center justify-content-center">
																				<i class="fas fa-user text-white"></i>
																			</div>
																		</div>
																		<div>
																			<p class="mb-0 fw-500"><?php echo htmlspecialchars($subscription['username']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($subscription['email']); ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<p class="mb-0 fw-500"><?php echo htmlspecialchars($subscription['plan_name']); ?></p>
																	<small class="text-mute">Fee: $<?php echo number_format($subscription['subscription_fee'], 2); ?>/month</small>
																</td>
																<td>
																	<p class="mb-0 fw-500 text-primary">$<?php echo number_format($subscription['trading_balance'], 2); ?></p>
																	<small class="text-mute">Daily ROI: <?php echo $subscription['daily_roi_percentage']; ?>%</small>
																</td>
																<td>
																	<p class="mb-0 fw-500 text-success">$<?php echo number_format($subscription['total_profit'], 2); ?></p>
																	<small class="text-mute">Expected: $<?php echo number_format($daily_profit, 2); ?>/day</small>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($subscription['status']); ?></span>
																	<?php if ($subscription['status'] == 'active'): ?>
																		<br><small class="text-mute"><?php echo $days_remaining; ?> days left</small>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $start_date; ?> - <?php echo $end_date; ?></p>
																	<small class="text-mute">Duration: <?php echo $days_remaining + ($interval->invert ? 0 : 0); ?> days</small>
																</td>
																<td>
																	<?php if ($subscription['auto_renew'] == 1): ?>
																		<span class="badge bg-success"><i class="fas fa-check me-1"></i> Yes</span>
																	<?php else: ?>
																		<span class="badge bg-secondary"><i class="fas fa-times me-1"></i> No</span>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $created_date; ?></p>
																	<small class="text-mute"><?php echo time_ago($subscription['created_at']); ?> ago</small>
																</td>
																<td>
																	<div class="btn-group">
																		<button type="button" class="btn btn-light btn-sm dropdown-toggle" data-bs-toggle="dropdown">
																			<i class="fas fa-cog"></i>
																		</button>
																		<div class="dropdown-menu">
																			<a class="dropdown-item" href="view_subscription.php?id=<?php echo $subscription['id']; ?>"><i class="fas fa-eye me-2"></i> View Details</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#statusModal" data-subscription-id="<?php echo $subscription['id']; ?>" data-current-status="<?php echo $subscription['status']; ?>"><i class="fas fa-sync me-2"></i> Change Status</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#balanceModal" data-subscription-id="<?php echo $subscription['id']; ?>"><i class="fas fa-money-bill-wave me-2"></i> Adjust Balance</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#extendModal" data-subscription-id="<?php echo $subscription['id']; ?>"><i class="fas fa-calendar-plus me-2"></i> Extend Period</a>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $subscription['id']; ?>)"><i class="fas fa-trash me-2"></i> Cancel Subscription</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 subscriptions found</h5>
																<p class="text-mute">Try adjusting your search or filters</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 Changing Subscription Status -->
		<div class="modal fade" id="statusModal" tabindex="-1" aria-labelledby="statusModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="statusModalLabel">Change Subscription Status</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_status">
							<input type="hidden" name="subscription_id" id="statusSubscriptionId">
							
							<div class="mb-3">
								<label class="form-label">New Status</label>
								<select class="form-control" name="status" required>
									<option value="active">Active</option>
									<option value="pending">Pending</option>
									<option value="expired">Expired</option>
									<option value="cancelled">Cancelled</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Reason (Optional)</label>
								<textarea class="form-control" name="reason" rows="3" placeholder="Enter reason for status change..."></textarea>
							</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 Status</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adjusting Balance -->
		<div class="modal fade" id="balanceModal" tabindex="-1" aria-labelledby="balanceModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="balanceModalLabel">Adjust Trading Balance</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_balance">
							<input type="hidden" name="subscription_id" id="balanceSubscriptionId">
							
							<div class="mb-3">
								<label class="form-label">Action</label>
								<select class="form-control" name="balance_type" required>
									<option value="add">Add Funds</option>
									<option value="deduct">Deduct Funds</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Amount ($)</label>
								<input type="number" class="form-control" name="amount" step="0.01" min="0.01" required placeholder="0.00">
							</div>
							
							<div class="mb-3">
								<label class="form-label">Note (Optional)</label>
								<textarea class="form-control" name="note" rows="3" placeholder="Enter reason for balance adjustment..."></textarea>
							</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 Balance</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Extending Subscription -->
		<div class="modal fade" id="extendModal" tabindex="-1" aria-labelledby="extendModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="extendModalLabel">Extend Subscription Period</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="extend_subscription">
							<input type="hidden" name="subscription_id" id="extendSubscriptionId">
							
							<div class="mb-3">
								<label class="form-label">Extension Period (Days)</label>
								<select class="form-control" name="days" required>
									<option value="7">7 Days (1 Week)</option>
									<option value="30" selected>30 Days (1 Month)</option>
									<option value="90">90 Days (3 Months)</option>
									<option value="180">180 Days (6 Months)</option>
									<option value="365">365 Days (1 Year)</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Note (Optional)</label>
								<textarea class="form-control" name="note" rows="3" placeholder="Enter reason for extension..."></textarea>
							</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">Extend Subscription</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Adding New Subscription -->
		<div class="modal fade" id="addSubscriptionModal" tabindex="-1" aria-labelledby="addSubscriptionModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<form method="POST" action="add_subscription.php">
						<div class="modal-header">
							<h5 class="modal-title" id="addSubscriptionModalLabel">Add New Subscription</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">User <span class="text-danger">*</span></label>
										<select class="form-control" name="user_id" required>
											<option value="">Select User</option>
											<?php
											$users_sql = "SELECT id, username, email FROM users WHERE status = 'verified' ORDER BY username";
											$users_result = mysqli_query($conn, $users_sql);
											while ($user = mysqli_fetch_assoc($users_result)) {
												echo "<option value='{$user['id']}'>{$user['username']} ({$user['email']})</option>";
											}
											?>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Bot Plan <span class="text-danger">*</span></label>
										<select class="form-control" name="bot_plan_id" required>
											<option value="">Select Plan</option>
											<?php
											mysqli_data_seek($plans_result, 0); // Reset pointer
											while ($plan = mysqli_fetch_assoc($plans_result)) {
												echo "<option value='{$plan['id']}'>{$plan['plan_name']}</option>";
											}
											?>
										</select>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Trading Balance ($) <span class="text-danger">*</span></label>
										<input type="number" class="form-control" name="trading_balance" step="0.01" min="100" required placeholder="Minimum $100">
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Subscription Period (Days) <span class="text-danger">*</span></label>
										<select class="form-control" name="duration_days" required>
											<option value="7">7 Days</option>
											<option value="30" selected>30 Days</option>
											<option value="90">90 Days</option>
											<option value="180">180 Days</option>
											<option value="365">365 Days</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Status</label>
										<select class="form-control" name="status">
											<option value="active">Active</option>
											<option value="pending" selected>Pending</option>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Auto Renew</label>
										<select class="form-control" name="auto_renew">
											<option value="1">Yes</option>
											<option value="0" selected>No</option>
										</select>
									</div>
								</div>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Notes (Optional)</label>
								<textarea class="form-control" name="notes" rows="3" placeholder="Enter any notes about this subscription..."></textarea>
							</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 Subscription</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Deleting Subscription (hidden form) -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_subscription">
			<input type="hidden" name="subscription_id" id="deleteSubscriptionId">
			<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
			$('#subscriptionsTable').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"
					}
				}
			});
			
			// Status Modal
			$('#statusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var subscriptionId = button.data('subscription-id');
				var currentStatus = button.data('current-status');
				var modal = $(this);
				
				modal.find('#statusSubscriptionId').val(subscriptionId);
				modal.find('select[name="status"]').val(currentStatus);
				modal.find('.modal-title').text('Change Status for Subscription #' + subscriptionId);
			});
			
			// Balance Modal
			$('#balanceModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var subscriptionId = button.data('subscription-id');
				var modal = $(this);
				
				modal.find('#balanceSubscriptionId').val(subscriptionId);
				modal.find('.modal-title').text('Adjust Balance for Subscription #' + subscriptionId);
			});
			
			// Extend Modal
			$('#extendModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var subscriptionId = button.data('subscription-id');
				var modal = $(this);
				
				modal.find('#extendSubscriptionId').val(subscriptionId);
				modal.find('.modal-title').text('Extend Subscription #' + subscriptionId);
			});
		});
		
		// Confirm Delete with PIN
		function confirmDelete(subscriptionId) {
			Swal.fire({
				title: 'Cancel Subscription?',
				html: `
					<p>This will cancel the subscription. The user will no longer have access to the trading bot.</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: 'Cancel Subscription',
				cancelButtonText: 'Keep Active',
				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('deleteSubscriptionId').value = subscriptionId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_subscription_stats.php',
				type: 'GET',
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total);
						$('.bg-gradient-success .fw-500').text(stats.active);
						$('.bg-gradient-warning .fw-500').text(stats.pending);
						$('.bg-gradient-danger .fw-500').text(stats.expired);
						$('.bg-gradient-info .fw-500').text('$' + stats.total_balance);
						$('.bg-gradient-secondary .fw-500').text('$' + stats.total_profit);
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}, 30000); // 30 seconds
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 10px;
			border-radius: 20px;
			font-size: 12px;
			font-weight: 600;
		}
		.pull-up {
			transition: transform 0.3s ease;
		}
		.pull-up:hover {
			transform: translateY(-5px);
		}
		</style>
		
	</body>
</html>

<?php
// Helper function to show time ago
function time_ago($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return $diff . " seconds";
    } elseif ($diff < 3600) {
        return floor($diff / 60) . " minutes";
    } elseif ($diff < 86400) {
        return floor($diff / 3600) . " hours";
    } elseif ($diff < 604800) {
        return floor($diff / 86400) . " days";
    } elseif ($diff < 2592000) {
        return floor($diff / 604800) . " weeks";
    } elseif ($diff < 31536000) {
        return floor($diff / 2592000) . " months";
    } else {
        return floor($diff / 31536000) . " years";
    }
}
?>