<?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 = isset($_GET['ajax']) ? 5 : 0; // Load 0 initially, 5 via scroll
$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 = $perPage > 0 ? ceil($totalResearchers / $perPage) : 0;

$stmt = $db->prepare("
    SELECT u.id, u.first_name, u.last_name, u.email, u.created_at,
           rp.photo, rp.title, rp.specialization, rp.institution_id, rp.department, 
           rp.degrees, rp.bio, rp.research_interests, rp.orcid_id, rp.google_scholar,
           rp.researchgate, rp.linkedin, rp.phone, rp.phone_visible, rp.country, rp.city,
           rp.publications_count, rp.studies_count, rp.collaborations_count, rp.profile_views, rp.verified_badge,
           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,
           (SELECT COUNT(*) FROM followers WHERE following_id = u.id) as followers_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 RAND()
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);
$researchers = $stmt->fetchAll();

// Handle AJAX requests
if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    // Return only the researcher cards HTML
    foreach ($researchers as $researcher): 
        // Skip researchers without valid IDs
        if (empty($researcher['id'])) continue;
        
        // Check if current user is following this researcher
        $isFollowing = false;
        if (isLoggedIn()) {
            $currentUserId = getCurrentUserId();
            $stmt = $db->prepare("SELECT id FROM followers WHERE follower_id = ? AND following_id = ?");
            $stmt->execute([$currentUserId, $researcher['id']]);
            $isFollowing = $stmt->fetch() ? true : false;
        }
    ?>
        <div class="col-md-6 col-lg-4 researcher-card">
            <div class="card h-100 shadow-sm">
                <div class="card-body text-center">
                    <?php 
                    $photoUrl = getProfilePictureUrl($researcher['photo']);
                    $photoExists = $researcher['photo'] && file_exists('../assets/uploads/profile_pictures/' . basename($researcher['photo']));
                    ?>
                    <?php if ($researcher['photo'] && $photoExists): ?>
                        <img src="<?php echo $photoUrl; ?>" 
                             alt="Profile Photo" 
                             class="rounded-circle mb-3" 
                             style="width: 80px; height: 80px; object-fit: cover;">
                    <?php else: ?>
                        <div class="avatar-circle mx-auto mb-3" style="width: 80px; height: 80px; font-size: 24px;">
                            <?php echo strtoupper(substr($researcher['first_name'], 0, 2)); ?>
                        </div>
                    <?php endif; ?>
                    <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['followers_count']; ?></strong>
                            <small class="d-block text-muted">Followers</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">
                    <?php if (isLoggedIn() && getCurrentUserId() != $researcher['id']): ?>
                        <button class="btn btn-sm <?php echo $isFollowing ? 'btn-outline-secondary' : 'btn-primary'; ?> w-100 mb-2" onclick="toggleFollow(<?php echo $researcher['id']; ?>, this)">
                            <i class="fas <?php echo $isFollowing ? 'fa-user-minus' : 'fa-user-plus'; ?>"></i>
                            <?php echo $isFollowing ? 'Unfollow' : 'Follow'; ?>
                        </button>
                    <?php endif; ?>
                    <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;
    exit;
}

// 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" id="researchers-container">
        <?php foreach ($researchers as $researcher): 
            // Skip researchers without valid IDs
            if (empty($researcher['id'])) continue;
            
            // Check if current user is following this researcher
            $isFollowing = false;
            if (isLoggedIn()) {
                $currentUserId = getCurrentUserId();
                $stmt = $db->prepare("SELECT id FROM followers WHERE follower_id = ? AND following_id = ?");
                $stmt->execute([$currentUserId, $researcher['id']]);
                $isFollowing = $stmt->fetch() ? true : false;
            }
        ?>
        <div class="col-md-6 col-lg-4 researcher-card">
            <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['followers_count']; ?></strong>
                            <small class="d-block text-muted">Followers</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">
                    <?php if (isLoggedIn() && getCurrentUserId() != $researcher['id']): ?>
                        <button class="btn btn-sm <?php echo $isFollowing ? 'btn-outline-secondary' : 'btn-primary'; ?> w-100 mb-2" onclick="toggleFollow(<?php echo $researcher['id']; ?>, this)">
                            <i class="fas <?php echo $isFollowing ? 'fa-user-minus' : 'fa-user-plus'; ?>"></i>
                            <?php echo $isFollowing ? 'Unfollow' : 'Follow'; ?>
                        </button>
                    <?php endif; ?>
                    <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>
    
    <!-- Skeleton loading placeholders -->
    <div id="skeleton-container" class="row g-4" style="display: none;">
        <?php for ($i = 0; $i < 5; $i++): ?>
        <div class="col-md-6 col-lg-4">
            <div class="card h-100 shadow-sm">
                <div class="card-body text-center">
                    <div class="skeleton-avatar mx-auto mb-3"></div>
                    <div class="skeleton-title mb-2"></div>
                    <div class="skeleton-text mb-1"></div>
                    <div class="skeleton-text mb-3"></div>
                    <div class="d-flex justify-content-around mt-3">
                        <div class="text-center">
                            <div class="skeleton-number"></div>
                            <div class="skeleton-label"></div>
                        </div>
                        <div class="text-center">
                            <div class="skeleton-number"></div>
                            <div class="skeleton-label"></div>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent">
                    <div class="skeleton-button"></div>
                </div>
            </div>
        </div>
        <?php endfor; ?>
    </div>
    
    <!-- Loading indicator -->
    <div id="loading-indicator" class="text-center py-4" style="display: none;">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
        <p class="text-muted mt-2">Loading more researchers...</p>
    </div>
