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

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

requireLogin();

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$userId = getCurrentUserId();

switch ($method) {
    case 'GET':
        // Get recommendations for current user
        $db = getDB();

        // Get user's research interests and connections
        $stmt = $db->prepare("
            SELECT institution_id, specialty
            FROM user_profiles
            WHERE user_id = ?
        ");
        $stmt->execute([$userId]);
        $userProfile = $stmt->fetch();

        // Find similar researchers
        $recommendations = [];

        if ($userProfile) {
            $stmt = $db->prepare("
                SELECT u.id, u.first_name, u.last_name, u.email,
                       up.institution_id, up.specialty,
                       COUNT(c.id) as common_connections
                FROM users u
                JOIN user_profiles up ON u.id = up.user_id
                LEFT JOIN connections c1 ON c1.user_id = ? AND c1.connected_user_id = u.id
                LEFT JOIN connections c2 ON c2.connected_user_id = ? AND c2.user_id = u.id
                LEFT JOIN connections c ON (c.user_id = c1.user_id AND c.connected_user_id = c1.connected_user_id) OR
                                         (c.user_id = c2.user_id AND c.connected_user_id = c2.connected_user_id)
                WHERE u.id != ?
                AND u.role = 'researcher'
                AND (up.institution_id = ? OR up.specialty = ?)
                GROUP BY u.id
                ORDER BY common_connections DESC, RAND()
                LIMIT 10
            ");
            $stmt->execute([
                $userId, $userId, $userId,
                $userProfile['institution_id'], $userProfile['specialty']
            ]);
            $recommendations = $stmt->fetchAll();
        }

        // Calculate recommendation scores
        foreach ($recommendations as &$rec) {
            $score = 50; // Base score

            // Same institution bonus
            if ($rec['institution_id'] == $userProfile['institution_id']) {
                $score += 20;
            }

            // Same specialty bonus
            if ($rec['specialty'] == $userProfile['specialty']) {
                $score += 15;
            }

            // Common connections bonus
            $score += min($rec['common_connections'] * 5, 15);

            $rec['score'] = $score;
            $rec['reason'] = generateRecommendationReason($rec, $userProfile);
        }

        // Store recommendations for caching
        foreach ($recommendations as $rec) {
            $stmt = $db->prepare("
                INSERT INTO researcher_recommendations (user_id, recommended_user_id, reason, score)
                VALUES (?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE reason = VALUES(reason), score = VALUES(score)
            ");
            $stmt->execute([$userId, $rec['id'], $rec['reason'], $rec['score']]);
        }

        echo json_encode([
            'success' => true,
            'recommendations' => $recommendations
        ]);
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}

function generateRecommendationReason($recommended, $user) {
    $reasons = [];

    if ($recommended['institution_id'] == $user['institution_id']) {
        $reasons[] = 'Same institution';
    }

    if ($recommended['specialty'] == $user['specialty']) {
        $reasons[] = 'Same specialty';
    }

    if ($recommended['common_connections'] > 0) {
        $reasons[] = $recommended['common_connections'] . ' mutual connection(s)';
    }

    return implode(', ', $reasons);
}
?>
