<?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();

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$date_filter = $_GET['date'] ?? '';
$crypto_filter = $_GET['crypto'] ?? 'all';
$search_query = $_GET['search'] ?? '';

// Build query with filters
$where_conditions = [];
$params = [];
$types = '';

// Status filter
if ($status_filter != 'all' && in_array($status_filter, ['active', 'completed', 'pending', 'cancelled'])) {
    $where_conditions[] = "ms.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

// Crypto filter
if ($crypto_filter != 'all') {
    $where_conditions[] = "ms.crypto_type LIKE ?";
    $params[] = "%{$crypto_filter}%";
    $types .= 's';
}

// Date filter
if ($date_filter == 'today') {
    $where_conditions[] = "DATE(ms.created_at) = CURDATE()";
} elseif ($date_filter == 'week') {
    $where_conditions[] = "ms.created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)";
} elseif ($date_filter == 'month') {
    $where_conditions[] = "ms.created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
}

// Search filter
if (!empty($search_query)) {
    $where_conditions[] = "(u.username LIKE ? OR u.email LIKE ? OR u.full_name LIKE ? OR ms.crypto_type LIKE ?)";
    $search_param = "%{$search_query}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Fetch mining sessions with user details
$query = "
    SELECT 
        ms.*,
        u.username,
        u.email,
        u.full_name,
        u.account_balance as user_balance,
        u.account_tier,
        u.account_status
    FROM mining_sessions ms
    JOIN users u ON ms.user_id = u.id
    $where_clause
    ORDER BY 
        CASE ms.status 
            WHEN 'active' THEN 1
            WHEN 'pending' THEN 2
            WHEN 'completed' THEN 3
            WHEN 'cancelled' THEN 4
            ELSE 5
        END,
        ms.created_at DESC
";

$stmt = $conn->prepare($query);

// Bind parameters if any
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();
$mining_sessions = [];

while ($row = $result->fetch_assoc()) {
    $mining_sessions[] = $row;
}
$stmt->close();

// Get mining statistics
$statsQuery = "
    SELECT 
        COUNT(*) as total_sessions,
        SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_sessions,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_sessions,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_sessions,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_sessions,
        COALESCE(SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END), 0) as total_mined,
        COALESCE(SUM(CASE WHEN status = 'completed' THEN profit_amount ELSE 0 END), 0) as total_profit,
        COALESCE(SUM(amount), 0) as total_invested,
        COALESCE(AVG(CASE WHEN status = 'completed' THEN profit_percentage END), 0) as avg_profit_percentage,
        COUNT(DISTINCT user_id) as unique_miners
    FROM mining_sessions
";

$statsResult = $conn->query($statsQuery);
$stats = $statsResult->fetch_assoc();

// Get crypto type distribution
$cryptoQuery = "
    SELECT 
        crypto_type,
        COUNT(*) as session_count,
        SUM(amount) as total_amount,
        SUM(CASE WHEN status = 'completed' THEN profit_amount ELSE 0 END) as total_profit,
        AVG(CASE WHEN status = 'completed' THEN profit_percentage END) as avg_profit
    FROM mining_sessions
    GROUP BY crypto_type
    ORDER BY session_count DESC
    LIMIT 10
";
$cryptoResult = $conn->query($cryptoQuery);
$crypto_stats = [];
while ($row = $cryptoResult->fetch_assoc()) {
    $crypto_stats[] = $row;
}

// Get daily mining activity for the last 30 days
$dailyQuery = "
    SELECT 
        DATE(created_at) as date,
        COUNT(*) as sessions,
        SUM(amount) as invested,
        SUM(CASE WHEN status = 'completed' THEN profit_amount ELSE 0 END) as profits
    FROM mining_sessions
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY DATE(created_at)
    ORDER BY date DESC
";
$dailyResult = $conn->query($dailyQuery);
$daily_activity = [];
while ($row = $dailyResult->fetch_assoc()) {
    $daily_activity[] = $row;
}

// Get top miners by total invested
$topMinersQuery = "
    SELECT 
        u.id,
        u.username,
        u.full_name,
        u.email,
        COUNT(ms.id) as total_sessions,
        SUM(ms.amount) as total_invested,
        SUM(CASE WHEN ms.status = 'completed' THEN ms.profit_amount ELSE 0 END) as total_profit,
        MAX(ms.created_at) as last_mining
    FROM users u
    JOIN mining_sessions ms ON u.id = ms.user_id
    GROUP BY u.id, u.username, u.full_name, u.email
    ORDER BY total_invested DESC
    LIMIT 10
";
$topMinersResult = $conn->query($topMinersQuery);
$top_miners = [];
while ($row = $topMinersResult->fetch_assoc()) {
    $top_miners[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crypto Mining Management - Unify Grant</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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f3f4f6;
        }
        
        .mining-card {
            transition: all 0.3s ease;
        }
        
        .mining-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .status-active { 
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white; 
        }
        .status-completed { 
            background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
            color: white; 
        }
        .status-pending { 
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white; 
        }
        .status-cancelled { 
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white; 
        }
        
        .profit-positive {
            color: #10b981;
        }
        
        .progress-bar {
            height: 6px;
            background: linear-gradient(90deg, #3b82f6, #8b5cf6);
            border-radius: 3px;
            transition: width 0.3s ease;
        }
        
        .crypto-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">

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

    <!-- Main Content -->
    <div class="main-content ml-64">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold text-gray-800">Crypto Mining Management</h2>
                    <p class="text-gray-600">Monitor and analyze all mining activities</p>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="exportMiningData()" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition">
                        <i class="fas fa-download mr-2"></i>
                        Export Data
                    </button>
                    <button onclick="refreshData()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                        <i class="fas fa-sync-alt mr-2"></i>
                        Refresh
                    </button>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="p-8">
            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mining-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Sessions</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['total_sessions']); ?></p>
                            <p class="text-xs text-gray-500 mt-1">
                                <span class="text-green-600"><?php echo $stats['active_sessions']; ?> active</span>
                            </p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-microchip text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mining-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Invested</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2">$<?php echo number_format($stats['total_invested'], 2); ?></p>
                            <p class="text-xs text-gray-500 mt-1">
                                Across <?php echo $stats['unique_miners']; ?> miners
                            </p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-coins text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mining-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Total Mined</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2">$<?php echo number_format($stats['total_mined'], 2); ?></p>
                            <p class="text-xs text-gray-500 mt-1">
                                +$<?php echo number_format($stats['total_profit'], 2); ?> profit
                            </p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-chart-line text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mining-card">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm font-medium text-gray-600">Avg Profit</p>
                            <p class="text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['avg_profit_percentage'], 1); ?>%</p>
                            <p class="text-xs text-gray-500 mt-1">
                                Per completed session
                            </p>
                        </div>
                        <div class="w-12 h-12 bg-yellow-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-percentage text-yellow-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

         
            <!-- Filters -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">Filter Mining Sessions</h3>
                <form method="GET" class="grid grid-cols-1 md:grid-cols-5 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="completed" <?php echo $status_filter == 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="cancelled" <?php echo $status_filter == 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Cryptocurrency</label>
                        <select name="crypto" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="all" <?php echo $crypto_filter == 'all' ? 'selected' : ''; ?>>All Cryptocurrencies</option>
                            <?php foreach ($crypto_stats as $crypto): ?>
                            <option value="<?php echo htmlspecialchars($crypto['crypto_type']); ?>" <?php echo $crypto_filter == $crypto['crypto_type'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($crypto['crypto_type']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Date Range</label>
                        <select name="date" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                            <option value="">All Time</option>
                            <option value="today" <?php echo $date_filter == 'today' ? 'selected' : ''; ?>>Today</option>
                            <option value="week" <?php echo $date_filter == 'week' ? 'selected' : ''; ?>>This Week</option>
                            <option value="month" <?php echo $date_filter == 'month' ? 'selected' : ''; ?>>This Month</option>
                        </select>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Search</label>
                        <input type="text" name="search" value="<?php echo htmlspecialchars($search_query); ?>" 
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg" 
                               placeholder="User or crypto...">
                    </div>
                    
                    <div class="flex items-end">
                        <button type="submit" class="w-full px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                            <i class="fas fa-filter mr-2"></i>
                            Apply Filters
                        </button>
                        <a href="crypto-mining.php" class="ml-2 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                            <i class="fas fa-redo"></i>
                        </a>
                    </div>
                </form>
            </div>

            <!-- Mining Sessions Table -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-8">
                <div class="p-6 border-b border-gray-200">
                    <div class="flex items-center justify-between">
                        <h3 class="text-lg font-semibold text-gray-800">Mining Sessions</h3>
                        <div class="text-sm text-gray-600">
                            Showing <?php echo count($mining_sessions); ?> of <?php echo $stats['total_sessions']; ?> sessions
                        </div>
                    </div>
                </div>
                
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-gray-50 text-left text-sm text-gray-500">
                                <th class="py-3 px-6 font-medium">User</th>
                                <th class="py-3 px-6 font-medium">Cryptocurrency</th>
                                <th class="py-3 px-6 font-medium">Amount</th>
                                <th class="py-3 px-6 font-medium">Profit</th>
                                <th class="py-3 px-6 font-medium">Total Return</th>
                                <th class="py-3 px-6 font-medium">Status</th>
                                <th class="py-3 px-6 font-medium">Duration</th>
                                <th class="py-3 px-6 font-medium">Started</th>
                                <th class="py-3 px-6 font-medium">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (empty($mining_sessions)): ?>
                            <tr>
                                <td colspan="9" class="py-8 text-center text-gray-500">
                                    <i class="fas fa-microchip text-3xl mb-2 block"></i>
                                    No mining sessions found
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($mining_sessions as $session): ?>
                            <tr class="hover:bg-gray-50 transition">
                                <td class="py-4 px-6">
                                    <div class="flex items-center">
                                        <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center mr-3">
                                            <span class="text-blue-800 font-medium text-xs">
                                                <?php echo !empty($session['full_name']) ? strtoupper(substr($session['full_name'], 0, 1)) : 'U'; ?>
                                            </span>
                                        </div>
                                        <div>
                                            <p class="font-medium text-gray-800">
                                                <?php echo !empty($session['full_name']) ? htmlspecialchars($session['full_name']) : htmlspecialchars($session['username']); ?>
                                            </p>
                                            <p class="text-xs text-gray-500">@<?php echo htmlspecialchars($session['username']); ?></p>
                                        </div>
                                    </div>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="crypto-badge">
                                        <i class="fas <?php 
                                            $crypto_name = explode(' ', $session['crypto_type'])[0];
                                            echo match(strtolower($crypto_name)) {
                                                'bitcoin' => 'fa-bitcoin',
                                                'ethereum' => 'fa-ethereum',
                                                'binance' => 'fa-bnb',
                                                'cardano' => 'fa-cardano',
                                                'solana' => 'fa-solana',
                                                'polkadot' => 'fa-polkadot',
                                                'dogecoin' => 'fa-doge',
                                                'ripple' => 'fa-xrp',
                                                'litecoin' => 'fa-litecoin',
                                                'chainlink' => 'fa-link',
                                                default => 'fa-coins'
                                            };
                                        ?> mr-1"></i>
                                        <?php echo htmlspecialchars($session['crypto_type']); ?>
                                    </span>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="font-medium">$<?php echo number_format($session['amount'], 2); ?></span>
                                </td>
                                <td class="py-4 px-6">
                                    <?php if ($session['status'] == 'completed'): ?>
                                        <span class="text-green-600 font-medium">
                                            +<?php echo $session['profit_percentage']; ?>%
                                        </span>
                                        <p class="text-xs text-gray-500">$<?php echo number_format($session['profit_amount'], 2); ?></p>
                                    <?php else: ?>
                                        <span class="text-gray-400">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-4 px-6">
                                    <?php if ($session['status'] == 'completed'): ?>
                                        <span class="font-medium">$<?php echo number_format($session['total_return'], 2); ?></span>
                                    <?php else: ?>
                                        <span class="text-gray-400">-</span>
                                    <?php endif; ?>
                                </td>
                                <td class="py-4 px-6">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium status-<?php echo $session['status']; ?>">
                                        <?php echo ucfirst($session['status']); ?>
                                    </span>
                                    <?php if ($session['status'] == 'active'): ?>
                                        <?php 
                                        $now = time();
                                        $start = strtotime($session['start_time']);
                                        $end = strtotime($session['end_time']);
                                        $progress = min(100, (($now - $start) / ($end - $start)) * 100);
                                        ?>
                                        <div class="w-20 mt-2">
                                            <div class="bg-gray-200 rounded-full h-1">
                                                <div class="progress-bar" style="width: <?php echo $progress; ?>%"></div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </td>
                                <td class="py-4 px-6">
                                    <?php 
                                    if ($session['status'] == 'completed') {
                                        $start = strtotime($session['start_time']);
                                        $end = strtotime($session['end_time']);
                                        $duration = $end - $start;
                                        echo floor($duration / 60) . ' min ' . ($duration % 60) . ' sec';
                                    } elseif ($session['status'] == 'active') {
                                        $now = time();
                                        $end = strtotime($session['end_time']);
                                        $remaining = max(0, $end - $now);
                                        echo floor($remaining / 60) . ':' . str_pad($remaining % 60, 2, '0', STR_PAD_LEFT) . ' left';
                                    } else {
                                        echo '-';
                                    }
                                    ?>
                                </td>
                                <td class="py-4 px-6">
                                    <p class="text-sm text-gray-600"><?php echo date('M d, Y', strtotime($session['created_at'])); ?></p>
                                    <p class="text-xs text-gray-500"><?php echo date('h:i A', strtotime($session['created_at'])); ?></p>
                                </td>
                                <td class="py-4 px-6">
                                    <div class="flex space-x-2">
                                        <button onclick="viewSession(<?php echo $session['id']; ?>)" 
                                                class="text-blue-600 hover:text-blue-800" title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <?php if ($session['status'] == 'active'): ?>
                                        <button onclick="cancelSession(<?php echo $session['id']; ?>)" 
                                                class="text-red-600 hover:text-red-800" title="Cancel Session">
                                            <i class="fas fa-times-circle"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Top Miners and Quick Stats -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                <!-- Top Miners -->
                <div class="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Top Miners</h3>
                    
                    <div class="space-y-4">
                        <?php foreach ($top_miners as $index => $miner): ?>
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                            <div class="flex items-center">
                                <div class="w-8 h-8 <?php 
                                    echo $index == 0 ? 'bg-yellow-100' : ($index == 1 ? 'bg-gray-100' : ($index == 2 ? 'bg-orange-100' : 'bg-blue-100')); 
                                ?> rounded-full flex items-center justify-center mr-3">
                                    <span class="font-bold text-sm <?php 
                                        echo $index == 0 ? 'text-yellow-600' : ($index == 1 ? 'text-gray-600' : ($index == 2 ? 'text-orange-600' : 'text-blue-600')); 
                                    ?>">#<?php echo $index + 1; ?></span>
                                </div>
                                <div>
                                    <p class="font-medium text-gray-800">
                                        <?php echo !empty($miner['full_name']) ? htmlspecialchars($miner['full_name']) : htmlspecialchars($miner['username']); ?>
                                    </p>
                                    <p class="text-xs text-gray-500"><?php echo $miner['total_sessions']; ?> sessions</p>
                                </div>
                            </div>
                            <div class="text-right">
                                <p class="font-bold text-gray-800">$<?php echo number_format($miner['total_invested'], 2); ?></p>
                                <p class="text-xs text-green-600">+$<?php echo number_format($miner['total_profit'], 2); ?> profit</p>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Quick Stats -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">Quick Stats</h3>
                    
                    <div class="space-y-4">
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600">Success Rate</span>
                            <span class="font-bold text-gray-800">
                                <?php 
                                $success_rate = $stats['total_sessions'] > 0 ? 
                                    ($stats['completed_sessions'] / $stats['total_sessions'] * 100) : 0;
                                echo number_format($success_rate, 1); ?>%
                            </span>
                        </div>
                        
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600">Avg Mining Time</span>
                            <span class="font-bold text-gray-800">6.5 min</span>
                        </div>
                        
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600">Most Active Crypto</span>
                            <span class="font-bold text-gray-800">
                                <?php 
                                if (!empty($crypto_stats)) {
                                    echo htmlspecialchars($crypto_stats[0]['crypto_type']);
                                } else {
                                    echo 'N/A';
                                }
                                ?>
                            </span>
                        </div>
                        
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600">Active Miners Now</span>
                            <span class="font-bold text-gray-800"><?php echo $stats['active_sessions']; ?></span>
                        </div>
                        
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600">Total Profit Paid</span>
                            <span class="font-bold text-green-600">$<?php echo number_format($stats['total_profit'], 2); ?></span>
                        </div>
                        
                        <div class="flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                            <span class="text-gray-600">Avg Profit/Session</span>
                            <span class="font-bold text-gray-800">
                                $<?php 
                                $avg_profit = $stats['completed_sessions'] > 0 ? 
                                    $stats['total_profit'] / $stats['completed_sessions'] : 0;
                                echo number_format($avg_profit, 2); 
                                ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Session Details Modal -->
    <div id="session-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 hidden">
        <div class="relative top-20 mx-auto p-5 border w-full max-w-2xl shadow-lg rounded-lg bg-white">
            <div class="flex justify-between items-center pb-3">
                <h3 class="text-xl font-semibold text-gray-800" id="session-title">Mining Session Details</h3>
                <button onclick="closeSessionModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <div id="session-details" class="space-y-4">
                <!-- Details will be loaded here -->
            </div>
            
            <div class="flex justify-end mt-6">
                <button onclick="closeSessionModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                    Close
                </button>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script>
        // Chart initialization
        document.addEventListener('DOMContentLoaded', function() {
            // Daily Activity Chart
            const ctx = document.getElementById('dailyChart').getContext('2d');
            
            const dailyData = <?php echo json_encode(array_reverse($daily_activity)); ?>;
            const labels = dailyData.map(d => d.date);
            const investedData = dailyData.map(d => d.invested);
            const profitData = dailyData.map(d => d.profits);
            
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Invested Amount',
                        data: investedData,
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: true
                    }, {
                        label: 'Profit Earned',
                        data: profitData,
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return '$' + value;
                                }
                            }
                        }
                    }
                }
            });
        });

        // Session viewing
        function viewSession(sessionId) {
            fetch(`get-mining-session.php?id=${sessionId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displaySessionDetails(data.session);
                    } else {
                        alert('Error loading session details');
                    }
                })
                .catch(error => console.error('Error:', error));
        }
        
        function displaySessionDetails(session) {
            const modal = document.getElementById('session-modal');
            const details = document.getElementById('session-details');
            
            let profitHtml = '';
            if (session.status === 'completed') {
                profitHtml = `
                    <div class="grid grid-cols-2 gap-4">
                        <div class="p-3 bg-green-50 rounded-lg">
                            <p class="text-sm text-gray-600">Profit Percentage</p>
                            <p class="text-xl font-bold text-green-600">+${session.profit_percentage}%</p>
                        </div>
                        <div class="p-3 bg-green-50 rounded-lg">
                            <p class="text-sm text-gray-600">Profit Amount</p>
                            <p class="text-xl font-bold text-green-600">$${parseFloat(session.profit_amount).toFixed(2)}</p>
                        </div>
                        <div class="p-3 bg-blue-50 rounded-lg col-span-2">
                            <p class="text-sm text-gray-600">Total Return</p>
                            <p class="text-xl font-bold text-blue-600">$${parseFloat(session.total_return).toFixed(2)}</p>
                        </div>
                    </div>
                `;
            }
            
            details.innerHTML = `
                <div class="grid grid-cols-2 gap-4">
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-600">User</p>
                        <p class="font-medium">${session.full_name || session.username}</p>
                        <p class="text-xs text-gray-500">${session.email}</p>
                    </div>
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-600">Cryptocurrency</p>
                        <p class="font-medium">${session.crypto_type}</p>
                    </div>
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-600">Investment Amount</p>
                        <p class="font-bold">$${parseFloat(session.amount).toFixed(2)}</p>
                    </div>
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-600">Status</p>
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium status-${session.status}">
                            ${session.status.charAt(0).toUpperCase() + session.status.slice(1)}
                        </span>
                    </div>
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-600">Started</p>
                        <p class="font-medium">${new Date(session.start_time).toLocaleString()}</p>
                    </div>
                    <div class="p-3 bg-gray-50 rounded-lg">
                        <p class="text-sm text-gray-600">End Time</p>
                        <p class="font-medium">${session.end_time ? new Date(session.end_time).toLocaleString() : '-'}</p>
                    </div>
                </div>
                ${profitHtml}
            `;
            
            modal.classList.remove('hidden');
        }
        
        function closeSessionModal() {
            document.getElementById('session-modal').classList.add('hidden');
        }
        
        // Cancel session
        function cancelSession(sessionId) {
            if (confirm('Are you sure you want to cancel this mining session? The user will be refunded.')) {
                fetch('cancel-mining-session.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'session_id=' + sessionId
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Session cancelled successfully');
                        window.location.reload();
                    } else {
                        alert('Error cancelling session: ' + data.message);
                    }
                })
                .catch(error => console.error('Error:', error));
            }
        }
        
        // Export data
        function exportMiningData() {
            const status = document.querySelector('select[name="status"]').value;
            const crypto = document.querySelector('select[name="crypto"]').value;
            const date = document.querySelector('select[name="date"]').value;
            
            window.open(`export-mining-data.php?status=${status}&crypto=${crypto}&date=${date}`, '_blank');
        }
        
        // Refresh data
        function refreshData() {
            window.location.reload();
        }
        
        // Auto-refresh every 5 minutes
        setTimeout(() => {
            window.location.reload();
        }, 300000);
    </script>
</body>
</html>