<?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'];

// 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; ?>
                    <div class="d-flex justify-content-center gap-4 mt-3 mb-3">
                        <div class="text-center">
                            <strong><?php echo $followersCount; ?></strong>
                            <small class="d-block text-muted">Followers</small>
                        </div>
                        <div class="text-center">
                            <strong><?php echo count($studies); ?></strong>
                            <small class="d-block text-muted">Studies</small>
                        </div>
                        <div class="text-center">
                            <strong><?php echo count($publications); ?></strong>
                            <small class="d-block text-muted">Publications</small>
                        </div>
                    </div>
                    <?php if (isLoggedIn() && getCurrentUserId() != $userId): ?>
                        <?php
                        // Check if current user is following this researcher
                        $currentUserId = getCurrentUserId();
                        $stmt = $db->prepare("SELECT id FROM followers WHERE follower_id = ? AND following_id = ?");
                        $stmt->execute([$currentUserId, $userId]);
                        $isFollowing = $stmt->fetch() ? true : false;
                        ?>
                        <div class="d-grid gap-2 mt-3">
                            <button id="follow-btn" class="btn <?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.php?to=<?php echo $userId; ?>" class="btn btn-outline-primary">
                                <i class="fas fa-envelope"></i> Send Message
                            </a>
                        </div>
                    <?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';
                        $hasPendingRequest = $contactRequest && $contactRequest['status'] === 'pending';
                        ?>

                        <?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 elseif ($hasPendingRequest): ?>
                            <!-- Show pending request status -->
                            <p class="text-muted mb-2">Contact information is private</p>
                            <button type="button" class="btn btn-secondary btn-sm" disabled>
                                <i class="fas fa-clock"></i> Request Sent
                            </button>
                            <p class="text-muted small mt-1">Waiting for approval</p>
                        <?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>

<script>
async function toggleFollow(targetUserId) {
    const btn = document.getElementById('follow-btn');
    const icon = btn.querySelector('i');
    const text = btn.querySelector('i').nextSibling;
    
    // Disable button during request
    btn.disabled = true;
    const wasFollowing = btn.classList.contains('btn-outline-secondary');
    
    try {
        let response;
        let result;
        
        if (wasFollowing) {
            // Unfollow
            response = await fetch('<?php echo SITE_URL; ?>/api/follow.php?user_id=' + targetUserId, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
        } else {
            // Follow
            const formData = new FormData();
            formData.append('user_id', targetUserId);
            
            response = await fetch('<?php echo SITE_URL; ?>/api/follow.php', {
                method: 'POST',
                body: formData
            });
        }
        
        result = await response.json();
        
        if (result.success) {
            if (wasFollowing) {
                // Successfully unfollowed
                btn.classList.remove('btn-outline-secondary');
                btn.classList.add('btn-primary');
                icon.className = 'fas fa-user-plus';
                text.textContent = ' Follow';
            } else {
                // Successfully followed
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-outline-secondary');
                icon.className = 'fas fa-user-minus';
                text.textContent = ' Unfollow';
            }
        } else {
            alert('Error: ' + (result.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Follow/Unfollow error:', error);
        alert('An error occurred. Please try again.');
    } finally {
        btn.disabled = false;
    }
}

async function requestContact(targetUserId) {
    const btn = document.querySelector(`button[onclick*="requestContact(${targetUserId})"]`);
    const statusDiv = document.getElementById('contact-request-status');
    
    // Disable button during request
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
    
    try {
        const formData = new FormData();
        formData.append('target_user_id', targetUserId);
        formData.append('message', 'I would like to connect with you regarding research collaboration.');
        
        const response = await fetch('<?php echo SITE_URL; ?>/api/contact-requests.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            statusDiv.style.display = 'block';
            statusDiv.innerHTML = '<div class="alert alert-success">Contact request sent successfully!</div>';
            // Update button to show "Request Sent" state
            btn.disabled = true;
            btn.className = 'btn btn-secondary btn-sm';
            btn.innerHTML = '<i class="fas fa-clock"></i> Request Sent';
            // Hide the status message after 3 seconds and show the permanent status
            setTimeout(() => {
                statusDiv.style.display = 'none';
                // Add a permanent status message
                const permanentStatus = document.createElement('p');
                permanentStatus.className = 'text-muted small mt-1';
                permanentStatus.textContent = 'Waiting for approval';
                btn.parentNode.insertBefore(permanentStatus, btn.nextSibling);
            }, 3000);
        } else {
            statusDiv.style.display = 'block';
            statusDiv.innerHTML = '<div class="alert alert-danger">Error: ' + (result.error || 'Unknown error') + '</div>';
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-user-plus"></i> Request Contact Info';
        }
    } catch (error) {
        console.error('Contact request error:', error);
        statusDiv.style.display = 'block';
        statusDiv.innerHTML = '<div class="alert alert-danger">An error occurred. Please try again.</div>';
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-user-plus"></i> Request Contact Info';
    }
}
</script>

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