<?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();

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

<div class="container my-5">
    <div class="row">
        <div class="col-lg-4">
            <div class="card shadow-sm mb-4">
                <div class="card-body text-center">
                    <div class="avatar-circle mx-auto mb-3" style="width: 120px; height: 120px; font-size: 48px;">
                        <?php echo strtoupper(substr($researcher['first_name'], 0, 1) . substr($researcher['last_name'], 0, 1)); ?>
                    </div>
                    <h3><?php echo e($researcher['first_name'] . ' ' . $researcher['last_name']); ?></h3>
                    <?php if ($researcher['specialization']): ?>
                        <p class="text-muted"><?php echo e($researcher['specialization']); ?></p>
                    <?php endif; ?>
                    <?php if ($researcher['institution_name']): ?>
                        <p class="text-muted"><i class="fas fa-university"></i> <?php echo e($researcher['institution_name']); ?></p>
                    <?php endif; ?>
                    <?php if (isLoggedIn() && getCurrentUserId() != $userId): ?>
                        <a href="<?php echo SITE_URL; ?>/researcher/messages.php?to=<?php echo $userId; ?>" class="btn btn-primary w-100 mt-3">
                            <i class="fas fa-envelope"></i> Send Message
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6>Contact Information</h6>
                    <?php if (isLoggedIn() && getCurrentUserId() == $userId): ?>
                        <!-- Show full contact info for profile owner -->
                        <p class="mb-1"><i class="fas fa-envelope"></i> <?php echo e($researcher['email']); ?></p>
                        <?php if ($researcher['phone']): ?>
                            <p class="mb-1"><i class="fas fa-phone"></i> <?php echo e($researcher['phone']); ?></p>
                        <?php endif; ?>
                        <?php if (isset($researcher['website']) && $researcher['website']): ?>
                            <p class="mb-0"><i class="fas fa-globe"></i> <a href="<?php echo e($researcher['website']); ?>" target="_blank">Website</a></p>
                        <?php endif; ?>
                    <?php elseif (isLoggedIn()): ?>
                        <!-- Check if user has approved contact request -->
                        <?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]);
                        $contactRequest = $stmt->fetch();
                        $hasAccess = $contactRequest && $contactRequest['status'] === 'approved';
                        ?>

                        <?php if ($hasAccess): ?>
                            <!-- Show contact info if request approved -->
                            <p class="mb-1"><i class="fas fa-envelope"></i> <?php echo e($researcher['email']); ?></p>
                            <?php if ($researcher['phone']): ?>
                                <p class="mb-1"><i class="fas fa-phone"></i> <?php echo e($researcher['phone']); ?></p>
                            <?php endif; ?>
                            <?php if (isset($researcher['website']) && $researcher['website']): ?>
                                <p class="mb-0"><i class="fas fa-globe"></i> <a href="<?php echo e($researcher['website']); ?>" target="_blank">Website</a></p>
                            <?php endif; ?>
                        <?php else: ?>
                            <!-- Show request button -->
                            <p class="text-muted mb-2">Contact information is private</p>
                            <button type="button" class="btn btn-outline-primary btn-sm" onclick="requestContact(<?php echo $userId; ?>)">
                                <i class="fas fa-user-plus"></i> Request Contact Info
                            </button>
                            <div id="contact-request-status" class="mt-2" style="display: none;"></div>
                        <?php endif; ?>
                    <?php else: ?>
                        <!-- Show login prompt for non-logged-in users -->
                        <p class="text-muted mb-2">Contact information is private</p>
                        <a href="<?php echo SITE_URL; ?>/login.php" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-sign-in-alt"></i> Login to Request Contact
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-lg-8">
            <?php if ($researcher['bio']): ?>
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <h4>About</h4>
                    <p><?php echo nl2br(e($researcher['bio'])); ?></p>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="card shadow-sm mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Studies (<?php echo count($studies); ?>)</h5>
                </div>
                <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">
                        <h6><?php echo e($study['title']); ?></h6>
                        <small class="text-muted"><?php echo ucfirst($study['type']); ?> | <?php echo date('Y', strtotime($study['created_at'])); ?></small>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="card shadow-sm">
                <div class="card-header">
                    <h5 class="mb-0">Publications (<?php echo count($publications); ?>)</h5>
                </div>
                <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">
                        <h6><?php echo e($pub['title']); ?></h6>
                        <small class="text-muted"><?php echo e($pub['journal'] ?? 'N/A'); ?> | <?php echo date('Y', strtotime($pub['publication_date'])); ?></small>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.avatar-circle {
    border-radius: 50%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
}
</style>

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