<?php
$page_title = "Transactions History";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';


$db = Database::getInstance()->connect();
$user_id = $_SESSION['user_id'];

// Get user balance
$user_stmt = $db->prepare("SELECT balance FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user = $user_stmt->fetch();

// Filter parameters
$type = $_GET['type'] ?? 'all';
$status = $_GET['status'] ?? 'all';
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 15;
$offset = ($page - 1) * $limit;

// Build query
$where = "WHERE user_id = ?";
$params = [$user_id];

if ($type != 'all') {
    $where .= " AND type = ?";
    $params[] = $type;
}

if ($status != 'all') {
    $where .= " AND status = ?";
    $params[] = $status;
}

if (!empty($start_date)) {
    $where .= " AND DATE(created_at) >= ?";
    $params[] = $start_date;
}

if (!empty($end_date)) {
    $where .= " AND DATE(created_at) <= ?";
    $params[] = $end_date;
}

if (!empty($search)) {
    $where .= " AND (reference LIKE ? OR description LIKE ? OR method LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

// Get total count
$count_sql = "SELECT COUNT(*) as total FROM transactions $where";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_transactions = $count_stmt->fetch()['total'];
$total_pages = ceil($total_transactions / $limit);

// Get transaction statistics
$stats_sql = "
    SELECT 
        COUNT(*) as total_count,
        SUM(CASE WHEN type IN ('deposit', 'credit', 'profit', 'referral_bonus', 'bonus') THEN amount ELSE 0 END) as total_income,
        SUM(CASE WHEN type IN ('withdrawal', 'debit', 'investment') THEN amount ELSE 0 END) as total_expense,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_count
    FROM transactions 
    WHERE user_id = ?
";

$stats_stmt = $db->prepare($stats_sql);
$stats_stmt->execute([$user_id]);
$stats = $stats_stmt->fetch();

// Get transactions
$sql = "
    SELECT * FROM transactions 
    $where 
    ORDER BY created_at DESC 
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

// Get transaction types for filter
$types_sql = "SELECT DISTINCT type FROM transactions WHERE user_id = ? ORDER BY type";
$types_stmt = $db->prepare($types_sql);
$types_stmt->execute([$user_id]);
$transaction_types = $types_stmt->fetchAll();
?>


<?php require_once '../includes/header_user.php'; ?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="mb-6">
        <h1 class="text-2xl font-bold">Transactions History</h1>
        <p class="text-gray-600">Track all your financial activities</p>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Transactions</p>
                    <h3 class="text-2xl font-bold"><?php echo number_format($stats['total_count']); ?></h3>
                </div>
                <i class="fas fa-exchange-alt text-purple-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Income</p>
                    <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format($stats['total_income'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-arrow-down text-green-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Total Expense</p>
                    <h3 class="text-2xl font-bold text-red-600">$<?php echo number_format($stats['total_expense'] ?? 0, 2); ?></h3>
                </div>
                <i class="fas fa-arrow-up text-red-500 text-2xl"></i>
            </div>
        </div>
        
        <div class="bg-white rounded-xl shadow p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-gray-600 text-sm">Current Balance</p>
                    <h3 class="text-2xl font-bold text-blue-600">$<?php echo number_format($user['balance'], 2); ?></h3>
                </div>
                <i class="fas fa-wallet text-blue-500 text-2xl"></i>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow p-6 mb-6">
        <form method="GET" action="" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Type Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Transaction Type</label>
                    <select name="type" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="all">All Types</option>
                        <?php foreach ($transaction_types as $tx_type): ?>
                        <option value="<?php echo $tx_type['type']; ?>" <?php echo $type == $tx_type['type'] ? 'selected' : ''; ?>>
                            <?php echo ucfirst(str_replace('_', ' ', $tx_type['type'])); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- Status Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Status</label>
                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="all">All Status</option>
                        <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="cancelled" <?php echo $status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        <option value="rejected" <?php echo $status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                    </select>
                </div>
                
                <!-- Start Date -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">From Date</label>
                    <input type="date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <!-- End Date -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">To Date</label>
                    <input type="date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
            </div>
            
            <!-- Search -->
            <div>
                <label class="block text-gray-700 text-sm mb-2">Search</label>
                <div class="flex">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
                           class="flex-1 px-4 py-2 border border-gray-300 rounded-l-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Search reference, description, or method">
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-r-lg hover:bg-purple-700">
                        <i class="fas fa-search"></i>
                    </button>
                </div>
            </div>
            
            <div class="flex justify-between items-center pt-4">
                <div>
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-filter mr-2"></i>Apply Filters
                    </button>
                    <a href="transactions.php" class="ml-2 text-gray-600 hover:text-gray-800">
                        Clear Filters
                    </a>
                </div>
                
                <div>
                    <button type="button" onclick="exportTransactions()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-download mr-2"></i>Export
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Transactions Table -->
    <div class="bg-white rounded-xl shadow overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="p-4 text-left">Date & Time</th>
                        <th class="p-4 text-left">Transaction</th>
                        <th class="p-4 text-left">Amount</th>
                        <th class="p-4 text-left">Method</th>
                        <th class="p-4 text-left">Reference</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php if (count($transactions) > 0): ?>
                        <?php foreach ($transactions as $tx): 
                            $is_positive = in_array($tx['type'], ['deposit', 'credit', 'profit', 'referral_bonus', 'bonus']);
                            $amount_color = $is_positive ? 'text-green-600' : 'text-red-600';
                            $amount_prefix = $is_positive ? '+' : '-';
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Date -->
                            <td class="p-4">
                                <p><?php echo date('M d, Y', strtotime($tx['created_at'])); ?></p>
                                <p class="text-sm text-gray-500"><?php echo date('H:i:s', strtotime($tx['created_at'])); ?></p>
                            </td>
                            
                            <!-- Transaction Info -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo ucfirst(str_replace('_', ' ', $tx['type'])); ?></p>
                                <p class="text-sm text-gray-500 truncate max-w-xs"><?php echo htmlspecialchars($tx['description']); ?></p>
                            </td>
                            
                            <!-- Amount -->
                            <td class="p-4">
                                <p class="font-bold <?php echo $amount_color; ?>">
                                    <?php echo $amount_prefix; ?>$<?php echo number_format($tx['amount'], 2); ?>
                                </p>
                                <?php if ($tx['fee'] > 0): ?>
                                <p class="text-xs text-gray-500">Fee: $<?php echo number_format($tx['fee'], 2); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Method -->
                            <td class="p-4">
                                <p class="text-sm"><?php echo ucfirst($tx['method'] ?? 'N/A'); ?></p>
                            </td>
                            
                            <!-- Reference -->
                            <td class="p-4">
                                <code class="text-sm bg-gray-100 px-2 py-1 rounded"><?php echo $tx['reference']; ?></code>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php
                                    echo $tx['status'] == 'completed' ? 'bg-green-100 text-green-800' :
                                        ($tx['status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' :
                                        ($tx['status'] == 'cancelled' ? 'bg-gray-100 text-gray-800' :
                                        'bg-red-100 text-red-800'));
                                ?>">
                                    <?php echo ucfirst($tx['status']); ?>
                                </span>
                                <?php if ($tx['admin_note']): ?>
                                <p class="text-xs text-gray-500 mt-1 truncate max-w-xs"><?php echo htmlspecialchars($tx['admin_note']); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <button onclick="viewTransaction(<?php echo $tx['id']; ?>)" 
                                        class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                    <i class="fas fa-eye mr-1"></i> Details
                                </button>
                                <?php if ($tx['type'] == 'withdrawal' && $tx['status'] == 'pending'): ?>
                                <button onclick="cancelWithdrawal(<?php echo $tx['id']; ?>)" 
                                        class="text-red-600 hover:text-red-800 text-sm font-medium ml-2">
                                    <i class="fas fa-times mr-1"></i> Cancel
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="7" class="p-8 text-center text-gray-500">
                                <i class="fas fa-exchange-alt text-4xl mb-4 text-gray-300"></i>
                                <p class="text-lg">No transactions found</p>
                                <?php if ($type != 'all' || $status != 'all' || $search || $start_date || $end_date): ?>
                                <p class="text-sm mt-2">Try changing your search filters</p>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
        <div class="border-t border-gray-100 p-4">
            <div class="flex items-center justify-between">
                <div class="text-sm text-gray-600">
                    Showing <?php echo ($offset + 1); ?> to <?php echo min($offset + $limit, $total_transactions); ?> of <?php echo number_format($total_transactions); ?> transactions
                </div>
                <div class="flex space-x-2">
                    <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>&type=<?php echo $type; ?>&status=<?php echo $status; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search); ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        <i class="fas fa-chevron-left"></i> Previous
                    </a>
                    <?php endif; ?>
                    
                    <?php
                    $start = max(1, $page - 2);
                    $end = min($total_pages, $start + 4);
                    
                    for ($i = $start; $i <= $end; $i++):
                    ?>
                    <a href="?page=<?php echo $i; ?>&type=<?php echo $type; ?>&status=<?php echo $status; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search); ?>"
                       class="px-3 py-2 rounded-lg <?php echo $i == $page ? 'bg-purple-600 text-white' : 'bg-gray-100 hover:bg-gray-200'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php endfor; ?>
                    
                    <?php if ($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>&type=<?php echo $type; ?>&status=<?php echo $status; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&search=<?php echo urlencode($search); ?>"
                       class="px-3 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
                        Next <i class="fas fa-chevron-right"></i>
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- Transaction Insights -->
    <div class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Monthly Summary -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Monthly Summary</h3>
            <div class="h-64">
                <canvas id="monthlyChart"></canvas>
            </div>
        </div>
        
        <!-- Transaction Statistics -->
        <div class="bg-white rounded-xl shadow p-6">
            <h3 class="text-lg font-bold mb-4">Transaction Statistics</h3>
            <div class="space-y-4">
                <div>
                    <div class="flex justify-between mb-1">
                        <span class="text-sm text-gray-600">Completed Transactions</span>
                        <span class="text-sm font-bold"><?php echo number_format($stats['completed_count']); ?></span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-green-600 h-2 rounded-full" 
                             style="width: <?php echo $stats['total_count'] > 0 ? ($stats['completed_count'] / $stats['total_count'] * 100) : 0; ?>%"></div>
                    </div>
                </div>
                
                <div>
                    <div class="flex justify-between mb-1">
                        <span class="text-sm text-gray-600">Pending Transactions</span>
                        <span class="text-sm font-bold"><?php echo number_format($stats['pending_count']); ?></span>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2">
                        <div class="bg-yellow-600 h-2 rounded-full" 
                             style="width: <?php echo $stats['total_count'] > 0 ? ($stats['pending_count'] / $stats['total_count'] * 100) : 0; ?>%"></div>
                    </div>
                </div>
                
                <!-- Type Distribution -->
                <div>
                    <h4 class="font-semibold mb-3">Transaction Types</h4>
                    <?php
                    $type_sql = "
                        SELECT type, COUNT(*) as count 
                        FROM transactions 
                        WHERE user_id = ? 
                        GROUP BY type 
                        ORDER BY count DESC 
                        LIMIT 5
                    ";
                    
                    $type_stmt = $db->prepare($type_sql);
                    $type_stmt->execute([$user_id]);
                    $type_distribution = $type_stmt->fetchAll();
                    ?>
                    
                    <div class="space-y-2">
                        <?php foreach ($type_distribution as $type_item): 
                            $percentage = $stats['total_count'] > 0 ? ($type_item['count'] / $stats['total_count'] * 100) : 0;
                        ?>
                        <div>
                            <div class="flex justify-between text-sm">
                                <span><?php echo ucfirst(str_replace('_', ' ', $type_item['type'])); ?></span>
                                <span><?php echo number_format($percentage, 1); ?>%</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full" style="width: <?php echo $percentage; ?>%"></div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Quick Actions -->
    <div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
        <a href="deposit.php" class="bg-gradient-to-r from-green-500 to-blue-500 text-white p-6 rounded-xl hover:opacity-90 text-center">
            <i class="fas fa-plus-circle text-3xl mb-3"></i>
            <p class="font-bold text-lg">Make Deposit</p>
            <p class="text-sm opacity-90">Add funds to your account</p>
        </a>
        
        <a href="withdrawal.php" class="bg-gradient-to-r from-blue-500 to-purple-500 text-white p-6 rounded-xl hover:opacity-90 text-center">
            <i class="fas fa-hand-holding-usd text-3xl mb-3"></i>
            <p class="font-bold text-lg">Withdraw Funds</p>
            <p class="text-sm opacity-90">Withdraw your earnings</p>
        </a>
        
        <a href="investment.php" class="bg-gradient-to-r from-purple-500 to-pink-500 text-white p-6 rounded-xl hover:opacity-90 text-center">
            <i class="fas fa-chart-line text-3xl mb-3"></i>
            <p class="font-bold text-lg">New Investment</p>
            <p class="text-sm opacity-90">Start growing your wealth</p>
        </a>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Prepare monthly data
<?php
// Get monthly transaction data
$monthly_sql = "
    SELECT 
        DATE_FORMAT(created_at, '%Y-%m') as month,
        SUM(CASE WHEN type IN ('deposit', 'credit', 'profit', 'referral_bonus', 'bonus') THEN amount ELSE 0 END) as income,
        SUM(CASE WHEN type IN ('withdrawal', 'debit', 'investment') THEN amount ELSE 0 END) as expense
    FROM transactions 
    WHERE user_id = ? 
    AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
    GROUP BY DATE_FORMAT(created_at, '%Y-%m')
    ORDER BY month
";

$monthly_stmt = $db->prepare($monthly_sql);
$monthly_stmt->execute([$user_id]);
$monthly_data = $monthly_stmt->fetchAll();

$months = [];
$income_data = [];
$expense_data = [];

foreach ($monthly_data as $data) {
    $months[] = date('M Y', strtotime($data['month'] . '-01'));
    $income_data[] = $data['income'];
    $expense_data[] = $data['expense'];
}

// If no data, show placeholder
if (empty($months)) {
    $months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    $income_data = array_fill(0, 6, 0);
    $expense_data = array_fill(0, 6, 0);
}
?>

const monthlyLabels = <?php echo json_encode($months); ?>;
const monthlyIncome = <?php echo json_encode($income_data); ?>;
const monthlyExpense = <?php echo json_encode($expense_data); ?>;

// Monthly Chart
const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
const monthlyChart = new Chart(monthlyCtx, {
    type: 'line',
    data: {
        labels: monthlyLabels,
        datasets: [
            {
                label: 'Income',
                data: monthlyIncome,
                borderColor: 'rgb(34, 197, 94)',
                backgroundColor: 'rgba(34, 197, 94, 0.1)',
                tension: 0.3,
                fill: true
            },
            {
                label: 'Expense',
                data: monthlyExpense,
                borderColor: 'rgb(239, 68, 68)',
                backgroundColor: 'rgba(239, 68, 68, 0.1)',
                tension: 0.3,
                fill: true
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'top',
            },
            tooltip: {
                mode: 'index',
                intersect: false,
                callbacks: {
                    label: function(context) {
                        return context.dataset.label + ': $' + context.parsed.y.toFixed(2);
                    }
                }
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return '$' + value.toFixed(2);
                    }
                }
            }
        }
    }
});

// Transaction functions
function viewTransaction(id) {
    $.ajax({
        url: '../api/get-transaction.php',
        method: 'GET',
        data: { id: id, user_id: <?php echo $user_id; ?> },
        success: function(response) {
            const tx = JSON.parse(response);
            
            // Create modal content
            const modalContent = `
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div class="bg-white rounded-xl shadow-xl w-full max-w-2xl">
                        <div class="p-6 border-b">
                            <h3 class="text-xl font-bold">Transaction Details</h3>
                        </div>
                        <div class="p-6 space-y-4">
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">Reference</p>
                                    <p class="font-bold">${tx.reference}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">Date & Time</p>
                                    <p class="font-bold">${new Date(tx.created_at).toLocaleString()}</p>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">Type</p>
                                    <p class="font-bold">${tx.type.replace('_', ' ').toUpperCase()}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">Amount</p>
                                    <p class="font-bold ${tx.type.includes('deposit') || tx.type.includes('profit') || tx.type.includes('bonus') ? 'text-green-600' : 'text-red-600'}">
                                        $${parseFloat(tx.amount).toFixed(2)}
                                    </p>
                                </div>
                            </div>
                            
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">Status</p>
                                    <span class="px-2 py-1 rounded-full text-xs font-semibold ${tx.status === 'completed' ? 'bg-green-100 text-green-800' : tx.status === 'pending' ? 'bg-yellow-100 text-yellow-800' : 'bg-red-100 text-red-800'}">
                                        ${tx.status.toUpperCase()}
                                    </span>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">Method</p>
                                    <p class="font-bold">${tx.method || 'N/A'}</p>
                                </div>
                            </div>
                            
                            <div>
                                <p class="text-sm text-gray-600">Description</p>
                                <p class="font-medium">${tx.description || 'No description'}</p>
                            </div>
                            
                            ${tx.fee > 0 ? `
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <p class="text-sm text-gray-600">Fee</p>
                                    <p class="font-bold text-red-600">$${parseFloat(tx.fee).toFixed(2)}</p>
                                </div>
                                <div>
                                    <p class="text-sm text-gray-600">Net Amount</p>
                                    <p class="font-bold">$${parseFloat(tx.net_amount || tx.amount).toFixed(2)}</p>
                                </div>
                            </div>
                            ` : ''}
                            
                            ${tx.admin_note ? `
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <p class="text-sm text-gray-600 mb-1">Admin Note</p>
                                <p class="text-sm">${tx.admin_note}</p>
                            </div>
                            ` : ''}
                            
                            ${tx.details ? `
                            <div>
                                <p class="text-sm text-gray-600 mb-1">Additional Details</p>
                                <pre class="text-sm bg-gray-100 p-3 rounded-lg overflow-x-auto">${JSON.stringify(JSON.parse(tx.details), null, 2)}</pre>
                            </div>
                            ` : ''}
                        </div>
                        <div class="p-6 border-t">
                            <button onclick="closeModal()" class="w-full bg-gray-600 text-white py-2 rounded-lg hover:bg-gray-700">
                                Close
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalContent);
        },
        error: function() {
            alert('Error loading transaction details');
        }
    });
}

function closeModal() {
    const modal = document.querySelector('.fixed.inset-0');
    if (modal) modal.remove();
}

function cancelWithdrawal(id) {
    if (confirm('Cancel this withdrawal request?')) {
        $.ajax({
            url: '../api/cancel-withdrawal.php',
            method: 'POST',
            data: { transaction_id: id },
            success: function(response) {
                const result = JSON.parse(response);
                alert(result.message);
                if (result.success) {
                    location.reload();
                }
            }
        });
    }
}

function exportTransactions() {
    const params = new URLSearchParams(window.location.search);
    window.open(../api/export-transactions.php?${params.toString()}, '_blank');
}

// Auto-refresh for pending transactions
const pendingCount = <?php echo $stats['pending_count']; ?>;
if (pendingCount > 0) {
    // Refresh every 30 seconds if there are pending transactions
    setTimeout(() => {
        location.reload();
    }, 30000);
}

// Search functionality
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey && e.key === 'f') {
        e.preventDefault();
        document.querySelector('input[name="search"]').focus();
    }
});
</script>

<?php require_once '../includes/footer.php'; ?>