<?php
/**
 * Collaborators API
 * Handles study collaborator management (add, remove, update roles)
 */

header('Content-Type: application/json');
require_once '../config/config.php';

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$userId = getCurrentUserId();
$method = $_SERVER['REQUEST_METHOD'];

try {
    $db = getDB();
    
    switch ($method) {
        case 'GET':
            // Get collaborators for a study
            if (!isset($_GET['study_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Study ID required']);
                exit;
            }
            
            $studyId = (int)$_GET['study_id'];
            
            // Verify user has access to study
            $stmt = $db->prepare("
                SELECT user_id FROM studies WHERE id = ?
                UNION
                SELECT user_id FROM study_collaborators WHERE study_id = ?
            ");
            $stmt->execute([$studyId, $studyId]);
            $hasAccess = false;
            
            while ($row = $stmt->fetch()) {
                if ($row['user_id'] == $userId) {
                    $hasAccess = true;
                    break;
                }
            }
            
            if (!$hasAccess && !canAccessAdminPanel()) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Get collaborators
            $stmt = $db->prepare("
                SELECT sc.*, u.first_name, u.last_name, u.email,
                       rp.specialization, i.name as institution_name
                FROM study_collaborators sc
                JOIN users u ON sc.user_id = u.id
                LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                LEFT JOIN institutions i ON rp.institution_id = i.id
                WHERE sc.study_id = ?
                ORDER BY sc.created_at ASC
            ");
            $stmt->execute([$studyId]);
            $collaborators = $stmt->fetchAll();
            
            echo json_encode([
                'success' => true,
                'collaborators' => $collaborators,
                'total' => count($collaborators)
            ]);
            break;
            
        case 'POST':
            // Add collaborator to study
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['study_id']) || !isset($data['user_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Study ID and User ID required']);
                exit;
            }
            
            $studyId = (int)$data['study_id'];
            $collaboratorUserId = (int)$data['user_id'];
            $role = isset($data['role']) ? sanitize($data['role']) : 'contributor';
            
            // Verify user owns the study
            $stmt = $db->prepare("SELECT user_id FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();
            
            if (!$study || ($study['user_id'] !== $userId && !canAccessAdminPanel())) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Check if user is already a collaborator
            $stmt = $db->prepare("
                SELECT id FROM study_collaborators 
                WHERE study_id = ? AND user_id = ?
            ");
            $stmt->execute([$studyId, $collaboratorUserId]);
            
            if ($stmt->fetch()) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'User is already a collaborator']);
                exit;
            }
            
            // Add collaborator
            $stmt = $db->prepare("
                INSERT INTO study_collaborators (study_id, user_id, role, status)
                VALUES (?, ?, ?, 'pending')
            ");
            $stmt->execute([$studyId, $collaboratorUserId, $role]);
            $collaboratorId = $db->lastInsertId();
            
            // Create notification for the invited user
            $stmt = $db->prepare("
                INSERT INTO notifications (user_id, type, title, message, related_id)
                VALUES (?, 'collaboration_invite', 'Collaboration Invitation', 
                        'You have been invited to collaborate on a study', ?)
            ");
            $stmt->execute([$collaboratorUserId, $studyId]);
            
            // Log activity
            logActivity('collaborator_added', 'study_collaborators', $collaboratorId);
            
            echo json_encode([
                'success' => true,
                'message' => 'Collaborator invitation sent',
                'collaborator_id' => $collaboratorId
            ]);
            break;
            
        case 'PUT':
            // Update collaborator role or accept/reject invitation
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['collaborator_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Collaborator ID required']);
                exit;
            }
            
            $collaboratorId = (int)$data['collaborator_id'];
            
            // Get collaborator details
            $stmt = $db->prepare("
                SELECT sc.*, s.user_id as study_owner_id
                FROM study_collaborators sc
                JOIN studies s ON sc.study_id = s.id
                WHERE sc.id = ?
            ");
            $stmt->execute([$collaboratorId]);
            $collaborator = $stmt->fetch();
            
            if (!$collaborator) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Collaborator not found']);
                exit;
            }
            
            // Check if user has permission to update
            $canUpdate = ($collaborator['study_owner_id'] == $userId) || 
                        ($collaborator['user_id'] == $userId) || 
                        canAccessAdminPanel();
            
            if (!$canUpdate) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Update based on action
            if (isset($data['action'])) {
                $action = sanitize($data['action']);
                
                if ($action === 'accept' && $collaborator['user_id'] == $userId) {
                    // Accept collaboration invitation
                    $stmt = $db->prepare("UPDATE study_collaborators SET status = 'accepted' WHERE id = ?");
                    $stmt->execute([$collaboratorId]);
                    
                    logActivity('collaboration_accepted', 'study_collaborators', $collaboratorId);
                    
                    echo json_encode(['success' => true, 'message' => 'Collaboration accepted']);
                    
                } elseif ($action === 'reject' && $collaborator['user_id'] == $userId) {
                    // Reject collaboration invitation
                    $stmt = $db->prepare("DELETE FROM study_collaborators WHERE id = ?");
                    $stmt->execute([$collaboratorId]);
                    
                    logActivity('collaboration_rejected', 'study_collaborators', $collaboratorId);
                    
                    echo json_encode(['success' => true, 'message' => 'Collaboration rejected']);
                    
                } else {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'message' => 'Invalid action']);
                }
                
            } elseif (isset($data['role']) && $collaborator['study_owner_id'] == $userId) {
                // Update collaborator role (only study owner can do this)
                $newRole = sanitize($data['role']);
                
                $stmt = $db->prepare("UPDATE study_collaborators SET role = ? WHERE id = ?");
                $stmt->execute([$newRole, $collaboratorId]);
                
                logActivity('collaborator_role_updated', 'study_collaborators', $collaboratorId);
                
                echo json_encode(['success' => true, 'message' => 'Collaborator role updated']);
                
            } else {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'No valid update action provided']);
            }
            break;
            
        case 'DELETE':
            // Remove collaborator from study
            $data = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($data['collaborator_id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Collaborator ID required']);
                exit;
            }
            
            $collaboratorId = (int)$data['collaborator_id'];
            
            // Get collaborator details
            $stmt = $db->prepare("
                SELECT sc.*, s.user_id as study_owner_id
                FROM study_collaborators sc
                JOIN studies s ON sc.study_id = s.id
                WHERE sc.id = ?
            ");
            $stmt->execute([$collaboratorId]);
            $collaborator = $stmt->fetch();
            
            if (!$collaborator) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Collaborator not found']);
                exit;
            }
            
            // Check if user has permission to remove
            $canRemove = ($collaborator['study_owner_id'] == $userId) || 
                        ($collaborator['user_id'] == $userId) || 
                        canAccessAdminPanel();
            
            if (!$canRemove) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                exit;
            }
            
            // Remove collaborator
            $stmt = $db->prepare("DELETE FROM study_collaborators WHERE id = ?");
            $stmt->execute([$collaboratorId]);
            
            // Log activity
            logActivity('collaborator_removed', 'study_collaborators', $collaboratorId);
            
            echo json_encode(['success' => true, 'message' => 'Collaborator removed']);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
            break;
    }
    
} catch (Exception $e) {
    error_log("Collaborators API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
}
?>
