<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// Handle deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $connection_id = intval($_GET['delete']);
    
    $delete_stmt = $conn->prepare("DELETE FROM wallet_connections WHERE id = ?");
    $delete_stmt->bind_param("i", $connection_id);
    
    if ($delete_stmt->execute()) {
        $message = "Wallet connection #{$connection_id} has been deleted successfully.";
        $message_type = "success";
    } else {
        $message = "Error deleting wallet connection: " . $conn->error;
        $message_type = "error";
    }
    $delete_stmt->close();
}

// Handle bulk delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_delete'])) {
    if (isset($_POST['selected_ids']) && is_array($_POST['selected_ids'])) {
        $selected_ids = array_map('intval', $_POST['selected_ids']);
        $ids_string = implode(',', $selected_ids);
        
        $delete_stmt = $conn->prepare("DELETE FROM wallet_connections WHERE id IN ($ids_string)");
        
        if ($delete_stmt->execute()) {
            $message = count($selected_ids) . " wallet connection(s) have been deleted successfully.";
            $message_type = "success";
        } else {
            $message = "Error deleting wallet connections: " . $conn->error;
            $message_type = "error";
        }
        $delete_stmt->close();
    } else {
        $message = "No items selected for deletion.";
        $message_type = "error";
    }
}

// Get filter parameters
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Build query based on filters
$query = "
    SELECT 
        wc.*,
        u.username,
        u.full_name,
        u.email
    FROM wallet_connections wc
    JOIN users u ON wc.user_id = u.id
    WHERE 1=1
";

$params = [];
$types = "";

if (!empty($date_from)) {
    $query .= " AND DATE(wc.created_at) >= ?";
    $params[] = $date_from;
    $types .= "s";
}

if (!empty($date_to)) {
    $query .= " AND DATE(wc.created_at) <= ?";
    $params[] = $date_to;
    $types .= "s";
}

$query .= " ORDER BY wc.created_at DESC";

$connections_stmt = $conn->prepare($query);
if (!empty($params)) {
    $connections_stmt->bind_param($types, ...$params);
}
$connections_stmt->execute();
$connections_result = $connections_stmt->get_result();
$connections_stmt->close();

// Get statistics
$stats = [];

// Total connections
$stats_query = "SELECT COUNT(*) as total FROM wallet_connections";
$stats_result = $conn->query($stats_query);
$stats['total'] = $stats_result->fetch_assoc()['total'];

// Today's connections
$stats_query = "SELECT COUNT(*) as today FROM wallet_connections WHERE DATE(created_at) = CURDATE()";
$stats_result = $conn->query($stats_query);
$stats['today'] = $stats_result->fetch_assoc()['today'];

// This week's connections
$stats_query = "SELECT COUNT(*) as week FROM wallet_connections WHERE YEARWEEK(created_at) = YEARWEEK(CURDATE())";
$stats_result = $conn->query($stats_query);
$stats['week'] = $stats_result->fetch_assoc()['week'];

// This month's connections
$stats_query = "SELECT COUNT(*) as month FROM wallet_connections WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())";
$stats_result = $conn->query($stats_query);
$stats['month'] = $stats_result->fetch_assoc()['month'];

// Unique users
$stats_query = "SELECT COUNT(DISTINCT user_id) as unique_users FROM wallet_connections";
$stats_result = $conn->query($stats_query);
$stats['unique_users'] = $stats_result->fetch_assoc()['unique_users'];

