<?php
/**
 * Connections Management
 * OBGYN Research & Collaboration Platform
 * Manage researcher connections and network
 */

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

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

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

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

<div class="container-fluid p-4">
    <div class="row">
        <!-- Main content - full width since sidebar is offcanvas -->
        <main class="col-12">
            <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-friends"></i> My Connections
                    <span class="badge bg-primary" id="totalConnectionsCount">0</span>
                </h1>
                <div class="btn-toolbar">
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#findResearchersModal">
                        <i class="fas fa-user-plus"></i> Find Researchers
                    </button>
                </div>
            </div>

            <!-- Alert Messages -->
            <div id="alertContainer"></div>

            <!-- Navigation Tabs -->
            <ul class="nav nav-tabs mb-4" id="connectionTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="connections-tab" data-bs-toggle="tab" 
                            data-bs-target="#connections" type="button" role="tab">
                        <i class="fas fa-users"></i> My Connections 
                        <span class="badge bg-success" id="connectionsCount">0</span>
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="pending-tab" data-bs-toggle="tab" 
                            data-bs-target="#pending" type="button" role="tab">
                        <i class="fas fa-clock"></i> Pending Requests 
                        <span class="badge bg-warning" id="pendingCount">0</span>
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="sent-tab" data-bs-toggle="tab" 
                            data-bs-target="#sent" type="button" role="tab">
                        <i class="fas fa-paper-plane"></i> Sent Requests 
                        <span class="badge bg-info" id="sentCount">0</span>
                    </button>
                </li>
            </ul>

            <!-- Tab Content -->
            <div class="tab-content" id="connectionTabContent">
                <!-- My Connections Tab -->
                <div class="tab-pane fade show active" id="connections" role="tabpanel">
                    <div class="card shadow">
                        <div class="card-body">
                            <div id="connectionsLoading" class="text-center py-5">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading connections...</p>
                            </div>
                            <div id="connectionsList" class="row g-3" style="display: none;"></div>
                            <div id="connectionsEmpty" class="text-center py-5" style="display: none;">
                                <i class="fas fa-user-friends fa-4x text-muted mb-3"></i>
                                <h5>No Connections Yet</h5>
                                <p class="text-muted">Start building your research network by connecting with other researchers.</p>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#findResearchersModal">
                                    <i class="fas fa-user-plus"></i> Find Researchers
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Pending Requests Tab -->
                <div class="tab-pane fade" id="pending" role="tabpanel">
                    <div class="card shadow">
                        <div class="card-body">
                            <div id="pendingLoading" class="text-center py-5">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading requests...</p>
                            </div>
                            <div id="pendingList" style="display: none;"></div>
                            <div id="pendingEmpty" class="text-center py-5" style="display: none;">
                                <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                                <h5>No Pending Requests</h5>
                                <p class="text-muted">You don't have any pending connection requests.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Sent Requests Tab -->
                <div class="tab-pane fade" id="sent" role="tabpanel">
                    <div class="card shadow">
                        <div class="card-body">
                            <div id="sentLoading" class="text-center py-5">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading requests...</p>
                            </div>
                            <div id="sentList" style="display: none;"></div>
                            <div id="sentEmpty" class="text-center py-5" style="display: none;">
                                <i class="fas fa-paper-plane fa-4x text-muted mb-3"></i>
                                <h5>No Sent Requests</h5>
                                <p class="text-muted">You haven't sent any connection requests yet.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Find Researchers Modal -->
<div class="modal fade" id="findResearchersModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-search"></i> Find Researchers</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <input type="text" class="form-control" id="searchResearchers" 
                           placeholder="Search by name, specialization, or institution...">
                </div>
                <div id="researchersLoading" class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
                <div id="researchersList" style="display: none;"></div>
            </div>
        </div>
    </div>
</div>

<script>
// API Base URL
const API_URL = '<?php echo SITE_URL; ?>/api';

