<?php
/**
 * Study Collaboration Requests - Phase 7
 * OBGYN Research & Collaboration Platform
 */

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

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

$pageTitle = 'Study Collaboration Requests';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Handle approve/reject actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();

    $action = $_POST['action'] ?? '';
    $requestId = (int)($_POST['request_id'] ?? 0);
    $responseMessage = sanitize($_POST['response_message'] ?? '');

    if ($action === 'approve' && $requestId > 0) {
        try {
            $db = getDB();
            // First get the request details
            $stmt = $db->prepare("SELECT * FROM study_collaboration_requests WHERE id = ? AND study_id IN (SELECT id FROM studies WHERE creator_id = ?)");
            $stmt->execute([$requestId, $userId]);
            $request = $stmt->fetch();

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

                // Add to study_collaborators table
                $stmt = $db->prepare("INSERT INTO study_collaborators (study_id, user_id, role) VALUES (?, ?, 'collaborator')");
                $stmt->execute([$request['study_id'], $request['requester_id']]);

                $success = 'Collaboration request approved. The researcher has been added to your study.';
            } else {
                $error = 'Request not found or you do not have permission to approve it.';
            }
        } catch (Exception $e) {
            $error = 'Failed to approve collaboration request.';
        }
    } elseif ($action === 'reject' && $requestId > 0) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE study_collaboration_requests
                SET status = 'rejected', responded_at = NOW(), responded_by = ?, response_message = ?
                WHERE id = ? AND study_id IN (SELECT id FROM studies WHERE creator_id = ?)
            ");
            $stmt->execute([$userId, $responseMessage, $requestId, $userId]);
            $success = 'Collaboration request rejected.';
        } catch (Exception $e) {
            $error = 'Failed to reject collaboration request.';
        }
    }
}

