<?php
/**
 * Study Collaboration Requests API
 * OBGYN Research Platform
 */

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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Authentication required']);
    exit;
}

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

try {
    switch ($method) {
        case 'GET':
            // Get collaboration requests for a study
            $studyId = isset($_GET['study_id']) ? (int)$_GET['study_id'] : 0;

            if (!$studyId) {
                throw new Exception('Study ID required');
            }

            // Check if user owns the study or is admin
            $stmt = $db->prepare("SELECT creator_id FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();

            if (!$study || ($study['creator_id'] !== $userId && !isAdmin())) {
                throw new Exception('Access denied');
            }

            $stmt = $db->prepare("
                SELECT scr.*, u.first_name, u.last_name, u.email, u.profile_picture,
                       rp.specialization, rp.institution
                FROM study_collaboration_requests scr
                JOIN users u ON scr.requester_id = u.id
                LEFT JOIN researcher_profiles rp ON u.id = rp.user_id
                WHERE scr.study_id = ?
                ORDER BY scr.created_at DESC
            ");
            $stmt->execute([$studyId]);

            $requests = $stmt->fetchAll();
            echo json_encode(['success' => true, 'data' => $requests]);
            break;

        case 'POST':
            // Send collaboration request
            $studyId = isset($_POST['study_id']) ? (int)$_POST['study_id'] : 0;
            $message = sanitize($_POST['message'] ?? '');

            if (!$studyId) {
                throw new Exception('Study ID required');
            }

            // Check if study exists and is collaborative
            $stmt = $db->prepare("SELECT id, creator_id, is_collaborative FROM studies WHERE id = ?");
            $stmt->execute([$studyId]);
            $study = $stmt->fetch();

            if (!$study) {
                throw new Exception('Study not found');
            }

            if (!$study['is_collaborative']) {
                throw new Exception('This study does not accept collaborators');
            }

            if ($study['creator_id'] === $userId) {
                throw new Exception('Cannot request collaboration on your own study');
            }

            // Check if already a collaborator
            $stmt = $db->prepare("SELECT id FROM study_collaborators WHERE study_id = ? AND user_id = ?");
            $stmt->execute([$studyId, $userId]);
            if ($stmt->fetch()) {
                throw new Exception('Already a collaborator on this study');
            }

            // Check if request already exists
            $stmt = $db->prepare("
                SELECT id FROM study_collaboration_requests
                WHERE study_id = ? AND requester_id = ? AND status = 'pending'
            ");
            $stmt->execute([$studyId, $userId]);
            if ($stmt->fetch()) {
                throw new Exception('Collaboration request already pending');
            }

            // Create collaboration request
            $stmt = $db->prepare("
                INSERT INTO study_collaboration_requests (study_id, requester_id, message)
                VALUES (?, ?, ?)
            ");
            $stmt->execute([$studyId, $userId, $message]);

            // Log activity
            logActivity('collaboration_requested', 'studies', $studyId);

            echo json_encode(['success' => true, 'message' => 'Collaboration request sent successfully']);
            break;

        case 'PUT':
            // Respond to collaboration request
            $requestId = isset($_POST['request_id']) ? (int)$_POST['request_id'] : 0;
            $action = $_POST['action'] ?? ''; // approve or reject
            $responseMessage = sanitize($_POST['response_message'] ?? '');

            if (!$requestId || !in_array($action, ['approve', 'reject'])) {
                throw new Exception('Invalid request parameters');
            }

            // Get request and verify study ownership
            $stmt = $db->prepare("
                SELECT scr.*, s.creator_id, s.title
                FROM study_collaboration_requests scr
                JOIN studies s ON scr.study_id = s.id
                WHERE scr.id = ?
            ");
            $stmt->execute([$requestId]);
            $request = $stmt->fetch();

            if (!$request || ($request['creator_id'] !== $userId && !isAdmin())) {
                throw new Exception('Access denied');
            }

            if ($request['status'] !== 'pending') {
                throw new Exception('Request has already been responded to');
            }

            // Update request
            $status = $action === 'approve' ? 'approved' : 'rejected';
            $stmt = $db->prepare("
                UPDATE study_collaboration_requests
                SET status = ?, response_message = ?, responded_at = NOW(), responded_by = ?
                WHERE id = ?
            ");
            $stmt->execute([$status, $responseMessage, $userId, $requestId]);

            // If approved, add as collaborator
            if ($action === 'approve') {
                $stmt = $db->prepare("
                    INSERT INTO study_collaborators (study_id, user_id, role, status)
                    VALUES (?, ?, 'contributor', 'active')
                ");
                $stmt->execute([$request['study_id'], $request['requester_id']]);

                // Update collaborator count
                $stmt = $db->prepare("
                    UPDATE researcher_profiles
                    SET collaborations_count = collaborations_count + 1
                    WHERE user_id = ?
                ");
                $stmt->execute([$request['requester_id']]);
            }

            // Log activity
            logActivity('collaboration_request_' . $action . 'd', 'studies', $request['study_id']);

            echo json_encode(['success' => true, 'message' => 'Collaboration request ' . $action . 'd successfully']);
            break;

        case 'DELETE':
            // Delete collaboration request
            $requestId = isset($_GET['request_id']) ? (int)$_GET['request_id'] : 0;

            if (!$requestId) {
                throw new Exception('Request ID required');
            }

            // Delete request (only if user is involved)
            $stmt = $db->prepare("
                DELETE FROM study_collaboration_requests
                WHERE id = ? AND (requester_id = ? OR study_id IN (
                    SELECT id FROM studies WHERE creator_id = ?
                ))
            ");
            $stmt->execute([$requestId, $userId, $userId]);

            if ($stmt->rowCount() === 0) {
                throw new Exception('Collaboration request not found or access denied');
            }

            echo json_encode(['success' => true, 'message' => 'Collaboration request deleted successfully']);
            break;

        default:
            http_response_code(405);
            echo json_encode(['error' => 'Method not allowed']);
            break;
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