// Most used wallet
$stats_query = "SELECT wallet_type, COUNT(*) as count FROM wallet_connections GROUP BY wallet_type ORDER BY count DESC LIMIT 1";
$stats_result = $conn->query($stats_query);
$most_used = $stats_result->fetch_assoc();
$stats['most_used_wallet'] = $most_used ? $most_used['wallet_type'] : 'N/A';
$stats['most_used_count'] = $most_used ? $most_used['count'] : 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wallet Connections - Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: #f3f4f6;
        }
        
        .stat-card {
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .action-btn {
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
        }
        
        /* Modal styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal.active {
            display: flex;
        }
        
        .modal-content {
            background: white;
            border-radius: 1rem;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease-out;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        /* Mobile responsive */
        @media (max-width: 768px) {
            .table-container {
                overflow-x: auto;
            }
            
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
        
        .recovery-phrase {
            font-family: monospace;
            background: #f3f4f6;
            padding: 0.5rem;
            border-radius: 0.5rem;
            font-size: 0.875rem;
            word-break: break-all;
        }
        
        .info-badge {
            background: #e5e7eb;
            color: #4b5563;
            padding: 0.25rem 0.5rem;
            border-radius: 0.375rem;
            font-size: 0.75rem;
            display: inline-block;
        }
    </style>
</head>
<body class="bg-gray-50">

<?php include("nav.php"); ?>

<div class="lg:ml-64 p-6">
    <!-- Header -->
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800">Wallet Connections</h1>
        <p class="text-gray-600 mt-1">View and manage all wallet connection requests</p>
    </div>

    <!-- Alert Messages -->
    <?php if (isset($message)): ?>
    <div class="mb-6 p-4 rounded-lg <?php echo $message_type === 'success' ? 'bg-green-100 text-green-700 border-green-400' : 'bg-red-100 text-red-700 border-red-400'; ?> border">
        <div class="flex items-center justify-between">
            <div class="flex items-center gap-3">
                <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <span><?php echo htmlspecialchars($message); ?></span>
            </div>
            <button onclick="this.parentElement.parentElement.remove()" class="text-gray-500 hover:text-gray-700">
                <i class="fas fa-times"></i>
            </button>
        </div>
    </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Total</p>
                    <p class="text-2xl font-bold text-gray-800"><?php echo $stats['total']; ?></p>
                </div>
                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-wallet text-blue-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Today</p>
                    <p class="text-2xl font-bold text-green-600"><?php echo $stats['today']; ?></p>
                </div>
                <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-calendar-day text-green-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">This Week</p>
                    <p class="text-2xl font-bold text-purple-600"><?php echo $stats['week']; ?></p>
                </div>
                <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-calendar-week text-purple-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">This Month</p>
                    <p class="text-2xl font-bold text-yellow-600"><?php echo $stats['month']; ?></p>
                </div>
                <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-calendar-alt text-yellow-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Unique Users</p>
                    <p class="text-2xl font-bold text-indigo-600"><?php echo $stats['unique_users']; ?></p>
                </div>
                <div class="w-10 h-10 bg-indigo-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-users text-indigo-600"></i>
                </div>
            </div>
        </div>
        
        <div class="stat-card bg-white rounded-xl shadow-sm border border-gray-200 p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm text-gray-500">Top Wallet</p>
                    <p class="text-lg font-bold text-pink-600 truncate max-w-[100px]"><?php echo htmlspecialchars($stats['most_used_wallet']); ?></p>
                    <p class="text-xs text-gray-500"><?php echo $stats['most_used_count']; ?> connections</p>
                </div>
                <div class="w-10 h-10 bg-pink-100 rounded-lg flex items-center justify-center">
                    <i class="fas fa-star text-pink-600"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <form method="GET" action="" class="flex flex-wrap gap-4 items-end">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Date From</label>
                <input type="date" name="date_from" value="<?php echo $date_from; ?>" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500">
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Date To</label>
                <input type="date" name="date_to" value="<?php echo $date_to; ?>" class="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary-500">
            </div>
            
            <div>
                <button type="submit" class="bg-primary-600 text-white px-4 py-2 rounded-lg hover:bg-primary-700 transition">
                    <i class="fas fa-filter mr-2"></i>
                    Apply Filters
                </button>
            </div>
            
            <div>
                <a href="wallet-connections.php" class="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 transition">
                    <i class="fas fa-redo mr-2"></i>
                    Reset
                </a>
            </div>
            
            <div class="ml-auto">
                <button type="button" onclick="exportConnections()" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition">
                    <i class="fas fa-download mr-2"></i>
                    Export CSV
                </button>
            </div>
        </form>
    </div>

    <!-- Bulk Actions -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <form method="POST" action="" id="bulkActionForm" class="flex items-center gap-4">
            <div class="flex items-center gap-2">
                <input type="checkbox" id="selectAll" onclick="toggleSelectAll()" class="rounded border-gray-300 text-primary-600 focus:ring-primary-500">
                <label for="selectAll" class="text-sm text-gray-700">Select All</label>
            </div>
            
            <button type="submit" name="bulk_delete" onclick="return confirmBulkDelete()" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700 transition text-sm">
                <i class="fas fa-trash mr-2"></i>
                Delete Selected
            </button>
            
            <span class="text-sm text-gray-500" id="selectedCount">0 selected</span>
        </form>
    </div>

    <!-- Connections Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                            <input type="checkbox" disabled class="rounded border-gray-300">
                        </th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Wallet</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Recovery Phrase</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP Address</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php if ($connections_result && $connections_result->num_rows > 0): ?>
                        <?php while ($connection = $connections_result->fetch_assoc()): 
                            // Truncate recovery phrase for display
                            $words = explode(' ', trim($connection['recovery_phrase']));
                            if (count($words) > 8) {
                                $display_phrase = implode(' ', array_slice($words, 0, 4)) . '...' . implode(' ', array_slice($words, -4));
                            } else {
                                $display_phrase = $connection['recovery_phrase'];
                            }
                        ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="px-6 py-4">
                                <input type="checkbox" name="selected_ids[]" value="<?php echo $connection['id']; ?>" class="row-checkbox rounded border-gray-300 text-primary-600 focus:ring-primary-500" onchange="updateSelectedCount()">
                            </td>
                            <td class="px-6 py-4 text-sm font-medium text-gray-900">#<?php echo $connection['id']; ?></td>
                            <td class="px-6 py-4">
                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($connection['full_name'] ?: $connection['username']); ?></div>
                                <div class="text-xs text-gray-500"><?php echo htmlspecialchars($connection['email']); ?></div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($connection['wallet_type']); ?></div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="recovery-phrase text-xs" title="<?php echo htmlspecialchars($connection['recovery_phrase']); ?>">
                                    <?php echo htmlspecialchars($display_phrase); ?>
                                </div>
                                <button onclick="copyToClipboard('<?php echo htmlspecialchars(addslashes($connection['recovery_phrase'])); ?>')" class="text-xs text-primary-600 hover:text-primary-800 mt-1">
                                </button>
                            </td>
                            <td class="px-6 py-4">
                                <span class="info-badge"><?php echo htmlspecialchars($connection['ip_address'] ?: 'N/A'); ?></span>
                            </td>
                            <td class="px-6 py-4 text-sm text-gray-500">
                                <?php echo date('M d, Y', strtotime($connection['created_at'])); ?>
                                <div class="text-xs text-gray-400"><?php echo date('H:i', strtotime($connection['created_at'])); ?></div>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex space-x-2">
                                    <button onclick="viewDetails(<?php echo htmlspecialchars(json_encode($connection)); ?>)" 
                                            class="action-btn text-blue-600 hover:text-blue-800 bg-blue-100 px-3 py-1 rounded-lg text-sm font-medium">
                                        <i class="fas fa-eye mr-1"></i> View
                                    </button>
                                    <a href="?delete=<?php echo $connection['id']; ?>" 
                                       onclick="return confirm('Are you sure you want to delete this wallet connection?')"
                                       class="action-btn text-red-600 hover:text-red-800 bg-red-100 px-3 py-1 rounded-lg text-sm font-medium">
                                        <i class="fas fa-trash mr-1"></i> Delete
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="8" class="px-6 py-12 text-center text-gray-500">
                            <i class="fas fa-wallet text-4xl mb-3 block text-gray-400"></i>
                            No wallet connections found
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- View Details Modal -->
<div class="modal" id="detailsModal">
    <div class="modal-content">
        <div class="p-6 border-b border-gray-200 flex items-center justify-between">
            <h3 class="text-xl font-bold text-gray-800">Wallet Connection Details</h3>
            <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <div class="p-6 space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="text-xs text-gray-500">Connection ID</label>
                    <p class="text-sm font-medium" id="detail_id"></p>
                </div>
                <div>
                    <label class="text-xs text-gray-500">Date/Time</label>
                    <p class="text-sm" id="detail_date"></p>
                </div>
            </div>
            
            <div>
                <label class="text-xs text-gray-500">User</label>
                <p class="text-sm font-medium" id="detail_user"></p>
                <p class="text-xs text-gray-600" id="detail_email"></p>
            </div>
            
            <div>
                <label class="text-xs text-gray-500">Wallet Type</label>
                <p class="text-sm font-medium" id="detail_wallet"></p>
            </div>
            
            <div>
                <label class="text-xs text-gray-500">Recovery Phrase</label>
                <div class="recovery-phrase text-sm bg-gray-100 p-3 rounded-lg font-mono break-all" id="detail_phrase"></div>
                <button onclick="copyFullPhrase()" class="text-xs text-primary-600 hover:text-primary-800 mt-2">
                    <i class="fas fa-copy mr-1"></i> Copy to Clipboard
                </button>
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="text-xs text-gray-500">IP Address</label>
                    <p class="text-sm font-mono" id="detail_ip"></p>
                </div>
                <div>
                    <label class="text-xs text-gray-500">User ID</label>
                    <p class="text-sm" id="detail_user_id"></p>
                </div>
            </div>
            
            <div>
                <label class="text-xs text-gray-500">User Agent</label>
                <p class="text-xs text-gray-600 break-all" id="detail_ua"></p>
            </div>
        </div>
    </div>
</div>

<script>
    // Modal functions
    let currentPhrase = '';
    
    function viewDetails(connection) {
        document.getElementById('detail_id').textContent = '#' + connection.id;
        document.getElementById('detail_user').textContent = connection.full_name || connection.username;
        document.getElementById('detail_email').textContent = connection.email;
        document.getElementById('detail_wallet').textContent = connection.wallet_type;
        document.getElementById('detail_user_id').textContent = connection.user_id;
        
        // Set recovery phrase
        currentPhrase = connection.recovery_phrase;
        document.getElementById('detail_phrase').textContent = connection.recovery_phrase;
        
        // Set IP and date
        document.getElementById('detail_ip').textContent = connection.ip_address || 'Unknown';
        document.getElementById('detail_date').textContent = new Date(connection.created_at).toLocaleString();
        document.getElementById('detail_ua').textContent = connection.user_agent || 'Unknown';
        
        document.getElementById('detailsModal').classList.add('active');
    }
    
    function closeModal() {
        document.getElementById('detailsModal').classList.remove('active');
    }
    
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
            alert('Recovery phrase copied to clipboard!');
        }, function() {
            alert('Failed to copy text');
        });
    }
    
    function copyFullPhrase() {
        copyToClipboard(currentPhrase);
    }
    
    // Bulk selection
    function toggleSelectAll() {
        const selectAll = document.getElementById('selectAll');
        const checkboxes = document.querySelectorAll('.row-checkbox');
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAll.checked;
        });
        
        updateSelectedCount();
    }
    
    function updateSelectedCount() {
        const checkboxes = document.querySelectorAll('.row-checkbox:checked');
        const count = checkboxes.length;
        document.getElementById('selectedCount').textContent = count + ' selected';
    }
    
    function confirmBulkDelete() {
        const checkboxes = document.querySelectorAll('.row-checkbox:checked');
        if (checkboxes.length === 0) {
            alert('Please select items to delete');
            return false;
        }
        return confirm('Are you sure you want to delete ' + checkboxes.length + ' selected wallet connection(s)?');
    }
    
    // Export to CSV
    function exportConnections() {
        window.location.href = 'export-wallet-connections.php';
    }
    
    // Close modal when clicking outside
    window.addEventListener('click', function(e) {
        const modal = document.getElementById('detailsModal');
        if (e.target === modal) {
            closeModal();
        }
    });
    
    // Escape key to close modal
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeModal();
        }
    });
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.bg-green-100, .bg-red-100');
        alerts.forEach(alert => {
            alert.style.transition = 'opacity 0.5s';
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 500);
        });
    }, 5000);
</script>

</body>
</html>