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

// PIN for confirmation
$admin_pin = "1234";

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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';
    $action_type = isset($_POST['action_type']) ? $_POST['action_type'] : '';
    $target_id = isset($_POST['transaction_id']) ? intval($_POST['transaction_id']) : 0;
    
    // Get admin details for notification
    $admin_id = $_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 1;
    $adminQuery = mysqli_query($conn, "SELECT first_name, email FROM users WHERE id='$admin_id'");
    $adminData = mysqli_fetch_assoc($adminQuery);
    $admin_name = $adminData['first_name'] ?? $_SESSION['admin_name'] ?? 'System Administrator';
    $admin_email = $adminData['email'] ?? 'admin@system.com';
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'add_transaction':
                $subscription_id = intval($_POST['subscription_id']);
                $transaction_date = mysqli_real_escape_string($conn, $_POST['transaction_date']);
                $transaction_type = mysqli_real_escape_string($conn, $_POST['transaction_type']);
                $amount = floatval($_POST['amount']);
                $description = mysqli_real_escape_string($conn, $_POST['description']);
                
                $sql = "INSERT INTO bot_transactions (subscription_id, transaction_date, transaction_type, amount, description, created_at) 
                        VALUES ($subscription_id, '$transaction_date', '$transaction_type', $amount, '$description', NOW())";
                
                if (mysqli_query($conn, $sql)) {
                    $new_transaction_id = mysqli_insert_id($conn);
                    
                    // Update subscription profit if it's a profit transaction
                    if ($transaction_type == 'profit') {
                        $update_sql = "UPDATE user_bot_subscriptions SET total_profit = total_profit + $amount WHERE id = $subscription_id";
                        mysqli_query($conn, $update_sql);
                    }
                    
                    // Get subscription details for logging and notification
                    $sub_sql = "SELECT s.id, s.user_id, 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 = $subscription_id";
                    $sub_result = mysqli_query($conn, $sub_sql);
                    $sub_data = mysqli_fetch_assoc($sub_result);
                    
                    logAdminActivity(
                        'Bot Transaction Added',
                        "Added $transaction_type transaction ($$amount) for subscription #$subscription_id (User: {$sub_data['username']}, Plan: {$sub_data['plan_name']})",
                        'Bot Transactions',
                        $new_transaction_id,
                        'bot_transactions'
                    );
                    
                    // NOTIFICATION: Bot Transaction Added (USER)
                    if ($transaction_type == 'profit' || $transaction_type == 'loss') {
                        $mail_subject = "Bot Trading Update - " . ($transaction_type == 'profit' ? 'Profit Earned' : 'Loss Recorded');
                        $mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Hello <span class='user-name'>" . $sub_data['first_name'] . "</span>,</h2>
                                            
                                            <p class='message'>
                                                Your trading bot has recorded a new " . $transaction_type . " transaction.
                                            </p>

                                            <!-- Transaction Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Transaction ID:</strong> TXN-" . $new_transaction_id . "<br>
                                                    <strong>Bot Plan:</strong> " . $sub_data['plan_name'] . "<br>
                                                    <strong>Transaction Type:</strong> <span style='color: " . ($transaction_type == 'profit' ? '#28a745' : '#dc3545') . "; font-weight: bold;'>" . strtoupper($transaction_type) . "</span><br>
                                                    <strong>Amount:</strong> <span style='color: " . ($transaction_type == 'profit' ? '#28a745' : '#dc3545') . ";'>$" . number_format($amount, 2) . "</span><br>
                                                    <strong>Date:</strong> " . date('F j, Y g:i A', strtotime($transaction_date)) . "<br>
                                                    <strong>Description:</strong> " . $description . "<br>
                                                    <strong>Processed By:</strong> " . $admin_name . " (Admin)
                                                </div>
                                            </div>

                                            <!-- Bot Performance -->
                                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #0056b3;'>📊 Bot Performance Update</h4>
                                                <p style='color: #0056b3;'>
                                                    This transaction has been recorded to your bot's performance history.<br>
                                                    Track all your bot activities in your trading dashboard.
                                                </p>
                                            </div>

                                            <!-- Action Button -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/my-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 Bot Performance
                                                </a>
                                            </div>
                                        </div>";

                        // Send user notification
                        require_once("../proccess/mail_sender.php");
                    }
                    
                    // NOTIFICATION: Bot Transaction Added (ADMIN)
                    $admin_mail_subject = "Bot Transaction Added - " . $sub_data['plan_name'];
                    $admin_mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Bot Transaction Added</h2>
                                            
                                            <p class='message'>
                                                A new bot transaction has been manually added by an administrator.
                                            </p>

                                            <!-- Transaction Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Transaction ID:</strong> " . $new_transaction_id . "<br>
                                                    <strong>Subscription ID:</strong> " . $subscription_id . "<br>
                                                    <strong>User:</strong> " . $sub_data['username'] . " (" . $sub_data['email'] . ")<br>
                                                    <strong>Bot Plan:</strong> " . $sub_data['plan_name'] . "<br>
                                                    <strong>Type:</strong> " . $transaction_type . "<br>
                                                    <strong>Amount:</strong> $" . number_format($amount, 2) . "<br>
                                                    <strong>Description:</strong> " . $description . "<br>
                                                    <strong>Added By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Date Added:</strong> " . date('F j, Y g:i A') . "
                                                </div>
                                            </div>

                                            <!-- Admin Actions -->
                                            <div style='text-align: center; margin: 30px 0;'>
                                                <a href='" . $myUrl . "/admin/bot-transactions.php?subscription_id=" . $subscription_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;'>
                                                    View All Transactions
                                                </a>
                                            </div>
                                        </div>";

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Transaction added successfully!";
                } else {
                    $error = "Failed to add transaction.";
                }
                break;
                
            case 'update_transaction':
                $amount = floatval($_POST['amount']);
                $description = mysqli_real_escape_string($conn, $_POST['description']);
                
                // Get old transaction data
                $old_sql = "SELECT * FROM bot_transactions WHERE id = $target_id";
                $old_result = mysqli_query($conn, $old_sql);
                $old_data = mysqli_fetch_assoc($old_result);
                
                $sql = "UPDATE bot_transactions SET amount = $amount, description = '$description', created_at = NOW() WHERE id = $target_id";
                
                if (mysqli_query($conn, $sql)) {
                    // Update subscription profit if needed
                    if ($old_data['transaction_type'] == 'profit') {
                        $diff = $amount - $old_data['amount'];
                        if ($diff != 0) {
                            $update_sql = "UPDATE user_bot_subscriptions SET total_profit = total_profit + $diff WHERE id = {$old_data['subscription_id']}";
                            mysqli_query($conn, $update_sql);
                        }
                    }
                    
                    // Get subscription details for notification
                    $sub_sql = "SELECT s.id, s.user_id, 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 = {$old_data['subscription_id']}";
                    $sub_result = mysqli_query($conn, $sub_sql);
                    $sub_data = mysqli_fetch_assoc($sub_result);
                    
                    logAdminActivity(
                        'Bot Transaction Updated',
                        "Updated transaction #$target_id (Old: \${$old_data['amount']}, New: \$$amount)",
                        'Bot Transactions',
                        $target_id,
                        'bot_transactions'
                    );
                    
                    // NOTIFICATION: Bot Transaction Updated (ADMIN)
                    $admin_mail_subject = "Bot Transaction Updated";
                    $admin_mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Bot Transaction Updated</h2>
                                            
                                            <p class='message'>
                                                A bot transaction has been modified by an administrator.
                                            </p>

                                            <!-- Update Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Transaction ID:</strong> " . $target_id . "<br>
                                                    <strong>User:</strong> " . $sub_data['username'] . "<br>
                                                    <strong>Bot Plan:</strong> " . $sub_data['plan_name'] . "<br>
                                                    <strong>Transaction Type:</strong> " . $old_data['transaction_type'] . "<br>
                                                    <strong>Old Amount:</strong> <span style='color: #dc3545;'>$" . number_format($old_data['amount'], 2) . "</span><br>
                                                    <strong>New Amount:</strong> <span style='color: #28a745;'>$" . number_format($amount, 2) . "</span><br>
                                                    <strong>Difference:</strong> " . ($diff > 0 ? '+' : '') . "$" . number_format($diff, 2) . "<br>
                                                    <strong>Updated By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Update Time:</strong> " . date('F j, Y g:i A') . "
                                                </div>
                                            </div>

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

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Transaction updated successfully!";
                } else {
                    $error = "Failed to update transaction.";
                }
                break;
                
            case 'delete_transaction':
                // Get transaction data before deletion
                $txn_sql = "SELECT bt.*, s.user_id, u.username, u.email, u.first_name, p.plan_name 
                          FROM bot_transactions bt
                          LEFT JOIN user_bot_subscriptions s ON bt.subscription_id = s.id
                          LEFT JOIN users u ON s.user_id = u.id
                          LEFT JOIN trading_bot_plans p ON s.bot_plan_id = p.id
                          WHERE bt.id = $target_id";
                $txn_result = mysqli_query($conn, $txn_sql);
                $txn_data = mysqli_fetch_assoc($txn_result);
                
                $sql = "DELETE FROM bot_transactions WHERE id = $target_id";
                
                if (mysqli_query($conn, $sql)) {
                    // Update subscription profit if it was a profit transaction
                    if ($txn_data['transaction_type'] == 'profit') {
                        $update_sql = "UPDATE user_bot_subscriptions SET total_profit = total_profit - {$txn_data['amount']} WHERE id = {$txn_data['subscription_id']}";
                        mysqli_query($conn, $update_sql);
                    }
                    
                    logAdminActivity(
                        'Bot Transaction Deleted',
                        "Deleted transaction #$target_id (Type: {$txn_data['transaction_type']}, Amount: \${$txn_data['amount']})",
                        'Bot Transactions',
                        $target_id,
                        'bot_transactions'
                    );
                    
                    // NOTIFICATION: Bot Transaction Deleted (ADMIN)
                    $admin_mail_subject = "Bot Transaction Deleted";
                    $admin_mail_message = "<!-- Content Section -->
                                        <div class='email-content'>
                                            <h2 class='greeting'>Bot Transaction Deleted</h2>
                                            
                                            <p class='message'>
                                                A bot transaction has been permanently deleted by an administrator.
                                            </p>

                                            <!-- Deletion Details -->
                                            <div class='details-section'>
                                                <div class='detail-box'>
                                                    <strong>Transaction ID:</strong> " . $target_id . "<br>
                                                    <strong>User:</strong> " . $txn_data['username'] . " (" . $txn_data['email'] . ")<br>
                                                    <strong>Bot Plan:</strong> " . $txn_data['plan_name'] . "<br>
                                                    <strong>Transaction Type:</strong> " . $txn_data['transaction_type'] . "<br>
                                                    <strong>Amount:</strong> $" . number_format($txn_data['amount'], 2) . "<br>
                                                    <strong>Description:</strong> " . $txn_data['description'] . "<br>
                                                    <strong>Original Date:</strong> " . date('F j, Y g:i A', strtotime($txn_data['transaction_date'])) . "<br>
                                                    <strong>Deleted By:</strong> " . $admin_name . " (ID: " . $admin_id . ")<br>
                                                    <strong>Deletion Time:</strong> " . date('F j, Y g:i A') . "
                                                </div>
                                            </div>

                                            <!-- Warning -->
                                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                                <h4 style='color: #721c24;'>⚠️ Permanent Deletion</h4>
                                                <p style='color: #721c24;'>
                                                    This transaction has been permanently removed from the system.<br>
                                                    The user's bot profit balance has been adjusted accordingly.
                                                </p>
                                            </div>

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

                    // Send admin notification
                    require_once("../proccess/admin_mailer.php");
                    
                    $success = "Transaction deleted successfully!";
                } else {
                    $error = "Failed to delete transaction.";
                }
                break;
        }
    }
}

