<?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'] : '';
$transaction_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Transaction type colors
$type_colors = array(
    'deposit' => 'success',
    'withdrawal' => 'danger',
    'profit' => 'info',
    'loss' => 'warning',
    'fee' => 'secondary',
    'bonus' => 'primary',
    'referral' => 'dark',
    'investment' => 'purple',
    'refund' => 'orange'
);

// Status colors
$status_colors = array(
    'pending' => 'warning',
    'processing' => 'info',
    'completed' => 'success',
    'failed' => 'danger',
    'cancelled' => 'secondary',
    'rejected' => 'dark'
);

// 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;
    
    // Verify PIN
    if ($submitted_pin !== $admin_pin) {
        $error = "Invalid PIN. Action not authorized.";
    } else {
        switch ($action_type) {
            case 'update_status':
                $new_status = isset($_POST['status']) ? $_POST['status'] : '';
                $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
                
                if ($target_id > 0 && in_array($new_status, ['pending', 'processing', 'completed', 'failed', 'cancelled', 'rejected'])) {
                    // Get transaction details before update
                    $txn_sql = "SELECT * FROM transactions WHERE id = $target_id";
                    $txn_result = mysqli_query($conn, $txn_sql);
                    $txn_data = mysqli_fetch_assoc($txn_result);
                    
                    // Update transaction status
                    $sql = "UPDATE transactions SET status = '$new_status', updated_at = NOW() WHERE id = $target_id";
                    
                    if (mysqli_query($conn, $sql)) {
                        // If changing from pending to completed and it's a deposit, update user balance
                        if ($txn_data['type'] == 'deposit' && $txn_data['status'] == 'pending' && $new_status == 'completed') {
                            $user_id = $txn_data['user_id'];
                            $amount = $txn_data['amount'];
                            $update_balance = "UPDATE users SET fund_balance = fund_balance + $amount, available_balance = available_balance + $amount WHERE id = $user_id";
                            mysqli_query($conn, $update_balance);
                            
                            // Log balance update
                            logAdminActivity(
                                'User Balance Updated',
                                "Updated balance for user ID $user_id after deposit approval ($$amount)",
                                'Transactions',
                                $user_id,
                                'users'
                            );
                        }
                        
                        // Log activity
                        logAdminActivity(
                            'Transaction Status Updated',
                            "Changed transaction ID $target_id status from {$txn_data['status']} to $new_status. Reason: $reason",
                            'Transactions',
                            $target_id,
                            'transactions'
                        );
                        
                        $success = "Transaction status updated successfully!";
                    } else {
                        $error = "Failed to update transaction status.";
                    }
                }
                break;
                
            case 'add_transaction':
                $user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
                $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
                $type = isset($_POST['type']) ? $_POST['type'] : 'deposit';
                $status = isset($_POST['status']) ? $_POST['status'] : 'completed';
                $description = isset($_POST['description']) ? mysqli_real_escape_string($conn, $_POST['description']) : '';
                
                if ($user_id > 0 && $amount > 0) {
                    // Get user info
                    $user_sql = "SELECT username FROM users WHERE id = $user_id";
                    $user_result = mysqli_query($conn, $user_sql);
                    $user_data = mysqli_fetch_assoc($user_result);
                    $username = $user_data['username'] ?: 'Unknown';
                    
                    // Insert transaction
                    $sql = "INSERT INTO transactions (user_id, amount, type, status, date, currency, description, created_at, updated_at) 
                           VALUES ($user_id, $amount, '$type', '$status', NOW(), 'USDT', '$description', NOW(), NOW())";
                    
                    if (mysqli_query($conn, $sql)) {
                        $new_txn_id = mysqli_insert_id($conn);
                        
                        // Update user balance if completed deposit or profit
                        if ($status == 'completed' && ($type == 'deposit' || $type == 'profit' || $type == 'bonus')) {
                            $update_balance = "UPDATE users SET fund_balance = fund_balance + $amount, available_balance = available_balance + $amount WHERE id = $user_id";
                            mysqli_query($conn, $update_balance);
                        }
                        
                        // Log activity
                        logAdminActivity(
                            'Manual Transaction Added',
                            "Added $type transaction ($$amount) for user $username",
                            'Transactions',
                            $new_txn_id,
                            'transactions'
                        );
                        
                        $success = "Transaction added successfully!";
                    } else {
                        $error = "Failed to add transaction.";
                    }
                } else {
                    $error = "Invalid user or amount.";
                }
                break;
                
            case 'delete_transaction':
                if ($target_id > 0) {
                    // Get transaction details before deletion
                    $txn_sql = "SELECT * FROM transactions WHERE id = $target_id";
                    $txn_result = mysqli_query($conn, $txn_sql);
                    $txn_data = mysqli_fetch_assoc($txn_result);
                    
                    // Only allow deletion of pending transactions
                    if ($txn_data['status'] == 'pending') {
                        $sql = "DELETE FROM transactions WHERE id = $target_id";
                        
                        if (mysqli_query($conn, $sql)) {
                            // Log activity
                            logAdminActivity(
                                'Transaction Deleted',
                                "Deleted pending transaction ID $target_id ($$txn_data[amount], $txn_data[type])",
                                'Transactions',
                                $target_id,
                                'transactions'
                            );
                            
                            $success = "Transaction deleted successfully!";
                        } else {
                            $error = "Failed to delete transaction.";
                        }
                    } else {
                        $error = "Only pending transactions can be deleted.";
                    }
                }
                break;
        }
    }
}

