<?php
/**
 * Group Chats - Phase 7
 * OBGYN Research & Collaboration Platform
 */

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

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

$pageTitle = 'Group Chats';
$userId = getCurrentUserId();
$error = '';
$success = '';

// Handle create group chat
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create_group') {
    validateCSRF();

    $groupName = sanitize($_POST['group_name'] ?? '');
    $description = sanitize($_POST['description'] ?? '');
    $isPrivate = isset($_POST['is_private']) ? 1 : 0;
    $memberIds = $_POST['members'] ?? [];

    if (empty($groupName)) {
        $error = 'Group name is required.';
    } elseif (count($memberIds) < 1) {
        $error = 'Please select at least one member.';
    } else {
        try {
            $db = getDB();

            // Create group chat
            $stmt = $db->prepare("INSERT INTO group_chats (name, description, created_by, is_private) VALUES (?, ?, ?, ?)");
            $stmt->execute([$groupName, $description, $userId, $isPrivate]);
            $groupId = $db->lastInsertId();

            // Add creator as admin
            $stmt = $db->prepare("INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, 'admin')");
            $stmt->execute([$groupId, $userId]);

            // Add selected members
            foreach ($memberIds as $memberId) {
                $stmt = $db->prepare("INSERT INTO group_members (group_id, user_id, role) VALUES (?, ?, 'member')");
                $stmt->execute([$groupId, (int)$memberId]);
            }

            $success = 'Group chat created successfully!';
        } catch (Exception $e) {
            $error = 'Failed to create group chat.';
        }
    }
}

// Get user's group chats
$db = getDB();
$stmt = $db->prepare("
    SELECT gc.*, gm.role,
           COUNT(DISTINCT gm2.user_id) as member_count,
           COUNT(DISTINCT m.id) as message_count,
           MAX(m.created_at) as last_message_time
    FROM group_chats gc
    JOIN group_members gm ON gc.id = gm.group_id
    LEFT JOIN group_members gm2 ON gc.id = gm2.group_id
    LEFT JOIN messages m ON gc.id = m.group_id
    WHERE gm.user_id = ?
    GROUP BY gc.id
    ORDER BY last_message_time DESC, gc.created_at DESC
");
$stmt->execute([$userId]);
$groupChats = $stmt->fetchAll();

// Get potential members (researchers user can add)
$stmt = $db->prepare("
    SELECT u.id, u.first_name, u.last_name, u.institution, u.specialization, u.profile_picture
    FROM users u
    WHERE u.id != ? AND u.role = 'researcher' AND u.status = 'active'
    ORDER BY u.first_name, u.last_name
");
$stmt->execute([$userId]);
$potentialMembers = $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-users-cog"></i> Group Chats</h1>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createGroupModal">
                    <i class="fas fa-plus"></i> Create Group
                </button>
            </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; ?>

            <!-- Group Chats List -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-comments"></i> Your Group Chats (<?php echo count($groupChats); ?>)</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($groupChats)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-users fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No Group Chats Yet</h5>
                            <p class="text-muted">Create your first group chat to start collaborating with multiple researchers at once.</p>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createGroupModal">
                                <i class="fas fa-plus"></i> Create Your First Group
                            </button>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($groupChats as $group): ?>
                                <div class="col-md-6 col-lg-4 mb-3">
                                    <div class="card h-100">
                                        <div class="card-body">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <h6 class="mb-1"><?php echo e($group['name']); ?></h6>
                                                <span class="badge bg-<?php echo $group['role'] === 'admin' ? 'primary' : 'secondary'; ?>">
                                                    <?php echo ucfirst($group['role']); ?>
                                                </span>
                                            </div>
                                            <?php if ($group['description']): ?>
                                                <p class="small text-muted mb-2"><?php echo e($group['description']); ?></p>
                                            <?php endif; ?>
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <small class="text-muted">
                                                    <i class="fas fa-users"></i> <?php echo $group['member_count']; ?> members
                                                </small>
                                                <small class="text-muted">
                                                    <i class="fas fa-comments"></i> <?php echo $group['message_count']; ?> messages
                                                </small>
                                            </div>
                                            <?php if ($group['last_message_time']): ?>
                                                <small class="text-muted d-block mb-3">
                                                    Last activity: <?php echo date('M d, Y H:i', strtotime($group['last_message_time'])); ?>
                                                </small>
                                            <?php endif; ?>
                                            <div class="d-flex gap-2">
                                                <a href="messages-enhanced.php?group_id=<?php echo $group['id']; ?>" class="btn btn-sm btn-primary">
                                                    <i class="fas fa-comments"></i> Open Chat
                                                </a>
                                                <?php if ($group['role'] === 'admin'): ?>
                                                    <button type="button" class="btn btn-sm btn-outline-secondary"
                                                            onclick="manageGroup(<?php echo $group['id']; ?>)">
                                                        <i class="fas fa-cog"></i> Manage
                                                    </button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Create Group Modal -->
<div class="modal fade" id="createGroupModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create New Group Chat</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <?php echo csrfField(); ?>
                <input type="hidden" name="action" value="create_group">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="groupName" class="form-label">Group Name *</label>
                        <input type="text" class="form-control" id="groupName" name="group_name" required
                               placeholder="Enter group name">
                    </div>
                    <div class="mb-3">
                        <label for="groupDescription" class="form-label">Description (Optional)</label>
                        <textarea class="form-control" id="groupDescription" name="description" rows="2"
                                  placeholder="Describe the purpose of this group"></textarea>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="isPrivate" name="is_private">
                            <label class="form-check-label" for="isPrivate">
                                Private Group
                            </label>
                            <small class="form-text text-muted">Private groups require invitation to join</small>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Add Members *</label>
                        <div class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                            <?php foreach ($potentialMembers as $member): ?>
                                <div class="form-check mb-2">
                                    <input class="form-check-input" type="checkbox" name="members[]"
                                           value="<?php echo $member['id']; ?>" id="member_<?php echo $member['id']; ?>">
                                    <label class="form-check-label d-flex align-items-center" for="member_<?php echo $member['id']; ?>">
                                        <img src="<?php echo getProfilePictureUrl($member['profile_picture']); ?>"
                                             class="rounded-circle me-2" width="30" height="30" alt="Profile">
                                        <div>
                                            <div><?php echo e($member['first_name'] . ' ' . $member['last_name']); ?></div>
                                            <small class="text-muted"><?php echo e($member['institution']); ?></small>
                                        </div>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <small class="form-text text-muted">Select at least one member to add to the group</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Group</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function manageGroup(groupId) {
    // TODO: Implement group management functionality
    alert('Group management functionality will be implemented in the next update.');
}
</script>

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