<?php
require_once '../includes/admin_auth.php';

if (!$adminAuth->isLoggedIn()) {
    header("Location: login.php");
    exit();
}

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

// Get statistics
$stats = [];
$queries = [
    'total_users' => "SELECT COUNT(*) as count FROM users",
    'active_users' => "SELECT COUNT(*) as count FROM users WHERE account_status = 'active'",
    'total_deposits' => "SELECT SUM(amount) as total FROM transactions WHERE type = 'deposit' AND status = 'completed'",
    'total_withdrawals' => "SELECT SUM(amount) as total FROM transactions WHERE type = 'withdrawal' AND status = 'completed'",
    'pending_deposits' => "SELECT COUNT(*) as count FROM transactions WHERE type = 'deposit' AND status = 'pending'",
    'pending_withdrawals' => "SELECT COUNT(*) as count FROM transactions WHERE type = 'withdrawal' AND status = 'pending'",
    'active_investments' => "SELECT COUNT(*) as count FROM investments WHERE status = 'running'",
    'total_profits' => "SELECT SUM(amount) as total FROM transactions WHERE type = 'profit'",
    'support_tickets' => "SELECT COUNT(*) as count FROM support_tickets WHERE status = 'open'"
];

foreach ($queries as $key => $query) {
    $stmt = $db->prepare($query);
    $stmt->execute();
    $result = $stmt->fetch();
    $stats[$key] = $result['count'] ?? $result['total'] ?? 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - <?php echo SITE_NAME; ?></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">
</head>
<body class="bg-gray-100">
    <div class="flex">
        <!-- Sidebar -->
        <div id="sidebar" class="w-64 bg-gray-900 text-white min-h-screen hidden md:block fixed md:relative top-0 left-0 z-50 h-full overflow-y-auto">
            <div class="p-6">
                <div class="flex justify-between items-center mb-8">
                    <div class="flex items-center space-x-3">
                        <i class="fas fa-chart-line text-2xl text-purple-500"></i>
                        <span class="text-xl font-bold"><?php echo SITE_NAME; ?> Admin</span>
                    </div>
                    <button id="sidebarClose" class="md:hidden text-gray-400 hover:text-white focus:outline-none">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                
                <!-- Admin Info -->
                <div class="bg-gray-800 rounded-lg p-4 mb-6">
                    <div class="flex items-center space-x-3">
                        <div class="w-12 h-12 bg-gradient-to-r from-purple-600 to-blue-600 rounded-full flex items-center justify-center">
                            <i class="fas fa-user-shield text-xl"></i>
                        </div>
                        <div>
                            <p class="font-semibold"><?php echo $_SESSION['admin_username']; ?></p>
                            <p class="text-gray-400 text-sm"><?php echo ucfirst($_SESSION['admin_role']); ?></p>
                        </div>
                    </div>
                </div>

                <!-- Navigation -->
                <nav class="space-y-1">
                    <a href="index.php" class="flex items-center space-x-3 p-3 rounded-lg bg-gradient-to-r from-purple-700 to-blue-700">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>Dashboard</span>
                    </a>
                    <a href="users.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-users"></i>
                        <span>Users Management</span>
                    </a>
                    <a href="transactions.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-exchange-alt"></i>
                        <span>Transactions</span>
                    </a>
                    <a href="deposits.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-money-bill-wave"></i>
                        <span>Deposits</span>
                    </a>
                    <a href="withdrawals.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-wallet"></i>
                        <span>Withdrawals</span>
                    </a>
                    <a href="investments.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-chart-pie"></i>
                        <span>Investments</span>
                    </a>
                    <a href="plans.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-list-alt"></i>
                        <span>Investment Plans</span>
                    </a>
                    <a href="support.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-headset"></i>
                        <span>Support Tickets</span>
                    </a>
                    <a href="settings.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-cog"></i>
                        <span>Settings</span>
                    </a>
                    <a href="logs.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-gray-800">
                        <i class="fas fa-history"></i>
                        <span>Activity Logs</span>
                    </a>
                    <a href="../logout.php" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-red-800 text-red-400">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Logout</span>
                    </a>
                </nav>
            </div>
        </div>

        <!-- Main Content -->
        <div class="flex-1 p-4 md:p-6 min-w-0">
            <!-- Header -->
            <div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4 mb-8">
                <div class="flex items-center">
                    <button id="sidebarToggle" class="md:hidden mr-4 text-gray-600 hover:text-gray-900 focus:outline-none">
                        <i class="fas fa-bars text-2xl"></i>
                    </button>
                    <h1 class="text-3xl font-bold text-gray-800">Admin Dashboard</h1>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="text-gray-600">Last login: Today</span>
                    <button onclick="refreshStats()" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-sync-alt mr-2"></i>Refresh
                    </button>
                </div>
            </div>

            <!-- Stats Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
                <!-- Total Users -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-blue-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600">Total Users</p>
                            <h3 class="text-2xl font-bold text-blue-600"><?php echo number_format($stats['total_users']); ?></h3>
                        </div>
                        <div class="bg-blue-100 p-3 rounded-full">
                            <i class="fas fa-users text-blue-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <a href="users.php" class="text-blue-600 hover:text-blue-800 text-sm font-semibold">
                            View All <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>
                </div>

                <!-- Total Deposits -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-green-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600">Total Deposits</p>
                            <h3 class="text-2xl font-bold text-green-600">$<?php echo number_format($stats['total_deposits'], 2); ?></h3>
                        </div>
                        <div class="bg-green-100 p-3 rounded-full">
                            <i class="fas fa-money-bill-wave text-green-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <span class="text-sm <?php echo $stats['pending_deposits'] > 0 ? 'text-red-600' : 'text-gray-600'; ?>">
                            <?php echo $stats['pending_deposits']; ?> pending
                        </span>
                    </div>
                </div>

                <!-- Active Investments -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-purple-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600">Active Investments</p>
                            <h3 class="text-2xl font-bold text-purple-600"><?php echo number_format($stats['active_investments']); ?></h3>
                        </div>
                        <div class="bg-purple-100 p-3 rounded-full">
                            <i class="fas fa-chart-pie text-purple-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <a href="investments.php" class="text-purple-600 hover:text-purple-800 text-sm font-semibold">
                            Manage <i class="fas fa-cog ml-1"></i>
                        </a>
                    </div>
                </div>

                <!-- Support Tickets -->
                <div class="bg-white rounded-xl shadow p-6 border-l-4 border-yellow-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-600">Support Tickets</p>
                            <h3 class="text-2xl font-bold text-yellow-600"><?php echo number_format($stats['support_tickets']); ?></h3>
                        </div>
                        <div class="bg-yellow-100 p-3 rounded-full">
                            <i class="fas fa-headset text-yellow-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="mt-4">
                        <a href="support.php" class="text-yellow-600 hover:text-yellow-800 text-sm font-semibold">
                            View Tickets <i class="fas fa-external-link-alt ml-1"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-lg font-bold mb-4">Quick Actions</h3>
                    <div class="space-y-3">
                        <a href="users.php?action=create" class="block bg-blue-50 hover:bg-blue-100 p-3 rounded-lg text-blue-700">
                            <i class="fas fa-user-plus mr-2"></i>Create New User
                        </a>
                        <a href="deposits.php?status=pending" class="block bg-green-50 hover:bg-green-100 p-3 rounded-lg text-green-700">
                            <i class="fas fa-check-circle mr-2"></i>Approve Deposits
                        </a>
                        <a href="withdrawals.php?status=pending" class="block bg-yellow-50 hover:bg-yellow-100 p-3 rounded-lg text-yellow-700">
                            <i class="fas fa-wallet mr-2"></i>Process Withdrawals
                        </a>
                        <a href="plans.php?action=create" class="block bg-purple-50 hover:bg-purple-100 p-3 rounded-lg text-purple-700">
                            <i class="fas fa-plus-circle mr-2"></i>Add Investment Plan
                        </a>
                    </div>
                </div>

                <!-- Recent Users -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-lg font-bold mb-4">Recent Users</h3>
                    <?php
                    $stmt = $db->prepare("SELECT username, email, created_at, account_status FROM users ORDER BY created_at DESC LIMIT 5");
                    $stmt->execute();
                    $users = $stmt->fetchAll();
                    ?>
                    <div class="space-y-3">
                        <?php foreach ($users as $user): ?>
                        <div class="flex items-center justify-between p-2 hover:bg-gray-50 rounded">
                            <div>
                                <p class="font-semibold"><?php echo htmlspecialchars($user['username']); ?></p>
                                <p class="text-sm text-gray-500"><?php echo htmlspecialchars($user['email']); ?></p>
                            </div>
                            <span class="px-2 py-1 text-xs rounded <?php echo $user['account_status'] == 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                <?php echo ucfirst($user['account_status']); ?>
                            </span>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="mt-4">
                        <a href="users.php" class="text-purple-600 hover:text-purple-800 text-sm font-semibold">
                            View All Users <i class="fas fa-arrow-right ml-1"></i>
                        </a>
                    </div>
                </div>

                <!-- System Status -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-lg font-bold mb-4">System Status</h3>
                    <div class="space-y-4">
                        <div>
                            <div class="flex justify-between mb-1">
                                <span class="text-sm">Server Load</span>
                                <span class="text-sm font-semibold">45%</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-2">
                                <div class="bg-green-600 h-2 rounded-full" style="width: 45%"></div>
                            </div>
                        </div>
                        <div>
                            <div class="flex justify-between mb-1">
                                <span class="text-sm">Database Status</span>
                                <span class="text-sm font-semibold text-green-600">Online</span>
                            </div>
                        </div>
                        <div>
                            <div class="flex justify-between mb-1">
                                <span class="text-sm">Last Backup</span>
                                <span class="text-sm">Today 02:00 AM</span>
                            </div>
                        </div>
                        <div class="mt-4">
                            <button onclick="runBackup()" class="w-full bg-gray-800 text-white py-2 rounded-lg hover:bg-gray-900">
                                <i class="fas fa-database mr-2"></i>Run Backup Now
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Recent Activity -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-bold mb-4">Recent Activity</h3>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                            <tr class="bg-gray-50">
                                <th class="p-3 text-left text-sm font-semibold text-gray-600">User</th>
                                <th class="p-3 text-left text-sm font-semibold text-gray-600">Action</th>
                                <th class="p-3 text-left text-sm font-semibold text-gray-600">Amount</th>
                                <th class="p-3 text-left text-sm font-semibold text-gray-600">Time</th>
                                <th class="p-3 text-left text-sm font-semibold text-gray-600">Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $stmt = $db->prepare("SELECT t.*, u.username FROM transactions t 
                                                JOIN users u ON t.user_id = u.id 
                                                ORDER BY t.created_at DESC LIMIT 10");
                            $stmt->execute();
                            $activities = $stmt->fetchAll();
                            
                            foreach ($activities as $activity):
                            ?>
                            <tr class="border-b border-gray-100 hover:bg-gray-50">
                                <td class="p-3"><?php echo htmlspecialchars($activity['username']); ?></td>
                                <td class="p-3">
                                    <span class="px-2 py-1 text-xs rounded <?php 
                                        echo $activity['type'] == 'deposit' ? 'bg-green-100 text-green-800' : 
                                            ($activity['type'] == 'withdrawal' ? 'bg-red-100 text-red-800' : 
                                            'bg-blue-100 text-blue-800'); 
                                    ?>">
                                        <?php echo ucfirst($activity['type']); ?>
                                    </span>
                                </td>
                                <td class="p-3 font-semibold">$<?php echo number_format($activity['amount'], 2); ?></td>
                                <td class="p-3 text-sm text-gray-600">
                                    <?php echo date('M d, H:i', strtotime($activity['created_at'])); ?>
                                </td>
                                <td class="p-3">
                                    <span class="px-2 py-1 text-xs rounded <?php 
                                        echo $activity['status'] == 'completed' ? 'bg-green-100 text-green-800' : 
                                            ($activity['status'] == 'pending' ? 'bg-yellow-100 text-yellow-800' : 
                                            'bg-red-100 text-red-800'); 
                                    ?>">
                                        <?php echo ucfirst($activity['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Mobile sidebar toggle
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('hidden');
        });

        // Mobile sidebar close
        document.getElementById('sidebarClose').addEventListener('click', function() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.add('hidden');
        });

        function refreshStats() {
            location.reload();
        }
        
        function runBackup() {
            if (confirm('Are you sure you want to run a database backup?')) {
                // AJAX call to backup script
                fetch('../api/admin_backup.php')
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showNotification('Backup completed successfully!', 'success');
                        } else {
                            showNotification('Backup failed: ' + data.message, 'error');
                        }
                    })
                    .catch(error => {
                        showNotification('Backup failed: ' + error, 'error');
                    });
            }
        }
    </script>
</body>
</html>