<?php
require_once '../config/config.php';

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);
$pageTitle = 'Browse Researchers';

$search = $_GET['search'] ?? '';
$specialty = $_GET['specialty'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 12;
$offset = ($page - 1) * $perPage;

$db = getDB();
$where = ["u.role_id = " . ROLE_RESEARCHER, "u.status = 'active'"];
$params = [];

if (!empty($search)) {
    $where[] = "(u.first_name LIKE ? OR u.last_name LIKE ? OR rp.bio LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($specialty)) {
    $where[] = "rp.specialization LIKE ?";
    $params[] = "%$specialty%";
}

$whereClause = implode(' AND ', $where);

$stmt = $db->prepare("SELECT COUNT(*) FROM users u LEFT JOIN researcher_profiles rp ON u.id = rp.user_id WHERE $whereClause");
$stmt->execute($params);
$totalResearchers = $stmt->fetchColumn();
$totalPages = ceil($totalResearchers / $perPage);

$stmt = $db->prepare("
    SELECT u.*, rp.*, i.name as institution_name,
           (SELECT COUNT(*) FROM studies WHERE creator_id = u.id) as studies_count,
           (SELECT COUNT(*) FROM publications WHERE user_id = u.id) as publications_count
    FROM users u
    LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
    LEFT JOIN institutions i ON rp.institution_id = i.id
    WHERE $whereClause
    ORDER BY u.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$researchers = $stmt->fetchAll();

// Include appropriate header based on device
if ($isMobile) {
    include '../templates/mobile-header.php';
} else {
    include '../templates/header.php';
}
?>

<div class="container my-5">
    <h2 class="mb-4"><i class="fas fa-user-md"></i> Browse Researchers</h2>
    
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-5">
                    <input type="text" class="form-control" name="search" value="<?php echo e($search); ?>" placeholder="Search by name or bio...">
                </div>
                <div class="col-md-3">
                    <input type="text" class="form-control" name="specialty" value="<?php echo e($specialty); ?>" placeholder="Specialty...">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> Search</button>
                </div>
                <div class="col-md-2">
                    <a href="researchers.php" class="btn btn-outline-secondary w-100"><i class="fas fa-redo"></i> Reset</a>
                </div>
            </form>
        </div>
    </div>
    
    <p class="text-muted mb-4">Found <?php echo number_format($totalResearchers); ?> researchers</p>
    
    <div class="row g-4">
        <?php foreach ($researchers as $researcher): ?>
        <div class="col-md-6 col-lg-4">
            <div class="card h-100 shadow-sm">
                <div class="card-body text-center">
                    <div class="avatar-circle mx-auto mb-3" style="width: 80px; height: 80px; font-size: 32px;">
                        <?php echo strtoupper(substr($researcher['first_name'], 0, 1) . substr($researcher['last_name'], 0, 1)); ?>
                    </div>
                    <h5 class="card-title">
                        <a href="researcher-profile.php?id=<?php echo $researcher['id']; ?>" class="text-decoration-none">
                            <?php echo e($researcher['first_name'] . ' ' . $researcher['last_name']); ?>
                        </a>
                    </h5>
                    <?php if ($researcher['specialization']): ?>
                        <p class="text-muted small"><?php echo e($researcher['specialization']); ?></p>
                    <?php endif; ?>
                    <?php if ($researcher['institution_name']): ?>
                        <p class="text-muted small"><i class="fas fa-university"></i> <?php echo e($researcher['institution_name']); ?></p>
                    <?php endif; ?>
                    <div class="d-flex justify-content-around mt-3">
                        <div>
                            <strong><?php echo $researcher['studies_count']; ?></strong>
                            <small class="d-block text-muted">Studies</small>
                        </div>
                        <div>
                            <strong><?php echo $researcher['publications_count']; ?></strong>
                            <small class="d-block text-muted">Publications</small>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent">
                    <a href="researcher-profile.php?id=<?php echo $researcher['id']; ?>" class="btn btn-sm btn-outline-primary w-100">
                        <i class="fas fa-eye"></i> View Profile
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
    <?php if ($totalPages > 1): ?>
    <nav class="mt-4">
        <ul class="pagination justify-content-center">
            <?php for ($i = 1; $i <= min($totalPages, 10); $i++): ?>
            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&specialty=<?php echo urlencode($specialty); ?>">
                    <?php echo $i; ?>
                </a>
            </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<style>
.avatar-circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}
</style>

<?php // Include appropriate footer based on device
if ($isMobile) {
    include '../templates/mobile-footer.php';
} else {
    include '../templates/footer.php';
} ?>