// Show alert message
function showAlert(message, type = 'success') {
    const alertHtml = `
        <div class="alert alert-${type} alert-dismissible fade show" role="alert">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    document.getElementById('alertContainer').innerHTML = alertHtml;
    
    // Auto-dismiss after 5 seconds
    setTimeout(() => {
        const alert = document.querySelector('.alert');
        if (alert) {
            alert.classList.remove('show');
            setTimeout(() => alert.remove(), 150);
        }
    }, 5000);
}

// Load connections
async function loadConnections() {
    try {
        const response = await fetch(`${API_URL}/connections.php?type=connections`);
        const data = await response.json();
        
        document.getElementById('connectionsLoading').style.display = 'none';
        
        if (data.success && data.connections.length > 0) {
            document.getElementById('connectionsList').style.display = 'flex';
            document.getElementById('connectionsEmpty').style.display = 'none';
            document.getElementById('connectionsCount').textContent = data.total;
            document.getElementById('totalConnectionsCount').textContent = data.total;
            
            let html = '';
            data.connections.forEach(conn => {
                html += `
                    <div class="col-md-6 col-lg-4">
                        <div class="card h-100 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="avatar-circle bg-primary text-white me-3">
                                        ${conn.first_name.charAt(0)}${conn.last_name.charAt(0)}
                                    </div>
                                    <div class="flex-grow-1">
                                        <h6 class="mb-0">
                                            <a href="../public/researcher-profile.php?id=${conn.id}" class="text-decoration-none">
                                                ${conn.first_name} ${conn.last_name}
                                            </a>
                                        </h6>
                                        <small class="text-muted">${conn.specialization || 'Researcher'}</small>
                                    </div>
                                </div>
                                ${conn.institution_name ? `
                                    <p class="small mb-2">
                                        <i class="fas fa-building text-muted"></i> ${conn.institution_name}
                                    </p>
                                ` : ''}
                                <p class="small text-muted mb-3">
                                    <i class="fas fa-calendar"></i> Connected ${timeAgo(conn.connected_at)}
                                </p>
                                <div class="d-flex gap-2">
                                    <a href="messages-enhanced.php?user=${conn.id}" class="btn btn-sm btn-outline-primary flex-grow-1">
                                        <i class="fas fa-envelope"></i> Message
                                    </a>
                                    <button onclick="removeConnection(${conn.id})" class="btn btn-sm btn-outline-danger" title="Remove Connection">
                                        <i class="fas fa-user-times"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            document.getElementById('connectionsList').innerHTML = html;
        } else {
            document.getElementById('connectionsEmpty').style.display = 'block';
            document.getElementById('connectionsCount').textContent = '0';
            document.getElementById('totalConnectionsCount').textContent = '0';
        }
    } catch (error) {
        console.error('Error loading connections:', error);
        showAlert('Failed to load connections', 'danger');
    }
}