// Get filter parameters
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$order = isset($_GET['order']) ? $_GET['order'] : 'DESC';

// Build query
$sql = "SELECT t.*, u.username, u.email 
        FROM transactions t 
        LEFT JOIN users u ON t.user_id = u.id 
        WHERE 1=1";
$count_sql = "SELECT COUNT(*) as total FROM transactions t WHERE 1=1";
$stats_sql = "SELECT 
                COUNT(*) as total_count,
                SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) as completed_amount,
                SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount,
                SUM(CASE WHEN type = 'profit' AND status = 'completed' THEN amount ELSE 0 END) as total_profit,
                SUM(CASE WHEN type = 'deposit' AND status = 'completed' THEN amount ELSE 0 END) as total_deposits,
                SUM(CASE WHEN type = 'withdrawal' AND status = 'completed' THEN amount ELSE 0 END) as total_withdrawals
              FROM transactions WHERE 1=1";

// Apply filters
if ($filter_type) {
    $sql .= " AND t.type = '$filter_type'";
    $count_sql .= " AND t.type = '$filter_type'";
    $stats_sql .= " AND type = '$filter_type'";
}

if ($filter_status) {
    $sql .= " AND t.status = '$filter_status'";
    $count_sql .= " AND t.status = '$filter_status'";
    $stats_sql .= " AND status = '$filter_status'";
}

if ($date_from) {
    $sql .= " AND DATE(t.date) >= '$date_from'";
    $count_sql .= " AND DATE(date) >= '$date_from'";
    $stats_sql .= " AND DATE(date) >= '$date_from'";
}

if ($date_to) {
    $sql .= " AND DATE(t.date) <= '$date_to'";
    $count_sql .= " AND DATE(date) <= '$date_to'";
    $stats_sql .= " AND DATE(date) <= '$date_to'";
}

if ($user_id > 0) {
    $sql .= " AND t.user_id = $user_id";
    $count_sql .= " AND user_id = $user_id";
    $stats_sql .= " AND user_id = $user_id";
}

if ($search) {
    $sql .= " AND (u.username LIKE '%$search%' OR u.email LIKE '%$search%' OR t.description LIKE '%$search%' OR t.reference_id LIKE '%$search%')";
    $count_sql .= " AND (user_id IN (SELECT id FROM users WHERE username LIKE '%$search%' OR email LIKE '%$search%') OR description LIKE '%$search%' OR reference_id LIKE '%$search%')";
    $stats_sql .= " AND (user_id IN (SELECT id FROM users WHERE username LIKE '%$search%' OR email LIKE '%$search%') OR description LIKE '%$search%' OR reference_id LIKE '%$search%')";
}

// Get stats
$stats_result = mysqli_query($conn, $stats_sql);
$stats = mysqli_fetch_assoc($stats_result);
$total_count = $stats['total_count'] ?: 0;
$completed_amount = $stats['completed_amount'] ?: 0;
$pending_amount = $stats['pending_amount'] ?: 0;
$total_profit = $stats['total_profit'] ?: 0;
$total_deposits = $stats['total_deposits'] ?: 0;
$total_withdrawals = $stats['total_withdrawals'] ?: 0;

// Get count for pagination
$count_result = mysqli_query($conn, $count_sql);
$count_row = mysqli_fetch_assoc($count_result);
$total_records = $count_row['total'];

// Add sorting
$sql .= " ORDER BY $sort $order";

