<?php
/**
 * Admin Dashboard
 * OBGYN Research & Collaboration Platform
 */

require_once '../config/config.php';

requireLogin();
if (!isSuperAdmin() && !isInstitutionAdmin()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Admin Dashboard';

// Get platform statistics
$db = getDB();

// User statistics
$stmt = $db->prepare("SELECT COUNT(*) FROM users");
$stmt->execute();
$totalUsers = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE status = 'active'");
$stmt->execute();
$activeUsers = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
$stmt->execute();
$newUsers = $stmt->fetchColumn();

// Study statistics
$stmt = $db->prepare("SELECT COUNT(*) FROM studies");
$stmt->execute();
$totalStudies = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM studies WHERE status = 'active'");
$stmt->execute();
$activeStudies = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM studies WHERE approval_status = 'pending'");
$stmt->execute();
$pendingStudies = $stmt->fetchColumn();

// Publication statistics
$stmt = $db->prepare("SELECT COUNT(*) FROM publications");
$stmt->execute();
$totalPublications = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM publications WHERE approval_status = 'pending'");
$stmt->execute();
$pendingPublications = $stmt->fetchColumn();

// Institution statistics
$stmt = $db->prepare("SELECT COUNT(*) FROM institutions");
$stmt->execute();
$totalInstitutions = $stmt->fetchColumn();

// Recent activities
$stmt = $db->prepare("
    SELECT * FROM audit_logs 
    ORDER BY created_at DESC 
    LIMIT 10
");
$stmt->execute();
$recentActivities = $stmt->fetchAll();

// Recent users
$stmt = $db->prepare("
    SELECT u.*, r.name as role_name
    FROM users u
    JOIN roles r ON u.role_id = r.id
    ORDER BY u.created_at DESC
    LIMIT 5
");
$stmt->execute();
$recentUsers = $stmt->fetchAll();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar-new.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4" style="margin-top: 56px;">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2"><i class="fas fa-tachometer-alt"></i> Admin Dashboard</h1>
                <div class="btn-toolbar">
                    <button class="btn btn-sm btn-outline-secondary" onclick="location.reload()">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="row mb-4">
                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-primary shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                        Total Users
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totalUsers); ?></div>
                                    <small class="text-success">
                                        <i class="fas fa-arrow-up"></i> <?php echo $newUsers; ?> new this month
                                    </small>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-users fa-2x text-gray-300"></i>
                                </div>
                            </div>
                            <a href="users.php" class="stretched-link"></a>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-success shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                        Studies
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totalStudies); ?></div>
                                    <small class="text-info">
                                        <?php echo $activeStudies; ?> active
                                    </small>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-flask fa-2x text-gray-300"></i>
                                </div>
                            </div>
                            <a href="studies.php" class="stretched-link"></a>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-info shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                        Publications
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totalPublications); ?></div>
                                    <?php if ($pendingPublications > 0): ?>
                                        <small class="text-warning">
                                            <i class="fas fa-clock"></i> <?php echo $pendingPublications; ?> pending
                                        </small>
                                    <?php endif; ?>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-book fa-2x text-gray-300"></i>
                                </div>
                            </div>
                            <a href="publications.php" class="stretched-link"></a>
                        </div>
                    </div>
                </div>

                <div class="col-xl-3 col-md-6 mb-4">
                    <div class="card border-left-warning shadow h-100 py-2">
                        <div class="card-body">
                            <div class="row no-gutters align-items-center">
                                <div class="col mr-2">
                                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                        Institutions
                                    </div>
                                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($totalInstitutions); ?></div>
                                </div>
                                <div class="col-auto">
                                    <i class="fas fa-university fa-2x text-gray-300"></i>
                                </div>
                            </div>
                            <a href="institutions.php" class="stretched-link"></a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Pending Actions -->
            <?php if ($pendingStudies > 0 || $pendingPublications > 0): ?>
            <div class="alert alert-warning shadow mb-4">
                <h5 class="alert-heading"><i class="fas fa-exclamation-triangle"></i> Pending Actions Required</h5>
                <hr>
                <div class="row">
                    <?php if ($pendingStudies > 0): ?>
                    <div class="col-md-6">
                        <p class="mb-2">
                            <strong><?php echo $pendingStudies; ?></strong> studies awaiting approval
                        </p>
                        <a href="studies.php?filter=pending" class="btn btn-sm btn-warning">
                            <i class="fas fa-eye"></i> Review Studies
                        </a>
                    </div>
                    <?php endif; ?>
                    <?php if ($pendingPublications > 0): ?>
                    <div class="col-md-6">
                        <p class="mb-2">
                            <strong><?php echo $pendingPublications; ?></strong> publications awaiting approval
                        </p>
                        <a href="publications.php?filter=pending" class="btn btn-sm btn-warning">
                            <i class="fas fa-eye"></i> Review Publications
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="row">
                <!-- Recent Users -->
                <div class="col-lg-6 mb-4">
                    <div class="card shadow">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-user-plus"></i> Recent Users
                            </h6>
                            <a href="users.php" class="btn btn-sm btn-outline-primary">View All</a>
                        </div>
                        <div class="card-body">
                            <?php if (empty($recentUsers)): ?>
                                <p class="text-muted text-center py-3">No users yet.</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>Name</th>
                                                <th>Email</th>
                                                <th>Role</th>
                                                <th>Status</th>
                                                <th>Joined</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($recentUsers as $user): ?>
                                            <tr>
                                                <td><?php echo e($user['first_name'] . ' ' . $user['last_name']); ?></td>
                                                <td><?php echo e($user['email']); ?></td>
                                                <td><span class="badge bg-info"><?php echo e($user['role_name']); ?></span></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $user['status'] === 'active' ? 'success' : 'warning'; ?>">
                                                        <?php echo ucfirst($user['status']); ?>
                                                    </span>
                                                </td>
                                                <td><?php echo date('M d', strtotime($user['created_at'])); ?></td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Recent Activities -->
                <div class="col-lg-6 mb-4">
                    <div class="card shadow">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h6 class="m-0 font-weight-bold text-primary">
                                <i class="fas fa-history"></i> Recent Activities
                            </h6>
                            <a href="audit-logs.php" class="btn btn-sm btn-outline-primary">View All</a>
                        </div>
                        <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                            <?php if (empty($recentActivities)): ?>
                                <p class="text-muted text-center py-3">No activities yet.</p>
                            <?php else: ?>
                                <div class="list-group list-group-flush">
                                    <?php foreach ($recentActivities as $activity): ?>
                                    <div class="list-group-item px-0">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1 small">
                                                <i class="fas fa-circle text-primary" style="font-size: 0.5rem;"></i>
                                                <?php echo e($activity['action']); ?>
                                            </h6>
                                            <small class="text-muted"><?php echo timeAgo($activity['created_at']); ?></small>
                                        </div>
                                        <p class="mb-1 small text-muted">
                                            <?php if ($activity['table_name']): ?>
                                                Table: <?php echo e($activity['table_name']); ?>
                                                <?php if ($activity['record_id']): ?>
                                                    (ID: <?php echo $activity['record_id']; ?>)
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card shadow mb-4">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-bolt"></i> Quick Actions
                    </h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <a href="users.php" class="btn btn-outline-primary w-100">
                                <i class="fas fa-users"></i><br>Manage Users
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="studies.php" class="btn btn-outline-success w-100">
                                <i class="fas fa-flask"></i><br>Manage Studies
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="institutions.php" class="btn btn-outline-info w-100">
                                <i class="fas fa-university"></i><br>Manage Institutions
                            </a>
                        </div>
                        <div class="col-md-3 mb-3">
                            <a href="settings.php" class="btn btn-outline-secondary w-100">
                                <i class="fas fa-cog"></i><br>Platform Settings
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<style>
.border-left-primary {
    border-left: 0.25rem solid #4e73df !important;
}

.border-left-success {
    border-left: 0.25rem solid #1cc88a !important;
}

.border-left-info {
    border-left: 0.25rem solid #36b9cc !important;
}

.border-left-warning {
    border-left: 0.25rem solid #f6c23e !important;
}
</style>

<?php include '../templates/admin-footer.php'; ?>