// Load pending requests
async function loadPendingRequests() {
    try {
        const response = await fetch(`${API_URL}/connections.php?type=pending`);
        const data = await response.json();
        
        document.getElementById('pendingLoading').style.display = 'none';
        
        if (data.success && data.requests.length > 0) {
            document.getElementById('pendingList').style.display = 'block';
            document.getElementById('pendingEmpty').style.display = 'none';
            document.getElementById('pendingCount').textContent = data.total;
            
            let html = '<div class="list-group">';
            data.requests.forEach(req => {
                html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="d-flex align-items-center flex-grow-1">
                                <div class="avatar-circle bg-info text-white me-3">
                                    ${req.first_name.charAt(0)}${req.last_name.charAt(0)}
                                </div>
                                <div>
                                    <h6 class="mb-1">
                                        <a href="../public/researcher-profile.php?id=${req.id}" class="text-decoration-none">
                                            ${req.first_name} ${req.last_name}
                                        </a>
                                    </h6>
                                    <p class="mb-1 small text-muted">${req.specialization || 'Researcher'}</p>
                                    ${req.institution_name ? `<p class="mb-1 small"><i class="fas fa-building"></i> ${req.institution_name}</p>` : ''}
                                    <small class="text-muted"><i class="fas fa-clock"></i> ${timeAgo(req.created_at)}</small>
                                </div>
                            </div>
                            <div class="btn-group">
                                <button onclick="acceptRequest(${req.request_id})" class="btn btn-sm btn-success">
                                    <i class="fas fa-check"></i> Accept
                                </button>
                                <button onclick="rejectRequest(${req.request_id})" class="btn btn-sm btn-outline-danger">
                                    <i class="fas fa-times"></i> Reject
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            document.getElementById('pendingList').innerHTML = html;
        } else {
            document.getElementById('pendingEmpty').style.display = 'block';
            document.getElementById('pendingCount').textContent = '0';
        }
    } catch (error) {
        console.error('Error loading pending requests:', error);
        showAlert('Failed to load pending requests', 'danger');
    }
}

// Load sent requests
async function loadSentRequests() {
    try {
        const response = await fetch(`${API_URL}/connections.php?type=sent`);
        const data = await response.json();
        
        document.getElementById('sentLoading').style.display = 'none';
        
        if (data.success && data.sent_requests.length > 0) {
            document.getElementById('sentList').style.display = 'block';
            document.getElementById('sentEmpty').style.display = 'none';
            document.getElementById('sentCount').textContent = data.total;
            
            let html = '<div class="list-group">';
            data.sent_requests.forEach(req => {
                const statusBadge = req.status === 'pending' ? 
                    '<span class="badge bg-warning">Pending</span>' : 
                    '<span class="badge bg-danger">Rejected</span>';
                    
                html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center flex-grow-1">
                                <div class="avatar-circle bg-secondary text-white me-3">
                                    ${req.first_name.charAt(0)}${req.last_name.charAt(0)}
                                </div>
                                <div>
                                    <h6 class="mb-1">${req.first_name} ${req.last_name}</h6>
                                    <p class="mb-1 small text-muted">${req.specialization || 'Researcher'}</p>
                                    ${req.institution_name ? `<p class="mb-0 small"><i class="fas fa-building"></i> ${req.institution_name}</p>` : ''}
                                </div>
                            </div>
                            <div class="text-end">
                                ${statusBadge}
                                <br>
                                <small class="text-muted">${timeAgo(req.created_at)}</small>
                            </div>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            document.getElementById('sentList').innerHTML = html;
        } else {
            document.getElementById('sentEmpty').style.display = 'block';
            document.getElementById('sentCount').textContent = '0';
        }
    } catch (error) {
        console.error('Error loading sent requests:', error);
        showAlert('Failed to load sent requests', 'danger');
    }
}

// Accept connection request
async function acceptRequest(requestId) {
    if (!confirm('Accept this connection request?')) return;
    
    try {
        const response = await fetch(`${API_URL}/connections.php`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ request_id: requestId, action: 'accept' })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('Connection request accepted!', 'success');
            loadPendingRequests();
            loadConnections();
        } else {
            showAlert(data.message || 'Failed to accept request', 'danger');
        }
    } catch (error) {
        console.error('Error accepting request:', error);
        showAlert('Failed to accept request', 'danger');
    }
}

// Reject connection request
async function rejectRequest(requestId) {
    if (!confirm('Reject this connection request?')) return;
    
    try {
        const response = await fetch(`${API_URL}/connections.php`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ request_id: requestId, action: 'reject' })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('Connection request rejected', 'info');
            loadPendingRequests();
        } else {
            showAlert(data.message || 'Failed to reject request', 'danger');
        }
    } catch (error) {
        console.error('Error rejecting request:', error);
        showAlert('Failed to reject request', 'danger');
    }
}

// Remove connection
async function removeConnection(userId) {
    if (!confirm('Are you sure you want to remove this connection?')) return;
    
    try {
        const response = await fetch(`${API_URL}/connections.php`, {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ user_id: userId })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('Connection removed', 'info');
            loadConnections();
        } else {
            showAlert(data.message || 'Failed to remove connection', 'danger');
        }
    } catch (error) {
        console.error('Error removing connection:', error);
        showAlert('Failed to remove connection', 'danger');
    }
}