// Get received collaboration requests (for studies I own)
$db = getDB();
$stmt = $db->prepare("
    SELECT scr.*, u.first_name, u.last_name, u.email, u.institution, u.specialization, u.profile_picture,
           s.title as study_title, s.id as study_id
    FROM study_collaboration_requests scr
    JOIN users u ON scr.requester_id = u.id
    JOIN studies s ON scr.study_id = s.id
    WHERE s.creator_id = ?
    ORDER BY scr.created_at DESC
");
$stmt->execute([$userId]);
$receivedRequests = $stmt->fetchAll();

// Get sent collaboration requests
$stmt = $db->prepare("
    SELECT scr.*, u.first_name, u.last_name, u.email, u.institution, u.specialization, u.profile_picture,
           s.title as study_title, s.id as study_id
    FROM study_collaboration_requests scr
    JOIN users u ON s.creator_id = u.id
    JOIN studies s ON scr.study_id = s.id
    WHERE scr.requester_id = ?
    ORDER BY scr.created_at DESC
");
$stmt->execute([$userId]);
$sentRequests = $stmt->fetchAll();

include '../templates/researcher-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-handshake"></i> Study Collaboration Requests</h1>
            </div>

            <?php if ($error): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?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" role="alert">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Received Requests Tab -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-inbox"></i> Received Requests (<?php echo count($receivedRequests); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($receivedRequests)): ?>
                        <p class="text-muted">No collaboration requests received yet.</p>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($receivedRequests as $request): ?>
                                <div class="col-md-6 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-2">
                                                <img src="<?php echo getProfilePictureUrl($request['profile_picture']); ?>"
                                                     class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                                <div>
                                                    <h6 class="mb-0"><?php echo e($request['first_name'] . ' ' . $request['last_name']); ?></h6>
                                                    <small class="text-muted"><?php echo e($request['institution']); ?></small>
                                                </div>
                                            </div>
                                            <p class="small text-muted mb-2"><?php echo e($request['specialization']); ?></p>
                                            <p class="small mb-1"><strong>Study:</strong> <?php echo e($request['study_title']); ?></p>
                                            <p class="small mb-2"><strong>Message:</strong> <?php echo e($request['message']); ?></p>
                                            <small class="text-muted d-block mb-3">
                                                Requested on <?php echo date('M d, Y', strtotime($request['created_at'])); ?>
                                            </small>

                                            <?php if ($request['status'] === 'pending'): ?>
                                                <div class="d-flex gap-2">
                                                    <button type="button" class="btn btn-sm btn-success"
                                                            onclick="respondToRequest(<?php echo $request['id']; ?>, 'approve')">
                                                        <i class="fas fa-check"></i> Approve
                                                    </button>
                                                    <button type="button" class="btn btn-sm btn-danger"
                                                            onclick="respondToRequest(<?php echo $request['id']; ?>, 'reject')">
                                                        <i class="fas fa-times"></i> Reject
                                                    </button>
                                                </div>
                                            <?php else: ?>
                                                <span class="badge bg-<?php echo $request['status'] === 'approved' ? 'success' : 'danger'; ?>">
                                                    <?php echo ucfirst($request['status']); ?>
                                                </span>
                                                <?php if ($request['response_message']): ?>
                                                    <p class="small mt-2"><strong>Your response:</strong> <?php echo e($request['response_message']); ?></p>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Sent Requests Tab -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-paper-plane"></i> Sent Requests (<?php echo count($sentRequests); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($sentRequests)): ?>
                        <p class="text-muted">No collaboration requests sent yet.</p>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($sentRequests as $request): ?>
                                <div class="col-md-6 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <div class="d-flex align-items-center mb-2">
                                                <img src="<?php echo getProfilePictureUrl($request['profile_picture']); ?>"
                                                     class="rounded-circle me-3" width="50" height="50" alt="Profile">
                                                <div>
                                                    <h6 class="mb-0"><?php echo e($request['first_name'] . ' ' . $request['last_name']); ?></h6>
                                                    <small class="text-muted"><?php echo e($request['institution']); ?></small>
                                                </div>
                                            </div>
                                            <p class="small text-muted mb-2"><?php echo e($request['specialization']); ?></p>
                                            <p class="small mb-1"><strong>Study:</strong> <?php echo e($request['study_title']); ?></p>
                                            <p class="small mb-2"><strong>Your message:</strong> <?php echo e($request['message']); ?></p>
                                            <small class="text-muted d-block mb-3">
                                                Sent on <?php echo date('M d, Y', strtotime($request['created_at'])); ?>
                                            </small>
                                            <span class="badge bg-<?php echo $request['status'] === 'approved' ? 'success' : ($request['status'] === 'rejected' ? 'danger' : 'warning'); ?>">
                                                <?php echo ucfirst($request['status']); ?>
                                            </span>
                                            <?php if ($request['response_message']): ?>
                                                <p class="small mt-2"><strong>Response:</strong> <?php echo e($request['response_message']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Response Modal -->
<div class="modal fade" id="responseModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Respond to Collaboration Request</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <?php echo csrfField(); ?>
                <input type="hidden" name="request_id" id="modalRequestId">
                <input type="hidden" name="action" id="modalAction">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="responseMessage" class="form-label">Response Message (Optional)</label>
                        <textarea class="form-control" id="responseMessage" name="response_message" rows="3"
                                  placeholder="Add a personal message with your response..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn" id="modalSubmitBtn">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function respondToRequest(requestId, action) {
    document.getElementById('modalRequestId').value = requestId;
    document.getElementById('modalAction').value = action;

    const modal = new bootstrap.Modal(document.getElementById('responseModal'));
    const submitBtn = document.getElementById('modalSubmitBtn');

    if (action === 'approve') {
        submitBtn.className = 'btn btn-success';
        submitBtn.innerHTML = '<i class="fas fa-check"></i> Approve Request';
    } else {
        submitBtn.className = 'btn btn-danger';
        submitBtn.innerHTML = '<i class="fas fa-times"></i> Reject Request';
    }

    modal.show();
}
</script>

<?php include '../templates/researcher-mobile-footer.php'; ?>
</body>
</html>
