<% function isValidHttpUrl(string) {
    try {
      const url = new URL(string);
      return url.protocol === 'http:' || url.protocol === 'https:';
    } catch (err) {
      return false;
    }
} %> 
<%-include ('./header')%>
    <div class="container">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <button type="button" class="btn btn-primary my-2 mx-2" data-toggle="modal" data-target="#groupsModal">
                    <i class="fa-regular fa-clipboard mr-2"></i>View My Projects
                </button>

                <div class="profile-card">
                    <button type="button" class="btn btn-dark float-right" data-toggle="modal" data-target="#passwordChangeModal">
                        <i class="fa-solid fa-key "></i> Change Password
                    </button>
                    <h2 class="text-center mb-4" style="margin-left: 10rem;"><i class="fa-solid fa-user-tie mr-2 fa-sm"></i>User Profile</h2>
                    <hr>
                    <div class="profile-picture">
                        <img src="<%= user.profileImage %>" alt="No Profile Picture">
                    </div>
                    <div class="user-details">
                        <strong>User ID:</strong> <%= user.userId %> <br>
                        <strong>Username:</strong> <%= user.userName %> <br>                  
                        <strong>Email:</strong> <%= user.userEmail %> <br>
                        <% if (user.userRoll) { %>
                            <strong>Roll:</strong> <%= user.userRoll %> <br>
                        <% } %>
                        <% if (user.userDepartment) { %>
                            <strong>Department:</strong> <%= user.userDepartment %> <br>
                        <% } %>
                        <% if (user.degree.length >0) { %>
                            <strong>Degree:</strong> |
                            <% user['degree'].forEach(degree => { %>
                                <%= degree %> | 
                            <% }) %>
                            <br>
                        <% } %>
                        
                        <% if (user.passout) { %>
                            <strong>Passout:</strong> <%= user.passout.toISOString().split('T')[0] %> <br>
                        <% } %>
                        <strong>Bio:</strong> <%= user.bio %> <br>
                        <%for(df of user['dynamicFields']){%>
                            <strong><%= df.field %>:</strong>
                            <% if (isValidHttpUrl(df.value)) { %>
                                <a href="<%= df.value %>" target="_blank">Click Here</a>
                            <% } else { %>
                                <%= df.value %>
                            <% } %>                            
                            <br>
                        <% } %>
                    </div>
                    <a href="/profile/edit"><button class="btn btn-warning edit-btn">
                        <i class="fa-solid fa-pencil mr-2"></i>Edit</button>
                    </a>
                    <button class="btn btn-danger edit-btn" style="float: right;" onclick="deleteProfile()">
                        <i class="fa-solid fa-trash-can mr-2"></i>Delete</button>
                </div>
            </div>
        </div>

        <!-- Change Password Modal -->
        <div class="modal fade invite-modal" id="passwordChangeModal" tabindex="-1" role="dialog" aria-labelledby="passwordChangeModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                <h5 class="modal-title" id="passwordChangeModalLabel">Change Password</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                </div>
                <div class="modal-body">
                <form id="passwordChangeForm">
                    <div class="form-group">
                    <label for="currentPassword">Current Password</label>
                    <input type="password" class="form-control" id="currentPassword" name="currentPassword" required>
                    </div>
                    <div class="form-group">
                    <label for="newPassword">New Password</label>
                    <input type="password" class="form-control" id="newPassword" name="newPassword" required>
                    </div>
                    <div class="form-group">
                    <label for="confirmNewPassword">Confirm New Password</label>
                    <input type="password" class="form-control" id="confirmNewPassword" name="confirmNewPassword" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Change Password</button>
                </form>
                </div>
            </div>
            </div>
        </div>
        
        <!-- My Groups Modal -->
        <div class="modal fade invite-modal" id="groupsModal" tabindex="-1" role="dialog" aria-labelledby="groupsModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="groupsModalLabel"> 
                            <i class="fa-solid fa-clipboard mr-2 fa-sm"></i>My Projects</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <!-- Group Cards -->
                        <div class="container">
                            <% for(const group of myGroups) { %>
                                <div class="group-card">
                                    <div class="group-details">
                                        <strong>Project ID:</strong> <%= group.groupId %> <br>
                                        <strong>Project Name:</strong> <%= group.groupName %><br>
                                        <strong>Admin:</strong> <%= group.adminId %>
                                        <a href="/group/dashboard?groupId=<%= group.groupId %>">
                                            <button class="btn btn-primary" style="float: right;">
                                                <i class="fa-solid fa-sitemap mr-2"></i>View Dashboard</button>
                                        </a>
                                    </div>
                                </div>
                            <% } %>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary btn-close-modal" data-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    

    </div>
<%-include ('./footer')%>

<script>
    const query=<%- query %>;
    if(query.editProfile=='success')
        Swal.fire({
            title: 'Yay!',
            text: 'Profile Edited Successfully',
            icon: 'success',
            confirmButtonText: 'OK'
        })

    if(query.editProfile=='failure')
        Swal.fire({
            title: 'Oops!',
            text: 'Profile Edit Failed',
            icon: 'error',
            confirmButtonText: 'OK'
        })
</script>

<script>
    // Add an event listener to each navigation link
    $(document).ready(function(){
        // Remove 'active' class from all navigation links
        $(".navbar-nav .nav-link").removeClass("active");
        // Add 'active' class to the clicked navigation link
        $('#myProfile').addClass("active");
    });
</script>

<script>
    function deleteProfile(event) {
        Swal.fire({
            title: 'Are You sure?',
            text: 'Your Profile will be Deleted',
            icon: 'warning',
            confirmButtonText: 'OK'
        })
        .then((result)=>{
            if(result.isConfirmed)
                window.location.href='/profile/delete'
        });
    }
</script>

<!-- PAssword Change Script -->

<script>
    $('#passwordChangeForm').submit(async function(e) {
        e.preventDefault();
        var currentPassword = $('#currentPassword').val();
        var newPassword = $('#newPassword').val();
        var confirmNewPassword = $('#confirmNewPassword').val();

        if(newPassword!==confirmNewPassword)
        {
            Swal.fire({
                    title: 'Error!',
                    text: 'Passwords Dont match',
                    icon: 'error',
                    confirmButtonText: 'OK'
                })
        }
        else
        {
            let response=await fetch('/profile/passwordChange',{
                method:"POST",
                headers:{
                    "Content-Type":"application/json"
                },
                body:JSON.stringify({
                    currentPassword,newPassword
                })
            })
            response=await response.json()
            console.log(response);
            if(response.msg=="success")
                Swal.fire({
                    title: 'Done!',
                    text: 'Password Changed Successfully',
                    icon: 'success',
                    confirmButtonText: 'OK'
            })
            else if(response.msg=="failure")
                Swal.fire({
                    title: 'Invalid Password!',
                    text: 'Password change Failed!',
                    icon: 'error',
                    confirmButtonText: 'OK'
                })
            else
                Swal.fire({
                    title: 'Server Error!',
                    text: 'Something Went Wrong',
                    icon: 'error',
                    confirmButtonText: 'OK'
                })

            $('#passwordChangeModal').modal('hide');
            $('#passwordChangeForm')[0].reset();
        }
    });
</script>