<?php
/**
 * Researcher Profile View
 * OBGYN Research & Collaboration Platform
 */

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

// Check if user is logged in
requireLogin();

// Check if user is a researcher
if (!isResearcher()) {
    redirect(SITE_URL . '/index.php');
}

$pageTitle = 'My Profile';
$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);
$userId = getCurrentUserId();

// Get researcher profile with all details
$db = getDB();
$stmt = $db->prepare("
    SELECT rp.*, u.first_name, u.last_name, u.email, u.created_at as member_since,
           i.name as institution_name, i.type as institution_type, i.country as institution_country
    FROM researcher_profiles rp
    JOIN users u ON rp.user_id = u.id
    LEFT JOIN institutions i ON rp.institution_id = i.id
    WHERE rp.user_id = ?
");
$stmt->execute([$userId]);
$profile = $stmt->fetch();

// Get user's studies
$stmt = $db->prepare("
    SELECT s.*, 
           (SELECT COUNT(*) FROM study_collaborators WHERE study_id = s.id AND status = 'active') as collaborators_count
    FROM studies s
    WHERE s.creator_id = ? AND s.status != 'archived'
    ORDER BY s.created_at DESC
    LIMIT 10
");
$stmt->execute([$userId]);
$studies = $stmt->fetchAll();

// Get user's publications
$stmt = $db->prepare("
    SELECT * FROM publications 
    WHERE user_id = ? AND status = 'published'
    ORDER BY publication_date DESC
    LIMIT 10
");
$stmt->execute([$userId]);
$publications = $stmt->fetchAll();

// Get connections count
$stmt = $db->prepare("
    SELECT COUNT(*) FROM connections 
    WHERE (requester_id = ? OR receiver_id = ?) AND status = 'accepted'
");
$stmt->execute([$userId, $userId]);
$connectionsCount = $stmt->fetchColumn();

if ($isMobile) {
    include '../templates/researcher-mobile-header.php';
} else {
    include '../templates/researcher-header.php';
}
?>

<div class="researcher-dashboard-wrapper">
  <div class="researcher-layout">
    <!-- LEFT COLUMN: Fixed, non-scrolling -->
    <aside class="profile-sidebar">
      <div class="profile-card shadow-sm">
        <div class="card-body text-center">
          <!-- Photo -->
          <div class="profile-photo-container mb-3">
            <?php if ($profile['photo']): ?>
              <img src="<?php echo getProfilePictureUrl($profile['photo']); ?>" 
                   alt="Profile" class="profile-photo">
            <?php else: ?>
              <div class="profile-avatar">
                <?php echo strtoupper(substr($profile['first_name'], 0, 1) . substr($profile['last_name'], 0, 1)); ?>
              </div>
            <?php endif; ?>
          </div>

          <!-- Name & Title -->
          <h4 class="name-text">
            <?php echo e($profile['first_name'] . ' ' . $profile['last_name']); ?>
            <?php if ($profile['verified_badge']): ?>
              <i class="fas fa-check-circle text-success ms-1" title="Verified Researcher"></i>
            <?php endif; ?>
          </h4>
          <?php if ($profile['title']): ?>
            <p class="title-text mb-1"><?php echo e($profile['title']); ?></p>
          <?php endif; ?>
          <?php if ($profile['specialization']): ?>
            <p class="specialization-text mb-2"><?php echo e($profile['specialization']); ?></p>
          <?php endif; ?>

          <!-- Institution -->
          <?php if ($profile['institution_name']): ?>
            <div class="institution-text mb-2">
              <strong><?php echo e($profile['institution_name']); ?></strong>
              <?php if ($profile['department']): ?>
                <br><small class="text-muted"><?php echo e($profile['department']); ?></small>
              <?php endif; ?>
            </div>
          <?php endif; ?>

          <!-- Location -->
          <?php if ($profile['country']): ?>
            <div class="location-text mb-3">
              <i class="fas fa-map-marker-alt text-muted me-1"></i>
              <span><?php echo e($profile['city'] ? $profile['city'] . ', ' : ''); ?><?php echo e($profile['country']); ?></span>
            </div>
          <?php endif; ?>

          <!-- Stats -->
          <div class="stats-row mb-3">
            <div class="stat-item">
              <div class="stat-value"><?php echo $profile['studies_count']; ?></div>
              <div class="stat-label">Studies</div>
            </div>
            <div class="stat-item">
              <div class="stat-value"><?php echo $profile['publications_count']; ?></div>
              <div class="stat-label">Publications</div>
            </div>
            <div class="stat-item">
              <div class="stat-value"><?php echo $connectionsCount; ?></div>
              <div class="stat-label">Connections</div>
            </div>
          </div>

          <!-- Social -->
          <?php if ($profile['orcid_id'] || $profile['google_scholar'] || $profile['researchgate'] || $profile['linkedin']): ?>
            <div class="social-links mb-3">
              <?php if ($profile['orcid_id']): ?>
                <a href="https://orcid.org/<?php echo e($profile['orcid_id']); ?>" target="_blank" class="social-icon orcid"><i class="fab fa-orcid"></i></a>
              <?php endif; ?>
              <?php if ($profile['google_scholar']): ?>
                <a href="<?php echo e($profile['google_scholar']); ?>" target="_blank" class="social-icon scholar"><i class="fas fa-graduation-cap"></i></a>
              <?php endif; ?>
              <?php if ($profile['researchgate']): ?>
                <a href="<?php echo e($profile['researchgate']); ?>" target="_blank" class="social-icon rg"><i class="fab fa-researchgate"></i></a>
              <?php endif; ?>
              <?php if ($profile['linkedin']): ?>
                <a href="<?php echo e($profile['linkedin']); ?>" target="_blank" class="social-icon li"><i class="fab fa-linkedin-in"></i></a>
              <?php endif; ?>
            </div>
          <?php endif; ?>

          <!-- Contact Info -->
          <div class="contact-section">
            <div class="contact-item mb-2">
              <i class="fas fa-envelope text-muted me-2"></i> <?php echo e($profile['email']); ?>
            </div>
            <?php if ($profile['phone'] && $profile['phone_visible']): ?>
              <div class="contact-item mb-2">
                <i class="fas fa-phone text-muted me-2"></i> <?php echo e($profile['phone']); ?>
              </div>
            <?php endif; ?>
            <div class="contact-item">
              <i class="fas fa-calendar text-muted me-2"></i> Member since <?php echo date('F Y', strtotime($profile['member_since'])); ?>
            </div>
          </div>
        </div>
      </div>
    </aside>

    <!-- RIGHT COLUMN: Scrollable content -->
    <main class="profile-content">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="h4 mb-0"><i class="fas fa-user me-2"></i>My Profile</h2>
        <a href="edit-profile.php" class="btn btn-sm btn-primary">
          <i class="fas fa-edit me-1"></i> Edit Profile
        </a>
      </div>

      <?php if ($profile['bio']): ?>
        <div class="content-card">
          <h5 class="card-title"><i class="fas fa-user-circle me-2"></i>About</h5>
          <p class="card-text"><?php echo nl2br(e($profile['bio'])); ?></p>
        </div>
      <?php endif; ?>

      <?php if ($profile['research_interests']): ?>
        <div class="content-card">
          <h5 class="card-title"><i class="fas fa-lightbulb me-2"></i>Research Interests</h5>
          <p class="card-text"><?php echo nl2br(e($profile['research_interests'])); ?></p>
        </div>
      <?php endif; ?>

      <?php if ($profile['degrees']): ?>
        <div class="content-card">
          <h5 class="card-title"><i class="fas fa-graduation-cap me-2"></i>Education</h5>
          <p class="card-text"><?php echo nl2br(e($profile['degrees'])); ?></p>
        </div>
      <?php endif; ?>

      <div class="content-card">
        <div class="d-flex justify-content-between align-items-center">
          <h5 class="card-title mb-0"><i class="fas fa-flask me-2"></i>Research Studies</h5>
          <a href="studies.php" class="text-primary small"><i class="fas fa-arrow-right me-1"></i>View All</a>
        </div>
        <?php if (empty($studies)): ?>
          <p class="text-muted mt-2">No studies yet.</p>
        <?php else: ?>
          <div class="list-group list-group-flush mt-2">
            <?php foreach ($studies as $study): ?>
              <div class="list-group-item py-2">
                <div class="d-flex justify-content-between">
                  <a href="edit-study.php?id=<?php echo $study['id']; ?>" class="study-title"><?php echo e($study['title']); ?></a>
                  <small class="text-muted"><?php echo date('M Y', strtotime($study['created_at'])); ?></small>
                </div>
                <p class="text-muted small mt-1"><?php echo e(substr($study['summary'] ?? 'No summary', 0, 120)) . '...'; ?></p>
                <div class="d-flex gap-2 mt-1">
                  <span class="badge bg-primary"><?php echo ucfirst($study['type']); ?></span>
                  <span class="badge bg-info"><?php echo ucfirst($study['status']); ?></span>
                  <?php if ($study['collaborators_count'] > 0): ?>
                    <span class="badge bg-success"><i class="fas fa-users me-1"></i><?php echo $study['collaborators_count']; ?></span>
                  <?php endif; ?>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>

      <div class="content-card">
        <h5 class="card-title"><i class="fas fa-book me-2"></i>Publications</h5>
        <?php if (empty($publications)): ?>
          <p class="text-muted">No publications yet.</p>
        <?php else: ?>
          <div class="publications-list">
            <?php foreach ($publications as $pub): ?>
              <div class="publication-item">
                <h6 class="publication-title"><?php echo e($pub['title']); ?></h6>
                <p class="text-muted small"><?php echo e($pub['authors']); ?></p>
                <p class="text-muted small">
                  <?php if ($pub['journal']): ?><em><?php echo e($pub['journal']); ?></em><?php endif; ?>
                  <?php if ($pub['publication_date']): ?>(<?php echo date('Y', strtotime($pub['publication_date'])); ?>)<?php endif; ?>
                </p>
                <?php if ($pub['doi']): ?>
                  <p class="small">
                    <strong>DOI:</strong> <a href="https://doi.org/<?php echo e($pub['doi']); ?>" target="_blank" class="text-primary"><?php echo e($pub['doi']); ?></a>
                  </p>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </main>
  </div>
</div>

<style>
.researcher-dashboard-wrapper {
  background-color: #f9fafc;
  min-height: 100vh;
  padding: 1.5rem 0;
}
.researcher-layout {
  display: flex;
  gap: 1.5rem;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 1rem;
  width: 100%;
}
.profile-sidebar {
  flex: 0 0 360px;
  position: sticky;
  top: 1.5rem;
  height: fit-content;
}
.profile-card {
  border-radius: 12px;
  background: white;
  border: 1px solid #eaeef5;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.profile-photo-container {
  margin-bottom: 1rem;
}
.profile-photo {
  width: 110px;
  height: 110px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.profile-avatar {
  width: 110px;
  height: 110px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4f6df5, #8a5cff);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 1.8rem;
  border: 3px solid #fff;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.name-text {
  font-weight: 600;
  font-size: 1.25rem;
  color: #2d3748;
  margin-bottom: 0.25rem;
}
.title-text {
  color: #4a5568;
  font-weight: 500;
  font-size: 0.95rem;
}
.specialization-text {
  color: #6b7280;
  font-size: 0.9rem;
}
.institution-text,
.location-text {
  font-size: 0.9rem;
  color: #4a5568;
}
.stats-row {
  display: flex;
  justify-content: space-around;
  margin: 1rem 0;
  padding: 0.5rem 0;
  border-top: 1px solid #edf2f7;
  border-bottom: 1px solid #edf2f7;
}
.stat-item {
  text-align: center;
}
.stat-value {
  font-weight: 700;
  font-size: 1.1rem;
  color: #4f6df5;
}
.stat-label {
  font-size: 0.75rem;
  color: #718096;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}
.social-links {
  display: flex;
  justify-content: center;
  gap: 0.75rem;
  margin: 0.5rem 0;
}
.social-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  color: white;
  text-decoration: none;
  font-size: 0.9rem;
}
.social-icon.orcid { background: #a6ce39; }
.social-icon.scholar { background: #4285f4; }
.social-icon.rg { background: #00ccbb; }
.social-icon.li { background: #0077b5; }
.contact-section {
  padding-top: 0.5rem;
  border-top: 1px solid #edf2f7;
}
.contact-item {
  font-size: 0.95rem;
  color: #4a5568;
  margin-bottom: 0.25rem;
}
.profile-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 1.25rem;
}
.content-card {
  background: white;
  border-radius: 12px;
  padding: 1.25rem;
  border: 1px solid #eaeef5;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.card-title {
  font-weight: 600;
  color: #2d3748;
  margin-bottom: 0.75rem;
  font-size: 1.15rem;
}
.card-text {
  color: #4a5568;
  line-height: 1.6;
  margin: 0;
}
.list-group-item {
  border-left: none;
  border-right: none;
  padding: 0.6rem 0;
}
.list-group-item:hover {
  background-color: #f8f9ff;
}
.study-title {
  color: #2d3748;
  text-decoration: none;
  font-weight: 500;
  font-size: 0.95rem;
}
.study-title:hover {
  color: #4f6df5;
}
.publications-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.publication-item {
  padding: 0.75rem 0;
}
.publication-title {
  font-size: 1rem;
  font-weight: 600;
  color: #2d3748;
  margin: 0 0 0.25rem 0;
}

/* Mobile */
@media (max-width: 991px) {
  .researcher-layout {
    flex-direction: column;
    padding: 0 0.75rem;
  }
  .profile-sidebar {
    position: static;
    flex: none;
    width: 100%;
  }
  .profile-content {
    width: 100%;
  }
  .profile-photo,
  .profile-avatar {
    width: 90px;
    height: 90px;
    font-size: 1.5rem;
  }
  .name-text {
    font-size: 1.15rem;
  }
}
</style>

<?php
if ($isMobile) {
    include '../templates/researcher-mobile-footer.php';
} else {
    include '../templates/footer.php';
}
?>