<?php
$page_title = "Transactions Management";
require_once 'header.php';

$db = Database::getInstance()->connect();

// Pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$limit = 25;
$offset = ($page - 1) * $limit;

// Filters
$type = $_GET['type'] ?? '';
$status = $_GET['status'] ?? '';
$method = $_GET['method'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$user_id = $_GET['user_id'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where = [];
$params = [];
$joins = "LEFT JOIN users u ON t.user_id = u.id";

if ($type) {
    $where[] = "t.type = ?";
    $params[] = $type;
}

if ($status) {
    $where[] = "t.status = ?";
    $params[] = $status;
}

if ($method) {
    $where[] = "t.method = ?";
    $params[] = $method;
}

if ($date_from) {
    $where[] = "DATE(t.created_at) >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $where[] = "DATE(t.created_at) <= ?";
    $params[] = $date_to;
}

if ($user_id) {
    $where[] = "t.user_id = ?";
    $params[] = $user_id;
}

if ($search) {
    $where[] = "(t.reference LIKE ? OR u.username LIKE ? OR u.email LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = $where ? "WHERE " . implode(" AND ", $where) : "";

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

// Get transactions
$sql = "SELECT t.*, u.username, u.email FROM transactions t $joins $where_clause 
        ORDER BY t.created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

// Get stats
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN type = 'deposit' THEN amount ELSE 0 END) as total_deposits,
    SUM(CASE WHEN type = 'withdrawal' THEN amount ELSE 0 END) as total_withdrawals,
    SUM(CASE WHEN type = 'profit' THEN amount ELSE 0 END) as total_profits,
    SUM(CASE WHEN type = 'referral_bonus' THEN amount ELSE 0 END) as total_referrals,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
    FROM transactions $where_clause";

$stats_stmt = $db->prepare($stats_sql);
$stats_stmt->execute($params);
$stats = $stats_stmt->fetch();

// Get distinct methods
$methods_stmt = $db->query("SELECT DISTINCT method FROM transactions WHERE method IS NOT NULL AND method != ''");
$methods = $methods_stmt->fetchAll();
?>

<div class="container-fluid">
    <!-- 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']); ?></h3>
                </div>
                <i class="fas fa-exchange-alt text-blue-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 Deposits</p>
                    <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format((float)($stats['total_deposits'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-money-bill-wave 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 Withdrawals</p>
                    <h3 class="text-2xl font-bold text-red-600">$<?php echo number_format((float)($stats['total_withdrawals'] ?? 0), 2); ?></h3>
                </div>
                <i class="fas fa-wallet 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">Pending Transactions</p>
                    <h3 class="text-2xl font-bold text-yellow-600"><?php echo number_format($stats['pending']); ?></h3>
                </div>
                <i class="fas fa-clock text-yellow-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-2 lg: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 Types</option>
                        <option value="deposit" <?php echo $type == 'deposit' ? 'selected' : ''; ?>>Deposit</option>
                        <option value="withdrawal" <?php echo $type == 'withdrawal' ? 'selected' : ''; ?>>Withdrawal</option>
                        <option value="investment" <?php echo $type == 'investment' ? 'selected' : ''; ?>>Investment</option>
                        <option value="profit" <?php echo $type == 'profit' ? 'selected' : ''; ?>>Profit</option>
                        <option value="referral_bonus" <?php echo $type == 'referral_bonus' ? 'selected' : ''; ?>>Referral Bonus</option>
                        <option value="credit" <?php echo $type == 'credit' ? 'selected' : ''; ?>>Credit</option>
                        <option value="debit" <?php echo $type == 'debit' ? 'selected' : ''; ?>>Debit</option>
                    </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 Status</option>
                        <option value="pending" <?php echo $status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        <option value="completed" <?php echo $status == 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="approved" <?php echo $status == 'approved' ? 'selected' : ''; ?>>Approved</option>
                        <option value="rejected" <?php echo $status == 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                        <option value="cancelled" <?php echo $status == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                    </select>
                </div>
                
                <!-- Method Filter -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Method</label>
                    <select name="method" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        <option value="">All Methods</option>
                        <?php foreach ($methods as $m): ?>
                        <option value="<?php echo $m['method']; ?>" <?php echo $method == $m['method'] ? 'selected' : ''; ?>>
                            <?php echo ucfirst($m['method']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <!-- User ID -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">User ID</label>
                    <input type="number" name="user_id" value="<?php echo htmlspecialchars($user_id); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="User ID">
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- Date Range -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">From Date</label>
                    <input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <div>
                    <label class="block text-gray-700 text-sm mb-2">To Date</label>
                    <input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                </div>
                
                <!-- Search -->
                <div>
                    <label class="block text-gray-700 text-sm mb-2">Search</label>
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"
                           placeholder="Reference, username, or email">
                </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">Reference</th>
                        <th class="p-4 text-left">User</th>
                        <th class="p-4 text-left">Type</th>
                        <th class="p-4 text-left">Amount</th>
                        <th class="p-4 text-left">Method</th>
                        <th class="p-4 text-left">Status</th>
                        <th class="p-4 text-left">Date</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): 
                            $type_colors = [
                                'deposit' => 'bg-green-100 text-green-800',
                                'withdrawal' => 'bg-red-100 text-red-800',
                                'profit' => 'bg-blue-100 text-blue-800',
                                'referral_bonus' => 'bg-yellow-100 text-yellow-800',
                                'credit' => 'bg-green-100 text-green-800',
                                'debit' => 'bg-red-100 text-red-800',
                                'investment' => 'bg-purple-100 text-purple-800'
                            ];
                            $status_colors = [
                                'pending' => 'bg-yellow-100 text-yellow-800',
                                'completed' => 'bg-green-100 text-green-800',
                                'approved' => 'bg-blue-100 text-blue-800',
                                'rejected' => 'bg-red-100 text-red-800',
                                'cancelled' => 'bg-gray-100 text-gray-800'
                            ];
                        ?>
                        <tr class="hover:bg-gray-50">
                            <!-- Reference -->
                            <td class="p-4">
                                <p class="font-mono text-sm"><?php echo $tx['reference']; ?></p>
                                <p class="text-xs text-gray-500">ID: <?php echo $tx['id']; ?></p>
                            </td>
                            
                            <!-- User -->
                            <td class="p-4">
                                <p class="font-medium"><?php echo htmlspecialchars($tx['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($tx['email']); ?></p>
                                <p class="text-xs text-gray-500">ID: <?php echo $tx['user_id']; ?></p>
                            </td>
                            
                            <!-- Type -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $type_colors[$tx['type']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                    <?php echo ucfirst($tx['type']); ?>
                                </span>
                                <?php if ($tx['description']): ?>
                                <p class="text-xs text-gray-500 mt-1 truncate max-w-xs"><?php echo htmlspecialchars($tx['description']); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Amount -->
                            <td class="p-4">
                                <p class="font-bold <?php echo in_array($tx['type'], ['deposit', 'profit', 'referral_bonus', 'credit']) ? 'text-green-600' : 'text-red-600'; ?>">
                                    <?php echo in_array($tx['type'], ['deposit', 'profit', 'referral_bonus', 'credit']) ? '+' : '-'; ?>
                                    $<?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; ?>
                                <?php if ($tx['net_amount'] > 0): ?>
                                <p class="text-xs text-gray-500">Net: $<?php echo number_format($tx['net_amount'], 2); ?></p>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Method -->
                            <td class="p-4">
                                <p class="capitalize"><?php echo $tx['method'] ?: 'N/A'; ?></p>
                            </td>
                            
                            <!-- Status -->
                            <td class="p-4">
                                <span class="px-3 py-1 rounded-full text-xs font-semibold <?php echo $status_colors[$tx['status']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                    <?php echo ucfirst($tx['status']); ?>
                                </span>
                            </td>
                            
                            <!-- 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', strtotime($tx['created_at'])); ?></p>
                            </td>
                            
                            <!-- Actions -->
                            <td class="p-4">
                                <div class="flex flex-col space-y-2">
                                    <a href="transaction-view.php?id=<?php echo $tx['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View
                                    </a>
                                    
                                    <?php if ($tx['status'] == 'pending'): ?>
                                        <?php if ($tx['type'] == 'deposit'): ?>
                                        <a href="deposits.php?action=approve&id=<?php echo $tx['id']; ?>" 
                                           onclick="return confirm('Approve this deposit?')"
                                           class="text-green-600 hover:text-green-800 text-sm font-medium">
                                            <i class="fas fa-check mr-1"></i> Approve
                                        </a>
                                        <a href="deposits.php?action=reject&id=<?php echo $tx['id']; ?>" 
                                           onclick="return confirm('Reject this deposit?')"
                                           class="text-red-600 hover:text-red-800 text-sm font-medium">
                                            <i class="fas fa-times mr-1"></i> Reject
                                        </a>
                                        <?php elseif ($tx['type'] == 'withdrawal'): ?>
                                        <a href="withdrawals.php?action=approve&id=<?php echo $tx['id']; ?>" 
                                           onclick="return confirm('Approve this withdrawal?')"
                                           class="text-green-600 hover:text-green-800 text-sm font-medium">
                                            <i class="fas fa-check mr-1"></i> Approve
                                        </a>
                                        <a href="withdrawals.php?action=reject&id=<?php echo $tx['id']; ?>" 
                                           onclick="return confirm('Reject this withdrawal?')"
                                           class="text-red-600 hover:text-red-800 text-sm font-medium">
                                            <i class="fas fa-times mr-1"></i> Reject
                                        </a>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    
                                    <a href="?action=delete&id=<?php echo $tx['id']; ?>" 
                                       onclick="return confirm('Delete this transaction? This action cannot be undone.')"
                                       class="text-red-600 hover:text-red-800 text-sm font-medium">
                                        <i class="fas fa-trash mr-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" 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 || $status || $search): ?>
                                <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; ?><?php echo http_build_query(array_filter([
                        'type' => $type,
                        'status' => $status,
                        'method' => $method,
                        'date_from' => $date_from,
                        'date_to' => $date_to,
                        'user_id' => $user_id,
                        'search' => $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; ?><?php echo http_build_query(array_filter([
                        'type' => $type,
                        'status' => $status,
                        'method' => $method,
                        'date_from' => $date_from,
                        'date_to' => $date_to,
                        'user_id' => $user_id,
                        'search' => $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; ?><?php echo http_build_query(array_filter([
                        'type' => $type,
                        'status' => $status,
                        'method' => $method,
                        'date_from' => $date_from,
                        'date_to' => $date_to,
                        'user_id' => $user_id,
                        'search' => $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>
    
    <!-- Bulk Actions -->
    <div class="mt-6 bg-white rounded-xl shadow p-6">
        <h4 class="text-lg font-bold mb-4">Bulk Actions</h4>
        <div class="flex flex-wrap gap-4">
            <button onclick="bulkApprove()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                <i class="fas fa-check-double mr-2"></i>Approve Selected
            </button>
            <button onclick="bulkReject()" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700">
                <i class="fas fa-times-circle mr-2"></i>Reject Selected
            </button>
            <button onclick="bulkDelete()" class="bg-gray-800 text-white px-4 py-2 rounded-lg hover:bg-gray-900">
                <i class="fas fa-trash-alt mr-2"></i>Delete Selected
            </button>
            <button onclick="bulkExport()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                <i class="fas fa-file-export mr-2"></i>Export Selected
            </button>
        </div>
    </div>
</div>

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

function bulkApprove() {
    const selected = getSelectedTransactions();
    if (selected.length === 0) {
        showNotification('Please select transactions first', 'error');
        return;
    }
    
    if (confirm(Approve ${selected.length} selected transaction(s)?)) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'bulk_approve',
                ids: selected
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}

function bulkReject() {
    const selected = getSelectedTransactions();
    if (selected.length === 0) {
        showNotification('Please select transactions first', 'error');
        return;
    }
    
    if (confirm(Reject ${selected.length} selected transaction(s)?)) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'bulk_reject',
                ids: selected
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}

function bulkDelete() {
    const selected = getSelectedTransactions();
    if (selected.length === 0) {
        showNotification('Please select transactions first', 'error');
        return;
    }
    
    if (confirm(WARNING: This will permanently delete ${selected.length} transaction(s). This action cannot be undone. Are you sure?)) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'bulk_delete',
                ids: selected
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}

function bulkExport() {
    const selected = getSelectedTransactions();
    if (selected.length === 0) {
        showNotification('Please select transactions first', 'error');
        return;
    }
    
    const params = new URLSearchParams();
    params.append('ids', selected.join(','));
    window.open(../api/export-transactions.php?${params.toString()}, '_blank');
}

function getSelectedTransactions() {
    const selected = [];
    document.querySelectorAll('input[name="transaction_ids[]"]:checked').forEach(checkbox => {
        selected.push(checkbox.value);
    });
    return selected;
}

// Quick status update
function updateTransactionStatus(transactionId, status) {
    if (confirm(Mark this transaction as ${status}?)) {
        $.ajax({
            url: '../api/admin-actions.php',
            method: 'POST',
            data: {
                action: 'update_transaction_status',
                transaction_id: transactionId,
                status: status
            },
            success: function(response) {
                const result = JSON.parse(response);
                showNotification(result.message, result.success ? 'success' : 'error');
                if (result.success) location.reload();
            }
        });
    }
}
</script>

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