<?php
/**
 * Follow Researchers - Phase 7
 * OBGYN Research & Collaboration Platform
 */

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

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

$pageTitle = 'Follow Researchers';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Handle follow/unfollow actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();

    $action = $_POST['action'] ?? '';
    $targetId = (int)($_POST['user_id'] ?? 0);

    if ($action === 'follow' && $targetId > 0 && $targetId !== $userId) {
        try {
            $db = getDB();
            $stmt = $db->prepare("INSERT IGNORE INTO followers (follower_id, following_id) VALUES (?, ?)");
            $stmt->execute([$userId, $targetId]);
            $success = 'You are now following this researcher.';
        } catch (Exception $e) {
            $error = 'Failed to follow researcher.';
        }
    } elseif ($action === 'unfollow' && $targetId > 0) {
        try {
            $db = getDB();
            $stmt = $db->prepare("DELETE FROM followers WHERE follower_id = ? AND following_id = ?");
            $stmt->execute([$userId, $targetId]);
            $success = 'You have unfollowed this researcher.';
        } catch (Exception $e) {
            $error = 'Failed to unfollow researcher.';
        }
    }
}

// Get researchers to follow (excluding current user and already followed)
$db = getDB();
$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 f2.follower_id) as follower_count
    FROM users u
    LEFT JOIN studies s ON u.id = s.creator_id AND s.is_public = 1
    LEFT JOIN followers f2 ON u.id = f2.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 = ?)
    GROUP BY u.id
    ORDER BY follower_count DESC, u.created_at DESC
    LIMIT 50
");
$stmt->execute([$userId, $userId]);
$researchers = $stmt->fetchAll();

// Get following list
$stmt = $db->prepare("
    SELECT u.id, u.first_name, u.last_name, u.email, u.institution, u.specialization,
           u.profile_picture, f.created_at as followed_at,
           COUNT(DISTINCT s.id) as study_count
    FROM followers f
    JOIN users u ON f.following_id = u.id
    LEFT JOIN studies s ON u.id = s.creator_id AND s.is_public = 1
    WHERE f.follower_id = ?
    GROUP BY u.id
    ORDER BY f.created_at DESC
");
$stmt->execute([$userId]);
$following = $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-user-plus"></i> Follow Researchers</h1>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Following Tab -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-users"></i> Researchers You Follow (<?php echo count($following); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($following)): ?>
                        <p class="text-muted">You haven't followed any researchers yet. Browse the suggestions below to get started!</p>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($following as $researcher): ?>
                                <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($researcher['profile_picture']); ?>"
                                                     class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                                <div>
                                                    <h6 class="mb-0"><?php echo e($researcher['first_name'] . ' ' . $researcher['last_name']); ?></h6>
                                                    <small class="text-muted"><?php echo e($researcher['institution']); ?></small>
                                                </div>
                                            </div>
                                            <p class="small text-muted mb-2"><?php echo e($researcher['specialization']); ?></p>
                                            <div class="d-flex justify-content-between align-items-center">
                                                <small class="text-muted">
                                                    <i class="fas fa-flask"></i> <?php echo $researcher['study_count']; ?> studies
                                                </small>
                                                <form method="POST" class="d-inline">
                                                    <?php echo csrfField(); ?>
                                                    <input type="hidden" name="action" value="unfollow">
                                                    <input type="hidden" name="user_id" value="<?php echo $researcher['id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                                        <i class="fas fa-user-minus"></i> Unfollow
                                                    </button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Discover Tab -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-search"></i> Discover Researchers</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php foreach ($researchers as $researcher): ?>
                            <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($researcher['profile_picture']); ?>"
                                                 class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                            <div>
                                                <h6 class="mb-0"><?php echo e($researcher['first_name'] . ' ' . $researcher['last_name']); ?></h6>
                                                <small class="text-muted"><?php echo e($researcher['institution']); ?></small>
                                            </div>
                                        </div>
                                        <p class="small text-muted mb-2"><?php echo e($researcher['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 $researcher['study_count']; ?> studies
                                            </small>
                                            <small class="text-muted">
                                                <i class="fas fa-users"></i> <?php echo $researcher['follower_count']; ?> followers
                                            </small>
                                        </div>
                                        <form method="POST" class="d-inline">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="follow">
                                            <input type="hidden" name="user_id" value="<?php echo $researcher['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-primary">
                                                <i class="fas fa-user-plus"></i> Follow
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

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