// Rest of your existing code continues here...
// Get filter parameters, build queries, etc.

?>

<!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-exchange-alt me-2"></i>Bot Transactions</h4>
										<div class="box-controls pull-right">
											<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addTransactionModal">
												<i class="fas fa-plus me-1"></i> Add Transaction
											</button>
										</div>
									</div>
									<div class="box-body">
										<!-- Stats Cards -->
										<div class="row mb-20">
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-primary pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500"><?php echo number_format($total_transactions); ?></h1>
														<p class="text-white mb-0">Total Transactions</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-success pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_profit'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Profit</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-danger pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_loss'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Loss</p>
													</div>
												</div>
											</div>
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-warning pull-up">
													<div class="box-body text-center">
														<h1 class="text-white fw-500">$<?php echo number_format($stats['total_fees'] ?: 0, 2); ?></h1>
														<p class="text-white mb-0">Total Fees</p>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Profit by Plan -->
										<div class="row mb-20">
											<div class="col-12">
												<div class="box">
													<div class="box-header">
														<h5 class="box-title"><i class="fas fa-chart-pie me-2"></i>Profit by Bot Plan</h5>
													</div>
													<div class="box-body">
														<div class="table-responsive">
															<table class="table table-hover">
																<thead>
																	<tr>
																		<th>Bot Plan</th>
																		<th>Transactions</th>
																		<th>Total Profit</th>
																		<th>Total Loss</th>
																		<th>Net Profit</th>
																		<th>Profit/Loss Ratio</th>
																	</tr>
																</thead>
																<tbody>
																	<?php if (mysqli_num_rows($plan_stats_result) > 0): ?>
																		<?php while ($plan = mysqli_fetch_assoc($plan_stats_result)): ?>
																			<?php
																			$net_profit = $plan['total_profit'] - $plan['total_loss'];
																			$profit_ratio = $plan['total_loss'] > 0 ? ($plan['total_profit'] / $plan['total_loss']) : 0;
																			$ratio_class = $profit_ratio >= 1 ? 'text-success' : 'text-danger';
																			?>
																			<tr>
																				<td><?php echo htmlspecialchars($plan['plan_name']); ?></td>
																				<td><?php echo $plan['transaction_count']; ?></td>
																				<td class="text-success">$<?php echo number_format($plan['total_profit'], 2); ?></td>
																				<td class="text-danger">$<?php echo number_format($plan['total_loss'], 2); ?></td>
																				<td class="fw-500 <?php echo $net_profit >= 0 ? 'text-success' : 'text-danger'; ?>">
																					$<?php echo number_format($net_profit, 2); ?>
																				</td>
																				<td class="<?php echo $ratio_class; ?>">
																					<?php echo number_format($profit_ratio, 2); ?>:1
																				</td>
																			</tr>
																		<?php endwhile; ?>
																	<?php else: ?>
																		<tr>
																			<td colspan="6" class="text-center py-10">No transaction data available</td>
																		</tr>
																	<?php endif; ?>
																</tbody>
															</table>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-12">
												<form method="GET" class="row g-3">
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Transaction Type</label>
															<select class="form-control" name="type">
																<option value="">All Types</option>
																<option value="profit" <?php echo $filter_type == 'profit' ? 'selected' : ''; ?>>Profit</option>
																<option value="loss" <?php echo $filter_type == 'loss' ? 'selected' : ''; ?>>Loss</option>
																<option value="fee" <?php echo $filter_type == 'fee' ? 'selected' : ''; ?>>Fee</option>
															</select>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $filter_date_from; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $filter_date_to; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Subscription</label>
															<select class="form-control" name="subscription_id">
																<option value="0">All Subscriptions</option>
																<?php while ($sub = mysqli_fetch_assoc($subscriptions_result)): ?>
																	<option value="<?php echo $sub['id']; ?>" <?php echo $filter_subscription == $sub['id'] ? 'selected' : ''; ?>>
																		#<?php echo $sub['id']; ?> - <?php echo htmlspecialchars($sub['username']); ?> (<?php echo htmlspecialchars($sub['plan_name']); ?>)
																	</option>
																<?php endwhile; ?>
																<?php mysqli_data_seek($subscriptions_result, 0); // Reset pointer ?>
															</select>
														</div>
													</div>
													<div class="col-md-6">
														<div class="form-group">
															<label class="form-label">Search</label>
															<input type="text" class="form-control" name="search" placeholder="Search by user, email, or description..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">&nbsp;</label>
															<div>
																<button type="submit" class="btn btn-primary"><i class="fas fa-filter me-1"></i> Apply Filters</button>
																<?php if ($filter_type || $filter_date_from || $filter_date_to || $filter_subscription || $search): ?>
																	<a href="bot_transactions.php" class="btn btn-secondary">Clear</a>
																<?php endif; ?>
															</div>
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">&nbsp;</label>
															<div class="dropdown">
																<button class="btn btn-light w-100 dropdown-toggle" type="button" data-bs-toggle="dropdown">
																	<i class="fas fa-download me-1"></i> Export
																</button>
																<div class="dropdown-menu">
																	<a class="dropdown-item" href="export_bot_transactions.php?format=csv&type=<?php echo $filter_type; ?>&date_from=<?php echo $filter_date_from; ?>&date_to=<?php echo $filter_date_to; ?>&subscription_id=<?php echo $filter_subscription; ?>&search=<?php echo urlencode($search); ?>">
																		<i class="fas fa-file-csv"></i> CSV
																	</a>
																	<a class="dropdown-item" href="export_bot_transactions.php?format=excel&type=<?php echo $filter_type; ?>&date_from=<?php echo $filter_date_from; ?>&date_to=<?php echo $filter_date_to; ?>&subscription_id=<?php echo $filter_subscription; ?>&search=<?php echo urlencode($search); ?>">
																		<i class="fas fa-file-excel"></i> Excel
																	</a>
																	<a class="dropdown-item" href="export_bot_transactions.php?format=pdf&type=<?php echo $filter_type; ?>&date_from=<?php echo $filter_date_from; ?>&date_to=<?php echo $filter_date_to; ?>&subscription_id=<?php echo $filter_subscription; ?>&search=<?php echo urlencode($search); ?>">
																		<i class="fas fa-file-pdf"></i> PDF
																	</a>
																</div>
															</div>
														</div>
													</div>
												</form>
											</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; ?>
										
										<!-- Transactions Table -->
										<div class="table-responsive">
											<table class="table table-hover table-bordered" id="transactionsTable">
												<thead class="bg-light">
													<tr>
														<th>ID</th>
														<th>User</th>
														<th>Subscription</th>
														<th>Type</th>
														<th>Amount</th>
														<th>Date</th>
														<th>Description</th>
														<th>Created</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($transaction = mysqli_fetch_assoc($result)): ?>
															<?php
															// Type colors and icons
															$type_colors = array(
																'profit' => 'success',
																'loss' => 'danger',
																'fee' => 'warning'
															);
															$type_icons = array(
																'profit' => 'fas fa-arrow-up',
																'loss' => 'fas fa-arrow-down',
																'fee' => 'fas fa-file-invoice'
															);
															$type_color = $type_colors[$transaction['transaction_type']] ?: 'secondary';
															$type_icon = $type_icons[$transaction['transaction_type']] ?: 'fas fa-exchange-alt';
															
															// Format dates
															$transaction_date = date('M d, Y', strtotime($transaction['transaction_date']));
															$created_date = date('M d, H:i', strtotime($transaction['created_at']));
															?>
															<tr>
																<td><?php echo $transaction['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($transaction['username']); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($transaction['email']); ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<p class="mb-0 fw-500">#<?php echo $transaction['subscription_id']; ?></p>
																	<small class="text-mute"><?php echo htmlspecialchars($transaction['plan_name']); ?></small>
																	<br>
																	<small class="text-mute">Balance: $<?php echo number_format($transaction['trading_balance'], 2); ?></small>
																</td>
																<td>
																	<span class="badge bg-<?php echo $type_color; ?>">
																		<i class="<?php echo $type_icon; ?> me-1"></i>
																		<?php echo ucfirst($transaction['transaction_type']); ?>
																	</span>
																</td>
																<td class="fw-500 <?php echo $transaction['transaction_type'] == 'profit' ? 'text-success' : 'text-danger'; ?>">
																	$<?php echo number_format($transaction['amount'], 2); ?>
																</td>
																<td><?php echo $transaction_date; ?></td>
																<td>
																	<small><?php echo htmlspecialchars($transaction['description']); ?></small>
																</td>
																<td>
																	<small class="text-mute"><?php echo $created_date; ?></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="#" data-bs-toggle="modal" data-bs-target="#viewTransactionModal" 
																			   data-transaction-id="<?php echo $transaction['id']; ?>">
																				<i class="fas fa-eye me-2"></i> View Details
																			</a>
																			<a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#editTransactionModal" 
																			   data-transaction-id="<?php echo $transaction['id']; ?>"
																			   data-amount="<?php echo $transaction['amount']; ?>"
																			   data-description="<?php echo htmlspecialchars($transaction['description']); ?>">
																				<i class="fas fa-edit me-2"></i> Edit
																			</a>
																			<div class="dropdown-divider"></div>
																			<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $transaction['id']; ?>)">
																				<i class="fas fa-trash me-2"></i> Delete
																			</a>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="9" class="text-center py-20">
																<i class="fas fa-exchange-alt fa-2x text-mute mb-3"></i>
																<h5>No transactions found</h5>
																<p class="text-mute">Try adjusting your filters or add a new transaction</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Summary -->
										<div class="row mt-20">
											<div class="col-12">
												<div class="box bg-light">
													<div class="box-body">
														<div class="row">
															<div class="col-md-3 text-center">
																<h3 class="fw-500 text-success">$<?php echo number_format($stats['total_profit'] ?: 0, 2); ?></h3>
																<p class="text-mute mb-0">Total Profit</p>
															</div>
															<div class="col-md-3 text-center">
																<h3 class="fw-500 text-danger">$<?php echo number_format($stats['total_loss'] ?: 0, 2); ?></h3>
																<p class="text-mute mb-0">Total Loss</p>
															</div>
															<div class="col-md-3 text-center">
																<h3 class="fw-500 text-warning">$<?php echo number_format($stats['total_fees'] ?: 0, 2); ?></h3>
																<p class="text-mute mb-0">Total Fees</p>
															</div>
															<div class="col-md-3 text-center">
																<?php
																$net_profit = ($stats['total_profit'] ?: 0) - ($stats['total_loss'] ?: 0);
																$net_class = $net_profit >= 0 ? 'text-success' : 'text-danger';
																?>
																<h3 class="fw-500 <?php echo $net_class; ?>">$<?php echo number_format($net_profit, 2); ?></h3>
																<p class="text-mute mb-0">Net Profit/Loss</p>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</div>
					</section>
					<!-- /.content -->
				</div>
			</div>
		  	
		  <?php include('includes/footer.php') ?>

		  <?php include('includes/control_sidebar.php') ?>
			
		</div>
		<!-- ./wrapper -->
		
		<!-- Modal for Adding Transaction -->
		<div class="modal fade" id="addTransactionModal" tabindex="-1" aria-labelledby="addTransactionModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST">
						<div class="modal-header">
							<h5 class="modal-title" id="addTransactionModalLabel">Add Bot Transaction</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<input type="hidden" name="action_type" value="add_transaction">
							
							<div class="mb-3">
								<label class="form-label">Subscription <span class="text-danger">*</span></label>
								<select class="form-control" name="subscription_id" required>
									<option value="">Select Subscription</option>
									<?php while ($sub = mysqli_fetch_assoc($subscriptions_result)): ?>
										<option value="<?php echo $sub['id']; ?>">
											#<?php echo $sub['id']; ?> - <?php echo htmlspecialchars($sub['username']); ?> (<?php echo htmlspecialchars($sub['plan_name']); ?>)
										</option>
									<?php endwhile; ?>
									<?php mysqli_data_seek($subscriptions_result, 0); // Reset pointer ?>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Transaction Date <span class="text-danger">*</span></label>
								<input type="date" class="form-control" name="transaction_date" value="<?php echo date('Y-m-d'); ?>" required>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Transaction Type <span class="text-danger">*</span></label>
								<select class="form-control" name="transaction_type" required>
									<option value="profit">Profit</option>
									<option value="loss">Loss</option>
									<option value="fee">Fee</option>
								</select>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Amount ($) <span class="text-danger">*</span></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">Description</label>
								<textarea class="form-control" name="description" rows="3" placeholder="Enter transaction description..."></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 Transaction</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Modal for Viewing Transaction Details -->
		<div class="modal fade" id="viewTransactionModal" tabindex="-1" aria-labelledby="viewTransactionModalLabel" aria-hidden="true">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header">
						<h5 class="modal-title" id="viewTransactionModalLabel">Transaction Details</h5>
						<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
					</div>
					<div class="modal-body" id="transactionDetailsContent">
						<!-- Content will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Editing Transaction -->
		<div class="modal fade" id="editTransactionModal" tabindex="-1" aria-labelledby="editTransactionModalLabel" aria-hidden="true">
			<div class="modal-dialog">
				<div class="modal-content">
					<form method="POST" id="editTransactionForm">
						<input type="hidden" name="action_type" value="update_transaction">
						<input type="hidden" name="transaction_id" id="editTransactionId">
						
						<div class="modal-header">
							<h5 class="modal-title" id="editTransactionModalLabel">Edit Transaction</h5>
							<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
						</div>
						<div class="modal-body">
							<div class="mb-3">
								<label class="form-label">Amount ($) <span class="text-danger">*</span></label>
								<input type="number" class="form-control" name="amount" id="editAmount" step="0.01" min="0.01" required>
							</div>
							
							<div class="mb-3">
								<label class="form-label">Description</label>
								<textarea class="form-control" name="description" id="editDescription" rows="3"></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 Transaction</button>
						</div>
					</form>
				</div>
			</div>
		</div>
		
		<!-- Hidden form for delete -->
		<form method="POST" id="deleteForm" style="display: none;">
			<input type="hidden" name="action_type" value="delete_transaction">
			<input type="hidden" name="transaction_id" id="deleteTransactionId">
			<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
			$('#transactionsTable').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"
					}
				}
			});
			
			// View Transaction Modal
			$('#viewTransactionModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var transactionId = button.data('transaction-id');
				
				// Load transaction details via AJAX
				$.ajax({
					url: 'ajax/get_bot_transaction_details.php',
					type: 'GET',
					data: { id: transactionId },
					success: function(data) {
						$('#transactionDetailsContent').html(data);
					}
				});
			});
			
			// Edit Transaction Modal
			$('#editTransactionModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var transactionId = button.data('transaction-id');
				var amount = button.data('amount');
				var description = button.data('description');
				
				$('#editTransactionId').val(transactionId);
				$('#editAmount').val(amount);
				$('#editDescription').val(description);
				$('#editTransactionModalLabel').text('Edit Transaction #' + transactionId);
			});
			
			// Auto-refresh stats every 30 seconds
			setInterval(function() {
				refreshTransactionStats();
			}, 30000);
		});
		
		// Refresh transaction stats
		function refreshTransactionStats() {
			$.ajax({
				url: 'ajax/get_bot_transaction_stats.php',
				type: 'GET',
				data: {
					type: '<?php echo $filter_type; ?>',
					date_from: '<?php echo $filter_date_from; ?>',
					date_to: '<?php echo $filter_date_to; ?>',
					subscription_id: <?php echo $filter_subscription; ?>
				},
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update stat cards
						$('.bg-gradient-primary .fw-500').text(stats.total_count);
						$('.bg-gradient-success .fw-500').text('$' + stats.total_profit);
						$('.bg-gradient-danger .fw-500').text('$' + stats.total_loss);
						$('.bg-gradient-warning .fw-500').text('$' + stats.total_fees);
						
						// Update summary
						$('.text-success.fw-500:eq(1)').text('$' + stats.total_profit);
						$('.text-danger.fw-500').text('$' + stats.total_loss);
						$('.text-warning.fw-500').text('$' + stats.total_fees);
						
						var netProfit = parseFloat(stats.total_profit) - parseFloat(stats.total_loss);
						var netClass = netProfit >= 0 ? 'text-success' : 'text-danger';
						$('.fw-500:last').removeClass('text-success text-danger').addClass(netClass).text('$' + netProfit.toFixed(2));
						
						// Show notification
						Swal.fire({
							toast: true,
							position: 'top-end',
							icon: 'success',
							title: 'Stats Updated',
							showConfirmButton: false,
							timer: 1500
						});
					}
				}
			});
		}
		
		// Confirm Delete with PIN
		function confirmDelete(transactionId) {
			Swal.fire({
				title: 'Delete Transaction?',
				html: `
					<p>This action cannot be undone. The transaction will be permanently deleted.</p>
					<div class="mt-3">
						<label class="form-label">Enter Admin PIN to confirm:</label>
						<input type="password" id="swalPin" class="form-control" placeholder="4-digit PIN" autocomplete="off">
					</div>
				`,
				icon: 'warning',
				showCancelButton: true,
				confirmButtonColor: '#d33',
				cancelButtonColor: '#3085d6',
				confirmButtonText: 'Delete Transaction',
				cancelButtonText: 'Cancel',
				preConfirm: () => {
					const pin = document.getElementById('swalPin').value;
					if (!pin) {
						Swal.showValidationMessage('Please enter your PIN');
					} else if (pin.length !== 4) {
						Swal.showValidationMessage('PIN must be 4 digits');
					}
					return { pin: pin };
				}
			}).then((result) => {
				if (result.isConfirmed) {
					// Submit the delete form
					document.getElementById('deleteTransactionId').value = transactionId;
					document.getElementById('deletePin').value = result.value.pin;
					document.getElementById('deleteForm').submit();
				}
			});
		}
		</script>
		
		<style>
		.table-hover tbody tr:hover {
			background-color: rgba(0,0,0,0.02);
		}
		.badge {
			padding: 5px 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>