// 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-exchange-alt me-2"></i>All 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">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Transactions</h5>
																<h2 class="text-white fw-500 mb-0" id="totalTransactions"><?php echo number_format($total_count); ?></h2>
																<p class="text-white-50 mb-0">All time</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-list-alt fa-2x text-white"></i>
															</div>
														</div>
													</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">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Completed Amount</h5>
																<h2 class="text-white fw-500 mb-0" id="completedAmount">$<?php echo number_format($completed_amount, 2); ?></h2>
																<p class="text-white-50 mb-0">All completed</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-check-circle fa-2x text-white"></i>
															</div>
														</div>
													</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">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Pending Amount</h5>
																<h2 class="text-white fw-500 mb-0" id="pendingAmount">$<?php echo number_format($pending_amount, 2); ?></h2>
																<p class="text-white-50 mb-0">Awaiting action</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-clock fa-2x text-white"></i>
															</div>
														</div>
													</div>
												</div>
											</div>
											
											<div class="col-xl-3 col-md-6 col-12">
												<div class="box bg-gradient-info pull-up">
													<div class="box-body">
														<div class="d-flex justify-content-between align-items-center">
															<div>
																<h5 class="text-white mb-0">Total Profit</h5>
																<h2 class="text-white fw-500 mb-0" id="totalProfitAmount">$<?php echo number_format($total_profit, 2); ?></h2>
																<p class="text-white-50 mb-0">From trading</p>
															</div>
															<div class="bg-white-20 rounded-circle p-15">
																<i class="fas fa-chart-line fa-2x text-white"></i>
															</div>
														</div>
													</div>
												</div>
											</div>
										</div>
										
										<!-- Filters -->
										<div class="row mb-20">
											<div class="col-md-12">
												<form method="GET" class="row">
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Type</label>
															<select class="form-control" name="type">
																<option value="">All Types</option>
																<option value="deposit" <?php echo $filter_type == 'deposit' ? 'selected' : ''; ?>>Deposit</option>
																<option value="withdrawal" <?php echo $filter_type == 'withdrawal' ? 'selected' : ''; ?>>Withdrawal</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>
																<option value="bonus" <?php echo $filter_type == 'bonus' ? 'selected' : ''; ?>>Bonus</option>
																<option value="referral" <?php echo $filter_type == 'referral' ? 'selected' : ''; ?>>Referral</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Status</label>
															<select class="form-control" name="status">
																<option value="">All Status</option>
																<option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
																<option value="processing" <?php echo $filter_status == 'processing' ? 'selected' : ''; ?>>Processing</option>
																<option value="completed" <?php echo $filter_status == 'completed' ? 'selected' : ''; ?>>Completed</option>
																<option value="failed" <?php echo $filter_status == 'failed' ? 'selected' : ''; ?>>Failed</option>
																<option value="cancelled" <?php echo $filter_status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
																<option value="rejected" <?php echo $filter_status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
															</select>
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Date From</label>
															<input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
														</div>
													</div>
													<div class="col-md-2">
														<div class="form-group">
															<label class="form-label">Date To</label>
															<input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
														</div>
													</div>
													<div class="col-md-3">
														<div class="form-group">
															<label class="form-label">Search</label>
															<input type="text" class="form-control" name="search" placeholder="Username, email, description..." value="<?php echo htmlspecialchars($search); ?>">
														</div>
													</div>
													<div class="col-md-1 d-flex align-items-end">
														<div class="form-group w-100">
															<button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i></button>
														</div>
													</div>
												</form>
												
												<?php if ($filter_type || $filter_status || $date_from || $date_to || $search): ?>
													<div class="mt-3">
														<a href="all_transactions.php" class="btn btn-sm btn-light">
															<i class="fas fa-times me-1"></i> Clear Filters
														</a>
														<small class="text-mute ms-3">
															Showing <?php echo number_format($total_records); ?> transaction(s)
														</small>
													</div>
												<?php endif; ?>
											</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>Type</th>
														<th>Amount</th>
														<th>Status</th>
														<th>Description</th>
														<th>Date</th>
														<th>Actions</th>
													</tr>
												</thead>
												<tbody>
													<?php if (mysqli_num_rows($result) > 0): ?>
														<?php while ($txn = mysqli_fetch_assoc($result)): ?>
															<?php
															$type_color = isset($type_colors[$txn['type']]) ? $type_colors[$txn['type']] : 'secondary';
															$status_color = isset($status_colors[$txn['status']]) ? $status_colors[$txn['status']] : 'secondary';
															$date = date('M d, Y H:i', strtotime($txn['date']));
															$description = htmlspecialchars($txn['description']);
															?>
															<tr>
																<td><?php echo $txn['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($txn['username'] ?: 'Unknown'); ?></p>
																			<small class="text-mute"><?php echo htmlspecialchars($txn['email'] ?: ''); ?></small>
																		</div>
																	</div>
																</td>
																<td>
																	<span class="badge bg-<?php echo $type_color; ?>">
																		<i class="fas fa-<?php echo getTransactionIcon($txn['type']); ?> me-1"></i>
																		<?php echo ucfirst($txn['type']); ?>
																	</span>
																</td>
																<td>
																	<p class="mb-0 fw-500">$<?php echo number_format($txn['amount'], 2); ?></p>
																	<?php if ($txn['fee'] > 0): ?>
																		<small class="text-mute">Fee: $<?php echo number_format($txn['fee'], 2); ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<span class="badge bg-<?php echo $status_color; ?>"><?php echo ucfirst($txn['status']); ?></span>
																</td>
																<td>
																	<small class="text-truncate d-block" style="max-width: 200px;" title="<?php echo $description; ?>">
																		<?php echo $description ?: 'No description'; ?>
																	</small>
																	<?php if ($txn['reference_id']): ?>
																		<small class="text-mute">Ref: <?php echo htmlspecialchars($txn['reference_id']); ?></small>
																	<?php endif; ?>
																</td>
																<td>
																	<p class="mb-0"><?php echo $date; ?></p>
																	<small class="text-mute"><?php echo time_ago($txn['date']); ?> 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="#" data-bs-toggle="modal" data-bs-target="#viewTransactionModal" data-txn-id="<?php echo $txn['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-txn-id="<?php echo $txn['id']; ?>" data-current-status="<?php echo $txn['status']; ?>">
																				<i class="fas fa-sync-alt me-2"></i> Change Status
																			</a>
																			<?php if ($txn['status'] == 'pending'): ?>
																				<div class="dropdown-divider"></div>
																				<a class="dropdown-item text-danger" href="#" onclick="confirmDelete(<?php echo $txn['id']; ?>)">
																					<i class="fas fa-trash me-2"></i> Delete
																				</a>
																			<?php endif; ?>
																		</div>
																	</div>
																</td>
															</tr>
														<?php endwhile; ?>
													<?php else: ?>
														<tr>
															<td colspan="8" 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 search or filters</p>
															</td>
														</tr>
													<?php endif; ?>
												</tbody>
											</table>
										</div>
										
										<!-- Export Section -->
										<div class="row mt-20">
											<div class="col-md-6">
												<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_transactions.php?format=csv&type=<?php echo $filter_type; ?>&status=<?php echo $filter_status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
															<i class="fas fa-file-csv"></i> CSV
														</a>
														<a class="dropdown-item" href="export_transactions.php?format=excel&type=<?php echo $filter_type; ?>&status=<?php echo $filter_status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
															<i class="fas fa-file-excel"></i> Excel
														</a>
														<a class="dropdown-item" href="export_transactions.php?format=pdf&type=<?php echo $filter_type; ?>&status=<?php echo $filter_status; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
															<i class="fas fa-file-pdf"></i> PDF
														</a>
													</div>
												</div>
											</div>
											<div class="col-md-6 text-end">
												<small class="text-mute">
													Total: <strong><?php echo number_format($total_records); ?></strong> transactions
													<?php if ($total_deposits > 0): ?> | Deposits: <strong>$<?php echo number_format($total_deposits, 2); ?></strong><?php endif; ?>
													<?php if ($total_withdrawals > 0): ?> | Withdrawals: <strong>$<?php echo number_format($total_withdrawals, 2); ?></strong><?php endif; ?>
												</small>
											</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 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">
						<!-- Details will be loaded via JavaScript -->
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
					</div>
				</div>
			</div>
		</div>
		
		<!-- Modal for Changing Transaction 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 Transaction 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="transaction_id" id="statusTransactionId">
							
							<div class="mb-3">
								<label class="form-label">New Status</label>
								<select class="form-control" name="status" required>
									<option value="pending">Pending</option>
									<option value="processing">Processing</option>
									<option value="completed">Completed</option>
									<option value="failed">Failed</option>
									<option value="cancelled">Cancelled</option>
									<option value="rejected">Rejected</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 Adding New 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 Manual 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">User <span class="text-danger">*</span></label>
								<select class="form-control" name="user_id" required id="userSelect">
									<option value="">Select User</option>
									<?php
									$users_sql = "SELECT id, username, email FROM users 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 class="row">
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Type <span class="text-danger">*</span></label>
										<select class="form-control" name="type" required>
											<option value="deposit">Deposit</option>
											<option value="withdrawal">Withdrawal</option>
											<option value="profit">Profit</option>
											<option value="loss">Loss</option>
											<option value="fee">Fee</option>
											<option value="bonus">Bonus</option>
											<option value="referral">Referral</option>
											<option value="refund">Refund</option>
										</select>
									</div>
								</div>
								<div class="col-md-6">
									<div class="mb-3">
										<label class="form-label">Status <span class="text-danger">*</span></label>
										<select class="form-control" name="status" required>
											<option value="pending">Pending</option>
											<option value="completed" selected>Completed</option>
											<option value="failed">Failed</option>
											<option value="cancelled">Cancelled</option>
										</select>
									</div>
								</div>
							</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 (Optional)</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 Deleting Transaction (hidden form) -->
		<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>
		
		<!-- Select2 for better dropdowns -->
		<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
		<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.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"
					}
				}
			});
			
			// Initialize Select2
			$('#userSelect').select2({
				placeholder: "Select User",
				allowClear: true,
				width: '100%'
			});
			
			// Status Modal
			$('#statusModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var txnId = button.data('txn-id');
				var currentStatus = button.data('current-status');
				var modal = $(this);
				
				modal.find('#statusTransactionId').val(txnId);
				modal.find('select[name="status"]').val(currentStatus);
				modal.find('.modal-title').text('Change Status for Transaction #' + txnId);
			});
			
			// View Transaction Modal
			$('#viewTransactionModal').on('show.bs.modal', function (event) {
				var button = $(event.relatedTarget);
				var txnId = button.data('txn-id');
				var modal = $(this);
				
				// Load transaction details
				$.ajax({
					url: 'ajax/get_transaction_details1.php',
					type: 'GET',
					data: { id: txnId },
					success: function(data) {
						modal.find('#transactionDetailsContent').html(data);
						modal.find('.modal-title').text('Transaction Details #' + txnId);
					},
					error: function() {
						modal.find('#transactionDetailsContent').html(
							'<div class="alert alert-danger">Failed to load transaction details.</div>'
						);
					}
				});
			});
		});
		
		// Confirm Delete with PIN
		function confirmDelete(transactionId) {
			Swal.fire({
				title: 'Delete Transaction?',
				html: `
					<p>This action cannot be undone. Only pending transactions can be 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();
				}
			});
		}
		
		// Auto-refresh stats every 30 seconds
		setInterval(function() {
			$.ajax({
				url: 'ajax/get_transaction_stats.php',
				type: 'GET',
				data: {
					type: '<?php echo $filter_type; ?>',
					status: '<?php echo $filter_status; ?>',
					date_from: '<?php echo $date_from; ?>',
					date_to: '<?php echo $date_to; ?>',
					search: '<?php echo $search; ?>'
				},
				success: function(data) {
					var stats = JSON.parse(data);
					if (stats.success) {
						// Update the stat cards
						$('#totalTransactions').text(stats.total_count.toLocaleString());
						$('#completedAmount').text('$' + stats.completed_amount.toLocaleString('en-US', {minimumFractionDigits: 2}));
						$('#pendingAmount').text('$' + stats.pending_amount.toLocaleString('en-US', {minimumFractionDigits: 2}));
						$('#totalProfitAmount').text('$' + stats.total_profit.toLocaleString('en-US', {minimumFractionDigits: 2}));
						
						// 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);
		}
		.bg-purple {
			background-color: #6f42c1 !important;
		}
		.bg-orange {
			background-color: #fd7e14 !important;
		}
		</style>
		
	</body>
</html>

<?php
// Helper function to get icon for transaction type
function getTransactionIcon($type) {
    $icons = array(
        'deposit' => 'download',
        'withdrawal' => 'upload',
        'profit' => 'chart-line',
        'loss' => 'chart-line',
        'fee' => 'file-invoice',
        'bonus' => 'gift',
        'referral' => 'users',
        'investment' => 'coins',
        'refund' => 'undo'
    );
    return isset($icons[$type]) ? $icons[$type] : 'exchange-alt';
}

// 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";
    }
}
?>