<?php
/**
 * Researcher Recommendations - Phase 7
 * OBGYN Research & Collaboration Platform
 */

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

requireLogin();
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'Researcher Recommendations';
$userId = getCurrentUserId();

// Get researcher recommendations
$db = getDB();
$stmt = $db->prepare("
    SELECT rr.*, u.first_name, u.last_name, u.email, u.institution, u.specialization,
           u.profile_picture, u.created_at as user_created_at,
           COUNT(DISTINCT s.id) as study_count,
           COUNT(DISTINCT f.follower_id) as follower_count
    FROM researcher_recommendations rr
    JOIN users u ON rr.recommended_user_id = u.id
    LEFT JOIN studies s ON u.id = s.creator_id AND s.is_public = 1
    LEFT JOIN followers f ON u.id = f.following_id
    WHERE rr.user_id = ?
    GROUP BY u.id
    ORDER BY rr.score DESC, rr.created_at DESC
    LIMIT 20
");
$stmt->execute([$userId]);
$recommendations = $stmt->fetchAll();

// If no recommendations exist, generate some based on similar research interests
if (empty($recommendations)) {
    // Get current user's specialization
    $stmt = $db->prepare("SELECT specialization FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $userSpecialization = $stmt->fetchColumn();

    if ($userSpecialization) {
        // Find researchers with similar specializations
        $stmt = $db->prepare("
            SELECT u.id, u.first_name, u.last_name, u.email, u.institution, u.specialization,
                   u.profile_picture, u.created_at,
                   COUNT(DISTINCT s.id) as study_count,
                   COUNT(DISTINCT f.follower_id) as follower_count,
                   MATCH(u.specialization) AGAINST(? IN NATURAL LANGUAGE MODE) as relevance_score
            FROM users u
            LEFT JOIN studies s ON u.id = s.creator_id AND s.is_public = 1
            LEFT JOIN followers f ON u.id = f.following_id
            WHERE u.id != ? AND u.role = 'researcher' AND u.status = 'active'
            AND u.id NOT IN (SELECT following_id FROM followers WHERE follower_id = ?)
            AND MATCH(u.specialization) AGAINST(? IN NATURAL LANGUAGE MODE)
            GROUP BY u.id
            ORDER BY relevance_score DESC, follower_count DESC
            LIMIT 10
        ");
        $stmt->execute([$userSpecialization, $userId, $userId, $userSpecialization]);
        $similarResearchers = $stmt->fetchAll();

        // Insert recommendations
        foreach ($similarResearchers as $researcher) {
            $score = min(5.0, $researcher['relevance_score'] * 2); // Scale score
            $stmt = $db->prepare("
                INSERT IGNORE INTO researcher_recommendations (user_id, recommended_user_id, reason, score)
                VALUES (?, ?, 'Similar research interests', ?)
            ");
            $stmt->execute([$userId, $researcher['id'], $score]);
        }

        // Re-fetch recommendations
        $stmt = $db->prepare("
            SELECT rr.*, u.first_name, u.last_name, u.email, u.institution, u.specialization,
                   u.profile_picture, u.created_at as user_created_at,
                   COUNT(DISTINCT s.id) as study_count,
                   COUNT(DISTINCT f.follower_id) as follower_count
            FROM researcher_recommendations rr
            JOIN users u ON rr.recommended_user_id = u.id
            LEFT JOIN studies s ON u.id = s.creator_id AND s.is_public = 1
            LEFT JOIN followers f ON u.id = f.following_id
            WHERE rr.user_id = ?
            GROUP BY u.id
            ORDER BY rr.score DESC, rr.created_at DESC
            LIMIT 20
        ");
        $stmt->execute([$userId]);
        $recommendations = $stmt->fetchAll();
    }
}

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

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

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <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-lightbulb"></i> Researcher Recommendations</h1>
                <button type="button" class="btn btn-outline-primary" onclick="refreshRecommendations()">
                    <i class="fas fa-sync-alt"></i> Refresh
                </button>
            </div>

            <div class="alert alert-info alert-dismissible fade show" role="alert">
                <i class="fas fa-info-circle"></i>
                These recommendations are based on your research interests, collaborations, and network activity.
                Connect with researchers who share similar research focus areas!
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>

            <!-- Recommendations -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-users"></i> Recommended Researchers (<?php echo count($recommendations); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($recommendations)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-search fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No Recommendations Yet</h5>
                            <p class="text-muted">We're analyzing your profile to find relevant researchers. Check back soon!</p>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($recommendations as $rec): ?>
                                <div class="col-md-6 col-lg-4 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-2">
                                                <img src="<?php echo getProfilePictureUrl($rec['profile_picture']); ?>"
                                                     class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-0"><?php echo e($rec['first_name'] . ' ' . $rec['last_name']); ?></h6>
                                                    <small class="text-muted"><?php echo e($rec['institution']); ?></small>
                                                </div>
                                                <div class="text-end">
                                                    <small class="text-muted d-block">Match</small>
                                                    <span class="badge bg-success"><?php echo number_format($rec['score'], 1); ?>/5</span>
                                                </div>
                                            </div>
                                            <p class="small text-muted mb-2"><?php echo e($rec['specialization']); ?></p>
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <small class="text-muted">
                                                    <i class="fas fa-flask"></i> <?php echo $rec['study_count']; ?> studies
                                                </small>
                                                <small class="text-muted">
                                                    <i class="fas fa-users"></i> <?php echo $rec['follower_count']; ?> followers
                                                </small>
                                            </div>
                                            <?php if ($rec['reason']): ?>
                                                <p class="small text-primary mb-2">
                                                    <i class="fas fa-star"></i> <?php echo e($rec['reason']); ?>
                                                </p>
                                            <?php endif; ?>
                                            <div class="d-flex gap-2">
                                                <a href="../public/researcher-profile.php?id=<?php echo $rec['recommended_user_id']; ?>"
                                                   class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-eye"></i> View Profile
                                                </a>
                                                <button type="button" class="btn btn-sm btn-success"
                                                        onclick="followResearcher(<?php echo $rec['recommended_user_id']; ?>)">
                                                    <i class="fas fa-user-plus"></i> Follow
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- How Recommendations Work -->
            <div class="card mt-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-question-circle"></i> How Recommendations Work</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <div class="text-center">
                                <i class="fas fa-microscope fa-2x text-primary mb-2"></i>
                                <h6>Research Interests</h6>
                                <p class="small text-muted">Based on your specialization and research focus areas</p>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="text-center">
                                <i class="fas fa-users fa-2x text-success mb-2"></i>
                                <h6>Network Activity</h6>
                                <p class="small text-muted">Researchers your connections are following</p>
                            </div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="text-center">
                                <i class="fas fa-chart-line fa-2x text-info mb-2"></i>
                                <h6>Collaboration Patterns</h6>
                                <p class="small text-muted">Similar collaboration and publication patterns</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
function followResearcher(userId) {
    if (!confirm('Follow this researcher to see their updates and connect for collaboration?')) {
        return;
    }

    // Use the existing follow functionality
    fetch('/obgyn-research-platform/api/follow.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            action: 'follow',
            user_id: userId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Successfully followed the researcher!');
            location.reload();
        } else {
            alert('Error: ' + (data.error || 'Failed to follow researcher'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
    });
}

function refreshRecommendations() {
    if (!confirm('Refresh recommendations? This will update the list based on your latest activity.')) {
        return;
    }

    // Clear existing recommendations for this user
    fetch('/obgyn-research-platform/api/recommendations.php?action=refresh', {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error refreshing recommendations');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred. Please try again.');
    });
}
</script>

<?php include '../templates/researcher-mobile-footer.php'; ?>
</body>
</html>
