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

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

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

$pageTitle = 'Collaborations';
$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 '../templates/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar.php'; ?>

        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <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; ?>

            <!-- Pending Invitations -->
            <div class="card shadow mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-clock"></i> Pending Invitations 
                        <?php if (count($pending) > 0): ?>
                            <span class="badge bg-warning"><?php echo count($pending); ?></span>
                        <?php endif; ?>
                    </h5>
                </div>
                <div class="card-body">
                    <?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">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1"><?php echo e($inv['study_title']); ?></h6>
                                        <p class="mb-1 small text-muted">
                                            Invited by <?php echo e($inv['first_name'] . ' ' . $inv['last_name']); ?> 
                                            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">
                                        <form method="POST" action="" style="display: inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="accept">
                                            <input type="hidden" name="collab_id" value="<?php echo $inv['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-success">
                                                <i class="fas fa-check"></i> Accept
                                            </button>
                                        </form>
                                        <form method="POST" action="" style="display: inline;">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="decline">
                                            <input type="hidden" name="collab_id" value="<?php echo $inv['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                                <i class="fas fa-times"></i> Decline
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Active Collaborations -->
            <div class="card shadow mb-4">
                <div class="card-header">
                    <h5 class="mb-0">
                        <i class="fas fa-check-circle"></i> Active Collaborations 
                        <?php if (count($active) > 0): ?>
                            <span class="badge bg-success"><?php echo count($active); ?></span>
                        <?php endif; ?>
                    </h5>
                </div>
                <div class="card-body">
                    <?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>
                                        <td>
                                            <a href="edit-study.php?id=<?php echo $collab['study_id']; ?>">
                                                <?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>
                                            <a href="edit-study.php?id=<?php echo $collab['study_id']; ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<?php include '../templates/footer.php'; ?>