// Send connection request
async function sendConnectionRequest(userId) {
    try {
        const response = await fetch(`${API_URL}/connections.php`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ user_id: userId })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('Connection request sent!', 'success');
            loadSentRequests();
            // Refresh researchers list
            searchResearchers();
        } else {
            showAlert(data.message || 'Failed to send request', 'danger');
        }
    } catch (error) {
        console.error('Error sending request:', error);
        showAlert('Failed to send request', 'danger');
    }
}

// Search researchers
async function searchResearchers() {
    const searchTerm = document.getElementById('searchResearchers').value;
    
    try {
        document.getElementById('researchersLoading').style.display = 'block';
        document.getElementById('researchersList').style.display = 'none';
        
        const response = await fetch(`${API_URL}/search.php?type=researchers&q=${encodeURIComponent(searchTerm)}`);
        const data = await response.json();
        
        document.getElementById('researchersLoading').style.display = 'none';
        
        if (data.success && data.results.length > 0) {
            document.getElementById('researchersList').style.display = 'block';
            
            let html = '<div class="list-group">';
            data.results.forEach(researcher => {
                html += `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center flex-grow-1">
                                <div class="avatar-circle bg-primary text-white me-3">
                                    ${researcher.first_name.charAt(0)}${researcher.last_name.charAt(0)}
                                </div>
                                <div>
                                    <h6 class="mb-1">${researcher.first_name} ${researcher.last_name}</h6>
                                    <p class="mb-1 small text-muted">${researcher.specialization || 'Researcher'}</p>
                                    ${researcher.institution_name ? `<p class="mb-0 small"><i class="fas fa-building"></i> ${researcher.institution_name}</p>` : ''}
                                </div>
                            </div>
                            <div class="btn-group">
                                <a href="../public/researcher-profile.php?id=${researcher.id}" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-eye"></i> View
                                </a>
                                <button onclick="sendConnectionRequest(${researcher.id})" class="btn btn-sm btn-primary">
                                    <i class="fas fa-user-plus"></i> Connect
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            document.getElementById('researchersList').innerHTML = html;
        } else {
            document.getElementById('researchersList').style.display = 'block';
            document.getElementById('researchersList').innerHTML = `
                <div class="text-center py-4 text-muted">
                    <i class="fas fa-search fa-3x mb-3"></i>
                    <p>No researchers found. Try a different search term.</p>
                </div>
            `;
        }
    } catch (error) {
        console.error('Error searching researchers:', error);
        document.getElementById('researchersLoading').style.display = 'none';
        showAlert('Failed to search researchers', 'danger');
    }
}

// Time ago helper
function timeAgo(dateString) {
    const date = new Date(dateString);
    const now = new Date();
    const seconds = Math.floor((now - date) / 1000);
    
    const intervals = {
        year: 31536000,
        month: 2592000,
        week: 604800,
        day: 86400,
        hour: 3600,
        minute: 60
    };
    
    for (const [unit, secondsInUnit] of Object.entries(intervals)) {
        const interval = Math.floor(seconds / secondsInUnit);
        if (interval >= 1) {
            return interval === 1 ? `1 ${unit} ago` : `${interval} ${unit}s ago`;
        }
    }
    
    return 'just now';
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    loadConnections();
    loadPendingRequests();
    loadSentRequests();
    
    // Search researchers on modal open
    document.getElementById('findResearchersModal').addEventListener('shown.bs.modal', function() {
        searchResearchers();
    });
    
    // Search on input
    document.getElementById('searchResearchers').addEventListener('input', function() {
        clearTimeout(this.searchTimeout);
        this.searchTimeout = setTimeout(() => searchResearchers(), 500);
    });
    
    // Refresh data when switching tabs
    document.querySelectorAll('#connectionTabs button').forEach(button => {
        button.addEventListener('shown.bs.tab', function(e) {
            const target = e.target.getAttribute('data-bs-target');
            if (target === '#connections') loadConnections();
            else if (target === '#pending') loadPendingRequests();
            else if (target === '#sent') loadSentRequests();
        });
    });
});
</script>

<style>
.avatar-circle {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 1.2rem;
    flex-shrink: 0;
}
</style>

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