<?php
require_once '../config/config.php';
$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);
$userId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$userId) redirect(SITE_URL . '/public/researchers.php');
$db = getDB();
$stmt = $db->prepare("
    SELECT u.*, rp.*, i.name as institution_name
    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 u.id = ? AND u.role_id = ? AND u.status = 'active'
");
$stmt->execute([$userId, ROLE_RESEARCHER]);
$researcher = $stmt->fetch();
if (!$researcher) redirect(SITE_URL . '/public/researchers.php');
$pageTitle = $researcher['first_name'] . ' ' . $researcher['last_name'];

// Get studies
$stmt = $db->prepare("SELECT * FROM studies WHERE creator_id = ? AND is_public = 1 ORDER BY created_at DESC LIMIT 5");
$stmt->execute([$userId]);
$studies = $stmt->fetchAll();

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

// Get follower count
$stmt = $db->prepare("SELECT COUNT(*) as followers_count FROM followers WHERE following_id = ?");
$stmt->execute([$userId]);
$followerData = $stmt->fetch();
$followersCount = $followerData['followers_count'];

// Check if current user is following
$isFollowing = false;
if (isLoggedIn()) {
    $currentUserId = getCurrentUserId();
    $stmt = $db->prepare("SELECT id FROM followers WHERE follower_id = ? AND following_id = ?");
    $stmt->execute([$currentUserId, $userId]);
    $isFollowing = $stmt->fetch() ? true : false;
}

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

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

          <!-- Name & Title -->
          <h4 class="name-text"><?php echo e($researcher['first_name'] . ' ' . $researcher['last_name']); ?></h4>
          <?php if ($researcher['title']): ?>
            <p class="title-text mb-1"><?php echo e($researcher['title']); ?></p>
          <?php endif; ?>
          <?php if ($researcher['specialization']): ?>
            <p class="specialization-text mb-2"><?php echo e($researcher['specialization']); ?></p>
          <?php endif; ?>

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

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

          <!-- Stats -->
          <div class="stats-row mb-3">
            <div class="stat-item">
              <div class="stat-value"><?php echo $followersCount; ?></div>
              <div class="stat-label">Followers</div>
            </div>
            <div class="stat-item">
              <div class="stat-value"><?php echo count($studies); ?></div>
              <div class="stat-label">Studies</div>
            </div>
            <div class="stat-item">
              <div class="stat-value"><?php echo count($publications); ?></div>
              <div class="stat-label">Publications</div>
            </div>
          </div>

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

          <!-- Actions -->
          <?php if (isLoggedIn() && getCurrentUserId() != $userId): ?>
            <div class="d-grid gap-2">
              <button id="follow-btn" class="btn btn-sm <?php echo $isFollowing ? 'btn-outline-secondary' : 'btn-primary'; ?>" onclick="toggleFollow(<?php echo $userId; ?>)">
                <i class="fas <?php echo $isFollowing ? 'fa-user-minus' : 'fa-user-plus'; ?>"></i>
                <?php echo $isFollowing ? 'Unfollow' : 'Follow'; ?>
              </button>
              <a href="<?php echo SITE_URL; ?>/researcher/messages-enhanced.php?user=<?php echo $userId; ?>" class="btn btn-sm btn-outline-primary">
                <i class="fas fa-envelope"></i> Message
              </a>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Contact Card -->
      <div class="contact-card shadow-sm">
        <div class="card-body">
          <h6 class="contact-title mb-2"><i class="fas fa-address-book me-2"></i>Contact</h6>
          <?php if (isLoggedIn() && getCurrentUserId() == $userId): ?>
            <div class="contact-info">
              <div class="contact-item"><i class="fas fa-envelope me-2 text-muted"></i> <?php echo e($researcher['email']); ?></div>
              <?php if ($researcher['phone']): ?>
                <div class="contact-item"><i class="fas fa-phone me-2 text-muted"></i> <?php echo e($researcher['phone']); ?></div>
              <?php endif; ?>
              <?php if (!empty($researcher['website'])): ?>
                <div class="contact-item"><i class="fas fa-globe me-2 text-muted"></i> <a href="<?php echo e($researcher['website']); ?>" target="_blank">Website</a></div>
              <?php endif; ?>
            </div>
          <?php elseif (isLoggedIn()): ?>
            <?php
            $currentUserId = getCurrentUserId();
            $stmt = $db->prepare("SELECT status FROM contact_requests WHERE (requester_id = ? AND target_id = ?) OR (requester_id = ? AND target_id = ?) ORDER BY created_at DESC LIMIT 1");
            $stmt->execute([$currentUserId, $userId, $userId, $currentUserId]);
            $req = $stmt->fetch();
            $approved = $req && $req['status'] === 'approved';
            $pending = $req && $req['status'] === 'pending';
            ?>
            <?php if ($approved): ?>
              <div class="contact-info">
                <div class="contact-item"><i class="fas fa-envelope me-2 text-muted"></i> <?php echo e($researcher['email']); ?></div>
                <?php if ($researcher['phone']): ?>
                  <div class="contact-item"><i class="fas fa-phone me-2 text-muted"></i> <?php echo e($researcher['phone']); ?></div>
                <?php endif; ?>
                <?php if (!empty($researcher['website'])): ?>
                  <div class="contact-item"><i class="fas fa-globe me-2 text-muted"></i> <a href="<?php echo e($researcher['website']); ?>" target="_blank">Website</a></div>
                <?php endif; ?>
              </div>
            <?php elseif ($pending): ?>
              <p class="text-muted small"><i class="fas fa-clock me-1"></i> Request pending approval</p>
            <?php else: ?>
              <p class="text-muted small mb-2"><i class="fas fa-lock me-1"></i> Contact info is private</p>
              <button class="btn btn-sm btn-outline-primary w-100" onclick="requestContact(<?php echo $userId; ?>)">
                <i class="fas fa-user-plus me-1"></i> Request Access
              </button>
            <?php endif; ?>
          <?php else: ?>
            <p class="text-muted small mb-2"><i class="fas fa-lock me-1"></i> Login to view contact info</p>
            <a href="<?php echo SITE_URL; ?>/login.php" class="btn btn-sm btn-outline-primary w-100">
              <i class="fas fa-sign-in-alt me-1"></i> Login
            </a>
          <?php endif; ?>
        </div>
      </div>
    </aside>

    <!-- RIGHT COLUMN: Scrollable content -->
    <main class="profile-content">
      <?php if ($researcher['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($researcher['bio'])); ?></p>
        </div>
      <?php endif; ?>

      <?php if ($researcher['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($researcher['research_interests'])); ?></p>
        </div>
      <?php endif; ?>

      <?php if ($researcher['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($researcher['degrees'])); ?></p>
        </div>
      <?php endif; ?>

      <div class="content-card">
        <h5 class="card-title"><i class="fas fa-flask me-2"></i>Research Studies <span class="badge bg-secondary ms-2"><?php echo count($studies); ?></span></h5>
        <?php if (empty($studies)): ?>
          <p class="text-muted">No studies published yet.</p>
        <?php else: ?>
          <div class="list-group list-group-flush">
            <?php foreach ($studies as $study): ?>
              <a href="study-detail.php?id=<?php echo $study['id']; ?>" class="list-group-item list-group-item-action py-2">
                <div class="d-flex justify-content-between">
                  <div><strong><?php echo e($study['title']); ?></strong></div>
                  <span class="text-muted small"><?php echo date('Y', strtotime($study['created_at'])); ?></span>
                </div>
                <small class="text-muted"><?php echo ucfirst($study['type']); ?></small>
              </a>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>

      <div class="content-card">
        <h5 class="card-title"><i class="fas fa-book me-2"></i>Publications <span class="badge bg-secondary ms-2"><?php echo count($publications); ?></span></h5>
        <?php if (empty($publications)): ?>
          <p class="text-muted">No publications yet.</p>
        <?php else: ?>
          <div class="list-group list-group-flush">
            <?php foreach ($publications as $pub): ?>
              <a href="publication-detail.php?id=<?php echo $pub['id']; ?>" class="list-group-item list-group-item-action py-2">
                <div class="d-flex justify-content-between">
                  <div><strong><?php echo e($pub['title']); ?></strong></div>
                  <span class="text-muted small"><?php echo date('Y', strtotime($pub['publication_date'])); ?></span>
                </div>
                <small class="text-muted"><?php echo e($pub['journal'] ?? 'N/A'); ?></small>
              </a>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </main>
  </div>
</div>

<style>
.researcher-profile-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;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  position: sticky;
  top: 1.5rem;
  height: fit-content;
}
.profile-card-public,
.contact-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-public {
  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-public {
  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-title {
  font-weight: 600;
  color: #2d3748;
  font-size: 1rem;
}
.contact-item {
  font-size: 0.95rem;
  color: #4a5568;
  margin-bottom: 0.25rem;
}
.contact-item a {
  color: #4f6df5;
  text-decoration: none;
}
.contact-item a:hover {
  text-decoration: underline;
}
.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;
}
.list-group-item strong {
  color: #2d3748;
  font-size: 0.95rem;
}
.list-group-item small {
  display: block;
  margin-top: 0.25rem;
}

/* 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-public,
  .profile-avatar-public {
    width: 90px;
    height: 90px;
    font-size: 1.5rem;
  }
  .name-text {
    font-size: 1.15rem;
  }
}
</style>

<script>
async function toggleFollow(targetUserId) {
    const btn = document.getElementById('follow-btn');
    const wasFollowing = btn.classList.contains('btn-outline-secondary');
    btn.disabled = true;
    try {
        let response;
        if (wasFollowing) {
            response = await fetch('<?php echo SITE_URL; ?>/api/follow.php?user_id=' + targetUserId, { method: 'DELETE' });
        } else {
            const fd = new FormData();
            fd.append('user_id', targetUserId);
            response = await fetch('<?php echo SITE_URL; ?>/api/follow.php', { method: 'POST', body: fd });
        }
        const result = await response.json();
        if (result.success) {
            if (wasFollowing) {
                btn.className = 'btn btn-sm btn-primary';
                btn.innerHTML = '<i class="fas fa-user-plus"></i> Follow';
            } else {
                btn.className = 'btn btn-sm btn-outline-secondary';
                btn.innerHTML = '<i class="fas fa-user-minus"></i> Unfollow';
            }
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
        }
    } catch (e) {
        alert('An error occurred.');
    } finally {
        btn.disabled = false;
    }
}

async function requestContact(targetUserId) {
    const btn = event.target.closest('button');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    try {
        const fd = new FormData();
        fd.append('target_user_id', targetUserId);
        fd.append('message', 'Request to connect');
        const res = await fetch('<?php echo SITE_URL; ?>/api/contact-requests.php', { method: 'POST', body: fd });
        const result = await res.json();
        if (result.success) {
            btn.className = 'btn btn-sm btn-secondary';
            btn.innerHTML = '<i class="fas fa-check"></i> Sent';
            setTimeout(() => {
                const p = document.createElement('p');
                p.className = 'text-muted small mt-2';
                p.textContent = 'Waiting for approval';
                btn.parentNode.appendChild(p);
            }, 1500);
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-user-plus me-1"></i> Request Access';
        }
    } catch (e) {
        alert('An error occurred.');
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-user-plus me-1"></i> Request Access';
    }
}
</script>

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