<% function isValidHttpUrl(string) {
    try {
      const url = new URL(string);
      return url.protocol === 'http:' || url.protocol === 'https:';
    } catch (err) {
      return false;
    }
} %> 
<div id="group_members" class="tab-pane">
    <!-- Button to Open Modal -->
    <% if (currUser.admin) { %>
        <div style="display: flex; justify-content: flex-end;">
            <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#inviteModal">
                <i class="fa-solid fa-user-plus mr-2"></i>Add Members
            </button>
        </div>
    <%}%>

    <!-- Get Members of group -->
    <% for(member of members) { %>
        <div class="card">
            <div class="card-body row" id="<%= member.userId %>">
                <div class="profile-picture col-2" style="margin-bottom: 0px;">
                    <img src="<%= member.profileImage %>" alt="Profile Picture">
                </div>
                <div class="col-6" style="align-content: center;">
                    <h5 style="font-weight: 700;" class="card-title">
                        <%= member.userName %>
                    </h5>
                    <h6>|
                        <% member['degree'].forEach(degree => { %>
                            <%= degree %> | 
                        <% }) %>
                    </h6>
                    <strong>Email:</strong> <%= member.userEmail %> <br>
                    <% if (member.passout) { %>
                        <% let passoutArr=member.passout.toDateString().split(" ") %>
                        <strong>Passout:</strong> 
                        <%= `${passoutArr[1]}, ${passoutArr[3]}` %> 
                    <% } %>
                </div>
                <div class="col-4" style="align-content: center;">
                    <div style="float: right;" class="mx-2 mt-2" >
                        <button class="btn btn-primary" data-toggle="modal" data-target="#userModal<%= member.userId %>">
                            <i class="fa-solid fa-circle-info mr-2"></i>Details
                        </button>
                    </div>
                    <% if (currUser.admin) { %>
                        <div style="float: right;">
                            <a href="/members/delete?userId=<%= member.userId%>&groupId=<%= group.groupId %>">
                                <button class="btn btn-danger btn-block my-2" 
                                    id="delete-member-button">
                                    <i class="fa-solid fa-user-minus mr-2"></i>Remove</button>
                            </a>
                        </div>
                    <% } %>
                </div>
            </div>
        </div>
        
        <div class="modal fade invite-modal" id="userModal<%= member.userId %>" tabindex="-1" role="dialog" aria-labelledby="userModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="userModalLabel">User Details</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="profile-card">
                            <h2 class="text-center mb-4"><i class="fa-regular fa-user mr-2 fa-sm"></i>User Profile</h2>
                            <hr>
                            <div class="profile-picture">
                                <img src="<%= member.profileImage %>" alt="Profile Picture">
                            </div>
                            <div class="user-details">
                                <strong>Username:</strong> <%= member.userName %> <br>
                                <strong>Email:</strong> <%= member.userEmail %> <br>
                                <strong>Roll:</strong> <%= member.userRoll %> <br>
                                <strong>Department:</strong> <%= member.userDepartment %> <br>
                                <strong>Bio:</strong> <%= member.bio %> <br>
                                <% for (df of member['dynamicFields']) { %>
                                    <strong><%= df.field %>:</strong> 
                                    <% if (isValidHttpUrl(df.value)) { %>
                                        <a href="<%= df.value %>" target="_blank">Click Here</a>
                                    <% } else { %>
                                        <%= df.value %>
                                    <% } %>
                                    <br>
                                <% } %>
                                
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    <% } %>
</div>

<!-- Invite Modal -->
<div class="modal fade invite-modal" id="inviteModal" tabindex="-1" role="dialog" aria-labelledby="inviteModalLabel"
aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="inviteModalLabel">Add Members to Group</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <% for(nonMember of nonMembers) { %>
                    <div class="invite-card">
                        <input type="checkbox" id="<%= nonMember.userId %>" name="inviteUsers"
                            value="<%= nonMember.userId %>">
                        <label for="<%= nonMember.userId %>">
                            - User ID: <%= nonMember.userId %> <br />
                            - Username: <%= nonMember.userName %> <br />
                            - Department: <%= nonMember.userDepartment %><br />
                        </label>
                    </div>
                <% } %>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn invite-btn"
                    onclick="addMembers('<%= group.groupId%>','<%= group.adminId%>')">Add Members</button>
            </div>
        </div>
    </div>
</div>

<script>
    async function addMembers(groupId, adminId) {
        try {
            const users = [];
            const items = document.getElementsByName('inviteUsers');
            for (item of items) {
                if (item.checked)
                    users.push(item.value);
            }
            console.log(users);
            let response = await fetch('/members/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ users, groupId, adminId })
            })
            response = await response.json();
            $('#inviteModal').modal('hide');
            if(response.success)
                window.location.href = `/group/dashboard?groupId=${groupId}&memberAdd=success`
            else
                window.location.href = `/group/dashboard?groupId=${groupId}&memberAdd=failure`
        }

        catch (err) {
            console.log(err.message);
        }
    }
</script>