</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;
}

/* Skeleton loading styles */
.skeleton-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
}

.skeleton-title {
    height: 24px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 4px;
}

.skeleton-text {
    height: 16px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 4px;
    margin-bottom: 8px;
}

.skeleton-number {
    height: 20px;
    width: 30px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 4px;
    margin: 0 auto;
}

.skeleton-label {
    height: 12px;
    width: 50px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 4px;
    margin: 4px auto 0;
}

.skeleton-button {
    height: 38px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s infinite;
    border-radius: 4px;
}

@keyframes skeleton-loading {
    0% {
        background-position: -200% 0;
    }
    100% {
        background-position: 200% 0;
    }
}
</style>

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

<script>
let currentPage = 0;
let isLoading = false;
let hasMoreData = true;
const searchParams = new URLSearchParams(window.location.search);

function showSkeleton() {
    document.getElementById('skeleton-container').style.display = 'flex';
}

function hideSkeleton() {
    document.getElementById('skeleton-container').style.display = 'none';
}

function showLoadingIndicator() {
    document.getElementById('loading-indicator').style.display = 'block';
}

function hideLoadingIndicator() {
    document.getElementById('loading-indicator').style.display = 'none';
}

async function loadMoreResearchers() {
    if (isLoading || !hasMoreData) return;
    
    isLoading = true;
    showSkeleton();
    
    try {
        const params = new URLSearchParams({
            page: currentPage + 1,
            search: searchParams.get('search') || '',
            specialty: searchParams.get('specialty') || ''
        });
        
        const response = await fetch(`researchers.php?${params}&ajax=1`);
        const html = await response.text();
        
        if (html.trim() === '') {
            hasMoreData = false;
            return;
        }
        
        // Parse the HTML and extract researcher cards
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const newCards = doc.querySelectorAll('.researcher-card');
        
        if (newCards.length === 0) {
            hasMoreData = false;
            return;
        }
        
        const container = document.getElementById('researchers-container');
        newCards.forEach(card => {
            container.appendChild(card);
        });
        
        currentPage++;
        
    } catch (error) {
        console.error('Error loading more researchers:', error);
        hasMoreData = false;
    } finally {
        isLoading = false;
        hideSkeleton();
    }
}

// Infinite scroll detection
function handleScroll() {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;
    
    // Load more when user is within 200px of the bottom
    if (documentHeight - (scrollTop + windowHeight) < 200) {
        loadMoreResearchers();
    }
}

// Throttle scroll events
let scrollTimeout;
function throttledScroll() {
    clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(handleScroll, 100);
}

// Initialize infinite scroll
window.addEventListener('scroll', throttledScroll);

// Also load more when user reaches the bottom (backup for scroll detection)
window.addEventListener('scroll', () => {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100) {
        loadMoreResearchers();
    }
});

// Load first batch on page load
window.addEventListener('load', () => {
    setTimeout(() => {
        loadMoreResearchers();
    }, 100); // Small delay to ensure everything is ready
});

async function toggleFollow(targetUserId, buttonElement) {
    const btn = buttonElement || document.querySelector(`button[onclick*="toggleFollow(${targetUserId}"]`);
    const icon = btn.querySelector('i');
    const text = btn.querySelector('i').nextSibling;
    
    // Disable button during request
    btn.disabled = true;
    const wasFollowing = btn.classList.contains('btn-outline-secondary');
    
    try {
        let response;
        let result;
        
        if (wasFollowing) {
            // Unfollow
            response = await fetch('<?php echo SITE_URL; ?>/api/follow.php?user_id=' + targetUserId, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
        } else {
            // Follow
            const formData = new FormData();
            formData.append('user_id', targetUserId);
            
            response = await fetch('<?php echo SITE_URL; ?>/api/follow.php', {
                method: 'POST',
                body: formData
            });
        }
        
        result = await response.json();
        
        if (result.success) {
            if (wasFollowing) {
                // Successfully unfollowed
                btn.classList.remove('btn-outline-secondary');
                btn.classList.add('btn-primary');
                icon.className = 'fas fa-user-plus';
                text.textContent = ' Follow';
            } else {
                // Successfully followed
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-secondary');
                icon.className = 'fas fa-user-minus';
                text.textContent = ' Unfollow';
            }
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Follow/Unfollow error:', error);
        alert('An error occurred. Please try again.');
    } finally {
        btn.disabled = false;
    }
}
</script>
