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

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

// Get user ID
$user_id = $_SESSION['user_id'];

// Fetch user data
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header("Location: login.php?error=User account not found");
    exit();
}

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

// Check account status
if (isset($user['email_verified']) && $user['email_verified'] == 0) {
    header("Location: verify.php?message=Please verify your email first");
    exit();
}

if (isset($user['account_status']) && $user['account_status'] != 'active') {
    $error_message = "Your account is " . $user['account_status'];
    header("Location: login.php?error=" . urlencode($error_message));
    exit();
}

// Create mining sessions table if it doesn't exist
$conn->query("
    CREATE TABLE IF NOT EXISTS mining_sessions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        crypto_type VARCHAR(50) NOT NULL,
        amount DECIMAL(15,2) NOT NULL,
        profit_percentage DECIMAL(5,2),
        profit_amount DECIMAL(15,2),
        total_return DECIMAL(15,2),
        status ENUM('pending', 'active', 'completed', 'cancelled') DEFAULT 'pending',
        start_time DATETIME,
        end_time DATETIME,
        completed_at DATETIME,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
        INDEX idx_user_status (user_id, status),
        INDEX idx_status_end (status, end_time)
    )
");

// Handle mining start
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['start_mining'])) {
    $crypto_type = mysqli_real_escape_string($conn, $_POST['crypto_type']);
    $amount = floatval($_POST['amount']);
    
    // Validation
    if ($amount <= 0) {
        $message = "Please enter a valid amount";
        $message_type = "error";
    } elseif ($amount < 10) {
        $message = "Minimum mining amount is $10";
        $message_type = "error";
    } elseif ($amount > $user['account_balance']) {
        $message = "Insufficient balance. Your available balance is $" . number_format($user['account_balance'], 2);
        $message_type = "error";
    } else {
        // Check if user has any active mining sessions
        $check_active = $conn->prepare("SELECT COUNT(*) as active FROM mining_sessions WHERE user_id = ? AND status = 'active'");
        $check_active->bind_param("i", $user_id);
        $check_active->execute();
        $active_result = $check_active->get_result();
        $active_count = $active_result->fetch_assoc()['active'];
        $check_active->close();
        
        if ($active_count >= 3) {
            $message = "You can only have up to 3 active mining sessions at once";
            $message_type = "error";
        } else {
            // Deduct from account balance
            $new_balance = $user['account_balance'] - $amount;
            $update_balance = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
            $update_balance->bind_param("di", $new_balance, $user_id);
            $update_balance->execute();
            $update_balance->close();
            
            // Calculate random mining duration (2-10 minutes in seconds)
            $mining_duration = rand(120, 600); // 2-10 minutes in seconds
            
            // Set start and end times
            $start_time = date('Y-m-d H:i:s');
            $end_time = date('Y-m-d H:i:s', strtotime("+{$mining_duration} seconds"));
            
            // Insert mining session
            $insert_stmt = $conn->prepare("
                INSERT INTO mining_sessions 
                (user_id, crypto_type, amount, status, start_time, end_time) 
                VALUES (?, ?, ?, 'active', ?, ?)
            ");
            $insert_stmt->bind_param("isdss", $user_id, $crypto_type, $amount, $start_time, $end_time);
            
            if ($insert_stmt->execute()) {
                $session_id = $conn->insert_id;
                
                // Refresh user data
                $user['account_balance'] = $new_balance;
                
                $message = "Mining started successfully! Mining will complete in " . round($mining_duration/60, 1) . " minutes.";
                $message_type = "success";
            } else {
                $message = "Error starting mining process. Please try again.";
                $message_type = "error";
            }
            $insert_stmt->close();
        }
    }
}

// IMPORTANT: Remove the automatic completion processing from page load
// We'll handle this via AJAX instead

// Handle AJAX requests for mining status and completion
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    
    if ($_GET['ajax'] == 'check_status') {
        $response = ['sessions' => []];
        
        $status_query = $conn->prepare("
            SELECT id, status, end_time, start_time 
            FROM mining_sessions 
            WHERE user_id = ? AND status = 'active'
        ");
        $status_query->bind_param("i", $user_id);
        $status_query->execute();
        $status_result = $status_query->get_result();
        
        while ($row = $status_result->fetch_assoc()) {
            $now = time();
            $end = strtotime($row['end_time']);
            $start = strtotime($row['start_time']);
            $total = $end - $start;
            $elapsed = $now - $start;
            $progress = min(100, max(0, ($elapsed / $total) * 100));
            
            $remaining_seconds = max(0, $end - $now);
            $minutes = floor($remaining_seconds / 60);
            $seconds = $remaining_seconds % 60;
            $time_remaining = sprintf("%d:%02d", $minutes, $seconds);
            
            $response['sessions'][] = [
                'id' => $row['id'],
                'progress' => $progress,
                'time_remaining' => $time_remaining,
                'completed' => ($now >= $end)
            ];
        }
        
        $status_query->close();
        echo json_encode($response);
        exit();
    }
    
    if ($_GET['ajax'] == 'complete_session' && isset($_POST['session_id'])) {
        $session_id = intval($_POST['session_id']);
        
        // Get the session details
        $session_query = $conn->prepare("
            SELECT ms.*, u.account_balance 
            FROM mining_sessions ms
            JOIN users u ON ms.user_id = u.id
            WHERE ms.id = ? AND ms.user_id = ? AND ms.status = 'active'
        ");
        $session_query->bind_param("ii", $session_id, $user_id);
        $session_query->execute();
        $session_result = $session_query->get_result();
        
        if ($session = $session_result->fetch_assoc()) {
            // Check if it's actually completed
            if (strtotime($session['end_time']) <= time()) {
                // Generate random profit percentage between 50% and 200%
                $profit_percentage = rand(50, 200);
                $profit_amount = ($session['amount'] * $profit_percentage) / 100;
                $total_return = $session['amount'] + $profit_amount;
                
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Update user balance
                    $new_balance = $session['account_balance'] + $total_return;
                    $update_balance = $conn->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
                    $update_balance->bind_param("di", $new_balance, $session['user_id']);
                    $update_balance->execute();
                    $update_balance->close();
                    
                    // Update mining session
                    $update_session = $conn->prepare("
                        UPDATE mining_sessions 
                        SET status = 'completed', 
                            profit_percentage = ?, 
                            profit_amount = ?, 
                            total_return = ?,
                            completed_at = NOW() 
                        WHERE id = ?
                    ");
                    $update_session->bind_param("dddi", $profit_percentage, $profit_amount, $total_return, $session['id']);
                    $update_session->execute();
                    $update_session->close();
                    
                    $conn->commit();
                    
                    // Create notification if table exists
                    $check_notif = $conn->query("SHOW TABLES LIKE 'notifications'");
                    if ($check_notif->num_rows > 0) {
                        $notif_title = "Mining Completed";
                        $notif_message = "Your mining session of $" . number_format($session['amount'], 2) . " in {$session['crypto_type']} has completed! You earned $" . number_format($profit_amount, 2) . " profit (" . $profit_percentage . "%). Total return: $" . number_format($total_return, 2);
                        $notif_stmt = $conn->prepare("INSERT INTO notifications (user_id, title, message, notification_type) VALUES (?, ?, ?, 'mining')");
                        $notif_stmt->bind_param("iss", $session['user_id'], $notif_title, $notif_message);
                        $notif_stmt->execute();
                        $notif_stmt->close();
                    }
                    
                    echo json_encode(['success' => true, 'message' => 'Mining completed successfully']);
                } catch (Exception $e) {
                    $conn->rollback();
                    echo json_encode(['success' => false, 'message' => 'Error completing mining session']);
                }
            } else {
                echo json_encode(['success' => false, 'message' => 'Mining session not yet completed']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Session not found']);
        }
        
        $session_query->close();
        exit();
    }
}

// Fetch user's mining sessions
$sessions_stmt = $conn->prepare("
    SELECT * FROM mining_sessions 
    WHERE user_id = ? 
    ORDER BY 
        CASE status 
            WHEN 'active' THEN 1 
            WHEN 'pending' THEN 2 
            WHEN 'completed' THEN 3 
            ELSE 4 
        END,
        created_at DESC
");
$sessions_stmt->bind_param("i", $user_id);
$sessions_stmt->execute();
$sessions_result = $sessions_stmt->get_result();
$sessions_stmt->close();

// Calculate mining statistics
$stats = [
    'total_mined' => 0,
    'total_profit' => 0,
    'total_sessions' => 0,
    'active_sessions' => 0,
    'completed_sessions' => 0
];

$stats_stmt = $conn->prepare("
    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,
        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
    FROM mining_sessions 
    WHERE user_id = ?
");
$stats_stmt->bind_param("i", $user_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
if ($row = $stats_result->fetch_assoc()) {
    $stats = $row;
}
$stats_stmt->close();

// Available cryptocurrencies for mining
$cryptocurrencies = [
    'Bitcoin (BTC)' => ['icon' => 'fa-bitcoin', 'color' => 'orange'],
    'Ethereum (ETH)' => ['icon' => 'fa-ethereum', 'color' => 'blue'],
    'Binance Coin (BNB)' => ['icon' => 'fa-bnb', 'color' => 'yellow'],
    'Cardano (ADA)' => ['icon' => 'fa-cardano', 'color' => 'blue'],
    'Solana (SOL)' => ['icon' => 'fa-solana', 'color' => 'purple'],
    'Polkadot (DOT)' => ['icon' => 'fa-polkadot', 'color' => 'pink'],
    'Dogecoin (DOGE)' => ['icon' => 'fa-doge', 'color' => 'yellow'],
    'Ripple (XRP)' => ['icon' => 'fa-xrp', 'color' => 'blue'],
    'Litecoin (LTC)' => ['icon' => 'fa-litecoin', 'color' => 'gray'],
    'Chainlink (LINK)' => ['icon' => 'fa-link', 'color' => 'blue'],
];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crypto Mining - <?php echo htmlspecialchars($site_settings['site_name'] ?? 'Trading Platform'); ?></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>
        :root {
            --sidebar-width: 16rem;
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-gradient: linear-gradient(135deg, #38b2ac 0%, #319795 100%);
            --warning-gradient: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
            --danger-gradient: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
            --info-gradient: linear-gradient(135deg, #4299e1 0%, #3182ce 100%);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            color: #e2e8f0;
        }
        
        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
            width: var(--sidebar-width);
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
            transform: translateX(-100%);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            overflow-y: auto;
            box-shadow: 4px 0 20px rgba(0, 0, 0, 0.3);
            border-right: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .sidebar.active {
            transform: translateX(0);
        }
        
        @media (min-width: 1024px) {
            .sidebar {
                transform: translateX(0) !important;
            }
        }
        
        .sidebar-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            z-index: 999;
            backdrop-filter: blur(4px);
        }
        
        .sidebar-overlay.active {
            display: block;
        }
        
        /* Main Content */
        .main-content {
            width: 100%;
            min-height: 100vh;
            transition: margin-left 0.3s ease;
        }
        
        @media (min-width: 1024px) {
            .main-content {
                margin-left: var(--sidebar-width);
                width: calc(100% - var(--sidebar-width));
            }
        }
        
        .glass-card {
            background: rgba(30, 41, 59, 0.7);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 1.25rem;
            transition: all 0.3s ease;
        }
        
        .glass-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        .mining-card {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 1.25rem;
            transition: all 0.3s ease;
            overflow: hidden;
        }
        
        .mining-card:hover {
            transform: translateY(-4px);
            border-color: rgba(102, 126, 234, 0.3);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
        }
        
        .crypto-icon {
            width: 48px;
            height: 48px;
            background: rgba(102, 126, 234, 0.1);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: #667eea;
            border: 1px solid rgba(102, 126, 234, 0.2);
        }
        
        .form-input {
            background: rgba(15, 23, 42, 0.6);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.75rem;
            padding: 0.75rem 1rem;
            color: white;
            width: 100%;
            transition: all 0.2s;
        }
        
        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
        }
        
        .form-input::placeholder {
            color: rgba(255, 255, 255, 0.3);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            padding: 0.75rem 1.5rem;
            border-radius: 0.75rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            width: 100%;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
        }
        
        .btn-primary:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }
        
        /* Progress Bar */
        .progress-container {
            width: 100%;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 9999px;
            height: 8px;
            overflow: hidden;
            margin: 0.5rem 0;
            position: relative;
        }
        
        .progress-bar {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 9999px;
            transition: width 0.3s ease;
            position: relative;
            overflow: hidden;
            width: 0%;
        }
        
        .progress-bar::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
            animation: shimmer 2s infinite;
        }
        
        @keyframes shimmer {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }
        
        .mining-active {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.4); }
            70% { box-shadow: 0 0 0 10px rgba(102, 126, 234, 0); }
            100% { box-shadow: 0 0 0 0 rgba(102, 126, 234, 0); }
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }
        
        .status-active {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
        }
        
        .status-completed {
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
        }
        
        .status-pending {
            background: rgba(245, 158, 11, 0.2);
            color: #f59e0b;
        }
        
        /* Mobile Menu Button */
        .mobile-menu-btn {
            position: fixed;
            top: 1.5rem;
            left: 1.5rem;
            z-index: 1100;
            width: 3rem;
            height: 3rem;
            background: rgba(30, 41, 59, 0.95);
            border-radius: 0.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            cursor: pointer;
        }
        
        .mobile-menu-btn:hover {
            background: rgba(30, 41, 59, 1);
            transform: translateY(-2px);
        }
        
        @media (min-width: 1024px) {
            .mobile-menu-btn {
                display: none;
            }
        }
        
        /* Navigation Items */
        .nav-item {
            display: flex;
            align-items: center;
            padding: 0.875rem 1rem;
            border-radius: 0.75rem;
            margin: 0.25rem 0.75rem;
            color: #94a3b8;
            text-decoration: none;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .nav-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            width: 3px;
            background: var(--primary-gradient);
            transform: translateX(-100%);
            transition: transform 0.3s ease;
        }
        
        .nav-item:hover {
            background: rgba(255, 255, 255, 0.05);
            color: #e2e8f0;
            transform: translateX(4px);
        }
        
        .nav-item:hover::before {
            transform: translateX(0);
        }
        
        .nav-item.active {
            background: rgba(102, 126, 234, 0.1);
            color: #e2e8f0;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
        }
        
        .nav-item.active::before {
            transform: translateX(0);
        }
        
        .nav-item.active i {
            color: #667eea;
            transform: scale(1.1);
        }
        
        .nav-item i {
            width: 1.5rem;
            margin-right: 0.875rem;
            transition: all 0.2s ease;
            font-size: 1.1rem;
        }
        
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
        }
        
        ::-webkit-scrollbar-thumb {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <!-- Mobile Menu Button -->
    <button class="mobile-menu-btn" id="menuToggle">
        <i class="fas fa-bars text-white text-xl"></i>
    </button>

    <!-- Sidebar Overlay -->
    <div class="sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Include Sidebar -->
    <?php include("nav.php"); ?>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Header -->
        <div class="border-b border-gray-800/50 p-6 glass-card mx-4 mt-4">
            <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4">
                <div>
                    <h1 class="text-2xl lg:text-3xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                        Crypto Mining
                    </h1>
                    <p class="text-gray-400 mt-1">
                        <i class="fas fa-microchip mr-2"></i> Mine cryptocurrencies with high profit potential
                    </p>
                </div>
                <div class="flex items-center gap-3">
                    <div class="glass-card px-4 py-2">
                        <span class="text-sm text-gray-400">Balance:</span>
                        <span class="text-xl font-bold text-green-400 ml-2" id="account-balance">$<?php echo number_format($user['account_balance'], 2); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mx-4 mt-4">
            <div class="p-4 rounded-xl <?php echo $message_type === 'success' ? 'bg-green-500/20 border-green-500/30' : 'bg-red-500/20 border-red-500/30'; ?> border">
                <div class="flex items-center gap-3">
                    <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?> <?php echo $message_type === 'success' ? 'text-green-400' : 'text-red-400'; ?>"></i>
                    <span><?php echo htmlspecialchars($message); ?></span>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Total Mined</p>
                        <p class="text-2xl font-bold text-white">$<?php echo number_format($stats['total_mined'], 2); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-blue-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-coins text-blue-400 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Total Profit</p>
                        <p class="text-2xl font-bold text-green-400">$<?php echo number_format($stats['total_profit'], 2); ?></p>
                    </div>
                    <div class="w-12 h-12 bg-green-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-chart-line text-green-400 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Active Sessions</p>
                        <p class="text-2xl font-bold text-yellow-400" id="active-sessions-count"><?php echo $stats['active_sessions']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-yellow-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-microchip text-yellow-400 text-xl"></i>
                    </div>
                </div>
            </div>
            
            <div class="glass-card p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-400">Completed</p>
                        <p class="text-2xl font-bold text-purple-400"><?php echo $stats['completed_sessions']; ?></p>
                    </div>
                    <div class="w-12 h-12 bg-purple-500/20 rounded-xl flex items-center justify-center">
                        <i class="fas fa-check-circle text-purple-400 text-xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Start Mining Form -->
        <div class="p-6 pt-0">
            <div class="glass-card p-6">
                <h2 class="text-xl font-bold mb-6 flex items-center gap-2">
                    <i class="fas fa-play text-green-400"></i>
                    Start New Mining Session
                </h2>
                
                <form method="POST" action="" class="grid grid-cols-1 md:grid-cols-2 gap-6" id="mining-form">
                    <div>
                        <label class="form-label">Select Cryptocurrency</label>
                        <select name="crypto_type" class="form-input" required>
                            <option value="" disabled selected>-- Choose a cryptocurrency --</option>
                            <?php foreach ($cryptocurrencies as $crypto => $details): ?>
                            <option value="<?php echo htmlspecialchars($crypto); ?>"><?php echo htmlspecialchars($crypto); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div>
                        <label class="form-label">Investment Amount ($)</label>
                        <input type="number" name="amount" class="form-input" 
                               placeholder="Enter amount (min $10)" min="10" 
                               max="<?php echo $user['account_balance']; ?>" step="0.01" required>
                        <p class="text-xs text-gray-500 mt-1">Max: $<?php echo number_format($user['account_balance'], 2); ?></p>
                    </div>
                    
                    <div class="md:col-span-2">
                        <button type="submit" name="start_mining" class="btn-primary" <?php echo $stats['active_sessions'] >= 3 ? 'disabled' : ''; ?> id="start-mining-btn">
                            <i class="fas fa-play mr-2"></i>
                            Start Mining
                        </button>
                        <?php if ($stats['active_sessions'] >= 3): ?>
                        <p class="text-xs text-yellow-400 text-center mt-2">Maximum 3 active mining sessions allowed</p>
                        <?php endif; ?>
                    </div>
                </form>
                
                <div class="mt-4 p-4 bg-gray-800/30 rounded-xl">
                    <h4 class="font-medium text-white mb-2 flex items-center gap-2">
                        <i class="fas fa-info-circle text-blue-400"></i>
                        Mining Information
                    </h4>
                    <ul class="space-y-2 text-sm text-gray-400">
                        <li class="flex items-start gap-2">
                            <i class="fas fa-clock text-blue-400 mt-0.5 text-xs"></i>
                            <span>Mining duration: 2-10 minutes (randomly selected)</span>
                        </li>
                        <li class="flex items-start gap-2">
                            <i class="fas fa-percentage text-green-400 mt-0.5 text-xs"></i>
                            <span>Profit range: 50% - 200% of your investment</span>
                        </li>
                        <li class="flex items-start gap-2">
                            <i class="fas fa-microchip text-purple-400 mt-0.5 text-xs"></i>
                            <span>Maximum 3 concurrent mining sessions</span>
                        </li>
                        <li class="flex items-start gap-2">
                            <i class="fas fa-shield-alt text-yellow-400 mt-0.5 text-xs"></i>
                            <span>Your mining progress is saved even if you leave the page</span>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- Mining Sessions -->
        <div class="p-6 pt-0">
            <div class="glass-card p-6">
                <h3 class="text-xl font-bold mb-6 flex items-center gap-2">
                    <i class="fas fa-history text-blue-400"></i>
                    Your Mining Sessions
                </h3>
                
                <div id="mining-sessions-container">
                    <?php if ($sessions_result->num_rows > 0): ?>
                    <div class="space-y-4">
                        <?php 
                        $sessions_result->data_seek(0);
                        while ($session = $sessions_result->fetch_assoc()): 
                            $status_class = '';
                            $status_icon = '';
                            switch ($session['status']) {
                                case 'active':
                                    $status_class = 'status-active';
                                    $status_icon = 'fa-microchip';
                                    break;
                                case 'completed':
                                    $status_class = 'status-completed';
                                    $status_icon = 'fa-check-circle';
                                    break;
                                case 'pending':
                                    $status_class = 'status-pending';
                                    $status_icon = 'fa-clock';
                                    break;
                            }
                            
                            // Calculate initial progress for active sessions (for server-side rendering)
                            $progress = 0;
                            $time_remaining = '';
                            if ($session['status'] == 'active') {
                                $now = time();
                                $start = strtotime($session['start_time']);
                                $end = strtotime($session['end_time']);
                                $total = $end - $start;
                                $elapsed = $now - $start;
                                $progress = min(100, max(0, ($elapsed / $total) * 100));
                                
                                $remaining_seconds = max(0, $end - $now);
                                $minutes = floor($remaining_seconds / 60);
                                $seconds = $remaining_seconds % 60;
                                $time_remaining = sprintf("%d:%02d", $minutes, $seconds);
                            }
                        ?>
                        <div class="mining-card p-4 <?php echo $session['status'] == 'active' ? 'mining-active' : ''; ?>" id="session-<?php echo $session['id']; ?>">
                            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                                <div class="flex items-center gap-4">
                                    <div class="crypto-icon">
                                        <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'
                                            };
                                        ?>"></i>
                                    </div>
                                    <div>
                                        <h4 class="font-bold text-white"><?php echo htmlspecialchars($session['crypto_type']); ?></h4>
                                        <p class="text-sm text-gray-400">Invested: $<?php echo number_format($session['amount'], 2); ?></p>
                                    </div>
                                </div>
                                
                                <div class="flex items-center gap-4">
                                    <?php if ($session['status'] == 'completed'): ?>
                                    <div class="text-right">
                                        <p class="text-sm text-gray-400">Profit</p>
                                        <p class="text-lg font-bold text-green-400">+<?php echo $session['profit_percentage']; ?>%</p>
                                        <p class="text-xs text-gray-500">$<?php echo number_format($session['profit_amount'], 2); ?></p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-sm text-gray-400">Total Return</p>
                                        <p class="text-lg font-bold text-white">$<?php echo number_format($session['total_return'], 2); ?></p>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="text-right min-w-[100px]">
                                        <span class="status-badge <?php echo $status_class; ?>">
                                            <i class="fas <?php echo $status_icon; ?>"></i>
                                            <?php echo ucfirst($session['status']); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            
                            <?php if ($session['status'] == 'active'): ?>
                            <div class="mt-4">
                                <div class="flex justify-between text-xs text-gray-400 mb-1">
                                    <span>Mining in progress...</span>
                                    <span id="time-<?php echo $session['id']; ?>"><?php echo $time_remaining; ?> remaining</span>
                                </div>
                                <div class="progress-container">
                                    <div class="progress-bar" id="progress-<?php echo $session['id']; ?>" style="width: <?php echo $progress; ?>%"></div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if ($session['status'] == 'completed'): ?>
                            <div class="mt-3 text-xs text-gray-500">
                                Completed: <?php echo date('M d, Y H:i', strtotime($session['completed_at'])); ?>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endwhile; ?>
                    </div>
                    <?php else: ?>
                    <div class="text-center py-12">
                        <div class="w-20 h-20 bg-gray-800/50 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-microchip text-gray-600 text-3xl"></i>
                        </div>
                        <h4 class="text-white font-medium mb-1">No mining sessions yet</h4>
                        <p class="text-gray-500 text-sm">Start your first mining session above</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Mobile menu functionality
        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.querySelector('.sidebar');
            const sidebarOverlay = document.getElementById('sidebarOverlay');
            const body = document.body;
            
            if (menuToggle && sidebar && sidebarOverlay) {
                menuToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    sidebar.classList.toggle('active');
                    sidebarOverlay.classList.toggle('active');
                    body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
                });
                
                sidebarOverlay.addEventListener('click', function() {
                    sidebar.classList.remove('active');
                    sidebarOverlay.classList.remove('active');
                    body.style.overflow = '';
                });
            }
            
            // Close sidebar when clicking a nav link on mobile
            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('click', function() {
                    if (window.innerWidth < 1024) {
                        setTimeout(() => {
                            sidebar.classList.remove('active');
                            sidebarOverlay.classList.remove('active');
                            body.style.overflow = '';
                        }, 200);
                    }
                });
            });
            
            // Handle window resize
            window.addEventListener('resize', function() {
                if (window.innerWidth >= 1024) {
                    sidebar.classList.add('active');
                    sidebarOverlay.classList.remove('active');
                    body.style.overflow = '';
                } else {
                    sidebar.classList.remove('active');
                    sidebarOverlay.classList.remove('active');
                    body.style.overflow = '';
                }
            });
            
            // Initialize sidebar state
            if (window.innerWidth >= 1024) {
                sidebar.classList.add('active');
            }
            
            // Set active nav item
            const currentPage = window.location.pathname.split('/').pop() || 'crypto-mining.php';
            document.querySelectorAll('.nav-item').forEach(nav => {
                const href = nav.getAttribute('href');
                if (href && href.includes(currentPage)) {
                    nav.classList.add('active');
                }
            });
            
            // Start real-time updates for mining progress
            startMiningUpdates();
        });
        
        // Real-time mining progress updates
        let updateInterval;
        let completedSessions = [];
        
        function startMiningUpdates() {
            // Clear any existing interval
            if (updateInterval) {
                clearInterval(updateInterval);
            }
            
            // Check immediately
            checkMiningStatus();
            
            // Then check every second
            updateInterval = setInterval(checkMiningStatus, 1000);
        }
        
        function checkMiningStatus() {
            fetch('?ajax=check_status')
                .then(response => response.json())
                .then(data => {
                    let needsReload = false;
                    
                    data.sessions.forEach(session => {
                        updateProgressBar(session.id, session.progress, session.time_remaining);
                        
                        // Check if session just completed
                        if (session.completed && !completedSessions.includes(session.id)) {
                            completedSessions.push(session.id);
                            completeMiningSession(session.id);
                            needsReload = true;
                        }
                    });
                    
                    // Reload if any session completed
                    if (needsReload) {
                        setTimeout(() => {
                            window.location.reload();
                        }, 2000); // Reload after 2 seconds to show completion animation
                    }
                })
                .catch(error => console.error('Error checking mining status:', error));
        }
        
        function updateProgressBar(sessionId, progress, timeRemaining) {
            const progressBar = document.getElementById('progress-' + sessionId);
            const timeDisplay = document.getElementById('time-' + sessionId);
            
            if (progressBar) {
                progressBar.style.width = progress + '%';
            }
            
            if (timeDisplay) {
                timeDisplay.textContent = timeRemaining + ' remaining';
            }
        }
        
        function completeMiningSession(sessionId) {
            // Send request to complete the mining session
            fetch('?ajax=complete_session', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'session_id=' + sessionId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('Session ' + sessionId + ' completed successfully');
                }
            })
            .catch(error => console.error('Error completing session:', error));
        }
        
        // Form validation
        document.getElementById('mining-form')?.addEventListener('submit', function(e) {
            const amount = parseFloat(document.querySelector('input[name="amount"]').value);
            const balance = <?php echo $user['account_balance']; ?>;
            
            if (amount > balance) {
                e.preventDefault();
                alert('Insufficient balance! Your available balance is $' + balance.toFixed(2));
            }
        });
        
        // Clean up interval when leaving page
        window.addEventListener('beforeunload', function() {
            if (updateInterval) {
                clearInterval(updateInterval);
            }
        });
    </script>
</body>
</html>