<?php
/**
 * Collaborations Management
 * OBGYN Research & Collaboration Platform
 */

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

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

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

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $action = $_POST['action'] ?? '';
    $collabId = isset($_POST['collab_id']) ? (int)$_POST['collab_id'] : 0;
    
    $db = getDB();
    
    if ($action === 'accept' && $collabId) {
        $stmt = $db->prepare("
            UPDATE study_collaborators 
            SET status = 'active' 
            WHERE id = ? AND user_id = ? AND status = 'pending'
        ");
        $stmt->execute([$collabId, $userId]);
        $success = 'Collaboration invitation accepted!';
        
    } elseif ($action === 'decline' && $collabId) {
        $stmt = $db->prepare("
            UPDATE study_collaborators 
            SET status = 'declined' 
            WHERE id = ? AND user_id = ? AND status = 'pending'
        ");
        $stmt->execute([$collabId, $userId]);
        $success = 'Collaboration invitation declined.';
    }
}

// Get pending invitations
$db = getDB();
$stmt = $db->prepare("
    SELECT sc.*, s.title as study_title, s.type, u.first_name, u.last_name
    FROM study_collaborators sc
    JOIN studies s ON sc.study_id = s.id
    JOIN users u ON s.creator_id = u.id
    WHERE sc.user_id = ? AND sc.status = 'pending'
    ORDER BY sc.joined_at DESC
");
$stmt->execute([$userId]);
$pending = $stmt->fetchAll();

// Get active collaborations
$stmt = $db->prepare("
    SELECT sc.*, s.title as study_title, s.type, s.status as study_status, u.first_name, u.last_name
    FROM study_collaborators sc
    JOIN studies s ON sc.study_id = s.id
    JOIN users u ON s.creator_id = u.id
    WHERE sc.user_id = ? AND sc.status = 'active'
    ORDER BY sc.joined_at DESC
");
$stmt->execute([$userId]);
$active = $stmt->fetchAll();

// 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-users"></i> Collaborations</h1>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Alert Container for AJAX messages -->
            <div id="alertContainer"></div>

            <!-- Pending Invitations -->
            <div class="card shadow mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-clock"></i> Pending Invitations 
                        <span class="badge bg-warning" id="pendingCount"><?php echo count($pending); ?></span>
                    </h5>
                    <button class="btn btn-sm btn-outline-secondary" onclick="CollaborationManager.loadPending()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
                <div class="card-body">
                    <div id="pendingInvitations">
                        <?php if (empty($pending)): ?>
                            <p class="text-muted text-center py-4">No pending invitations.</p>
                        <?php else: ?>
                            <div class="list-group">
                                <?php foreach ($pending as $inv): ?>
                                <div class="list-group-item" data-collab-id="<?php echo $inv['id']; ?>">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <h6 class="mb-1">
                                                <i class="fas fa-flask text-primary"></i>
                                                <?php echo e($inv['study_title']); ?>
                                            </h6>
                                            <p class="mb-1 small text-muted">
                                                Invited by <strong><?php echo e($inv['first_name'] . ' ' . $inv['last_name']); ?></strong> 
                                                as <span class="badge bg-info"><?php echo ucfirst(str_replace('_', ' ', $inv['role'])); ?></span>
                                            </p>
                                            <small class="text-muted">
                                                <i class="fas fa-calendar"></i> <?php echo timeAgo($inv['joined_at']); ?>
                                            </small>
                                        </div>
                                        <div class="btn-group">
                                            <button onclick="CollaborationManager.acceptInvitation(<?php echo $inv['id']; ?>)" 
                                                    class="btn btn-sm btn-success">
                                                <i class="fas fa-check"></i> Accept
                                            </button>
                                            <button onclick="CollaborationManager.rejectInvitation(<?php echo $inv['id']; ?>)" 
                                                    class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-times"></i> Decline
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Active Collaborations -->
            <div class="card shadow mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-check-circle"></i> Active Collaborations 
                        <span class="badge bg-success" id="activeCount"><?php echo count($active); ?></span>
                    </h5>
                    <button class="btn btn-sm btn-outline-secondary" onclick="CollaborationManager.loadActive()">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                </div>
                <div class="card-body">
                    <div id="activeCollaborations">
                        <?php if (empty($active)): ?>
                            <p class="text-muted text-center py-4">No active collaborations.</p>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>Study</th>
                                            <th>Your Role</th>
                                            <th>Lead Researcher</th>
                                            <th>Status</th>
                                            <th>Joined</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($active as $collab): ?>
                                        <tr data-collab-id="<?php echo $collab['id']; ?>">
                                            <td>
                                                <a href="edit-study.php?id=<?php echo $collab['study_id']; ?>" class="text-decoration-none">
                                                    <i class="fas fa-flask text-primary"></i>
                                                    <?php echo e($collab['study_title']); ?>
                                                </a>
                                            </td>
                                            <td><span class="badge bg-info"><?php echo ucfirst(str_replace('_', ' ', $collab['role'])); ?></span></td>
                                            <td><?php echo e($collab['first_name'] . ' ' . $collab['last_name']); ?></td>
                                            <td><span class="badge bg-success"><?php echo ucfirst($collab['study_status']); ?></span></td>
                                            <td><?php echo date('M d, Y', strtotime($collab['joined_at'])); ?></td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="edit-study.php?id=<?php echo $collab['study_id']; ?>" 
                                                       class="btn btn-outline-primary">
                                                        <i class="fas fa-eye"></i> View
                                                    </a>
                                                    <button onclick="CollaborationManager.leaveCollaboration(<?php echo $collab['id']; ?>)" 
                                                            class="btn btn-outline-danger" title="Leave Collaboration">
                                                        <i class="fas fa-sign-out-alt"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

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

const CollaborationManager = {
    async acceptInvitation(collabId) {
        if (!confirm('Accept this collaboration invitation?')) return;
        
        try {
            const response = await fetch(`${API_URL}/collaborators.php`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    collaborator_id: collabId,
                    action: 'accept'
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.showAlert('Collaboration invitation accepted!', 'success');
                this.loadPending();
                this.loadActive();
            } else {
                this.showAlert(data.message || 'Failed to accept invitation', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to accept invitation', 'danger');
        }
    },
    
    async rejectInvitation(collabId) {
        if (!confirm('Decline this collaboration invitation?')) return;
        
        try {
            const response = await fetch(`${API_URL}/collaborators.php`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    collaborator_id: collabId,
                    action: 'reject'
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.showAlert('Collaboration invitation declined', 'info');
                this.loadPending();
            } else {
                this.showAlert(data.message || 'Failed to decline invitation', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to decline invitation', 'danger');
        }
    },
    
    async leaveCollaboration(collabId) {
        if (!confirm('Are you sure you want to leave this collaboration?')) return;
        
        try {
            const response = await fetch(`${API_URL}/collaborators.php`, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    collaborator_id: collabId
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.showAlert('You have left the collaboration', 'info');
                this.loadActive();
            } else {
                this.showAlert(data.message || 'Failed to leave collaboration', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            this.showAlert('Failed to leave collaboration', 'danger');
        }
    },
    
    async loadPending() {
        // Reload page to refresh pending invitations
        window.location.reload();
    },
    
    async loadActive() {
        // Reload page to refresh active collaborations
        window.location.reload();
    },
    
    showAlert(message, type = 'info') {
        const container = document.getElementById('alertContainer');
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} alert-dismissible fade show`;
        alert.innerHTML = `
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        container.appendChild(alert);
        
        setTimeout(() => alert.remove(), 5000);
    }
};
</script>

<style>
.list-group-item {
    transition: all 0.3s ease;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}

@keyframes fadeOut {
    from {
        opacity: 1;
        transform: translateX(0);
    }
    to {
        opacity: 0;
        transform: translateX(-100%);
    }
}
</style>

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