<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Community Homepage</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/1.1.2/css/bootstrap-multiselect.min.css"/>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fa-solid fa-user-plus mr-2 fa-sm"></i>User Registration</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="/profile/create" enctype="multipart/form-data">
                            <!-- Existing fields -->

                            <!-- Add image upload field -->
                            <div class="form-group">
                                <label for="profileImage">Profile Image:</label>
                                <input type="file" class="form-control-file" id="profileImage" name="profileImage"
                                 accept="image/*" onchange="checkFileSizeAndType()">
                            </div>
                            <!-- Image preview -->
                            <div id="imagePreviewContainer" class="text-center">
                                <img id="profileImagePreview" src="#" alt="Profile Image Preview">
                            </div>
                            <!-- Remaining fields -->
                            <div class="form-group">
                                <label for="userId">UserID:</label>
                                <span class="text-muted mx-2">*UserID cannot be changed once set*</span> 
                                <input type="text" class="form-control" id="userId" name="userId" required>
                                <span id="duplicateUserId" style="display: none; color: red;">*This UserID is already taken*</span>
                                <span id="alphaWarning" style="display: none; color: red;">*Only Alphanumeric Characters Allowed*</span>
                            </div>
                            <div class="form-group">
                                <label for="username">Name:</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" id="email" name="email" required>
                            </div>
                            <div class="form-group">
                                <label for="password">Password:</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            <div class="form-group">
                                <label for="roll">Roll:</label>
                                <input type="number" class="form-control" id="roll" name="roll" required>
                            </div>
                            <div class="form-group">
                                <label for="department">Department:</label>
                                <input type="text" class="form-control" id="department" name="department" required>
                            </div>
                            <div class="form-group">
                                <label for="degree">Degree:</label>
                                <span class="text-muted">*Select all of your Degrees*</span><br>
                                <select name="degree" id="degree" class="custom-select" multiple required>
                                    <option value="B.Sc">B.Sc</option>
                                    <option value="M.Sc">M.Sc</option>
                                    <option value="B.Tech">B.Tech</option>
                                    <option value="M.Tech">M.Tech</option>
                                    <option value="MCA">M.C.A</option>
                                    <option value="B.E">B.E.</option>
                                    <option value="M.E">M.E.</option>
                                    <option value="PhD">PhD</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="passout">Passout:</label>
                                <input type="date" class="form-control" id="passout" name="passout" required>
                            </div>
                            <div class="form-group">
                                <label for="bio">Bio:</label>
                                <textarea class="form-control" id="bio" name="bio" style="min-height:100px" required></textarea>
                            </div>
                            <div class="form-group">
                                <label for="joinGroup">Join Project:</label>
                                <select name="joinGroup" id="joinGroup" class="custom-select">
                                    <% for( group of groups ) { %>
                                        <option value="<%= group.groupId %>"><%= group.groupName %></option>
                                    <% } %>
                                </select>
                            </div>

                            <!-- Add more fields button -->
                            <button type="button" class="btn btn-warning mb-3" id="addFieldBtn" onclick="addDynamicField()">
                                <i class="fa-solid fa-plus mr-2"></i>Add More Fields
                            </button>
                            <!-- Dynamic fields container -->
                            <div id="dynamicFieldsContainer">
                                <!-- Dynamic FIELDS ADDED HERE!! -->
                                
                            </div>

                            <button type="submit" class="btn btn-primary btn-register">
                                <i class="fa-solid fa-pen-to-square mr-2"></i>Register
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/js/all.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/1.1.2/js/bootstrap-multiselect.min.js"></script>
</body>
</html>

<script>

    // Bootstrap MultiSelect
    $(document).ready(function() {
        $('#degree').multiselect({
          includeSelectAllOption: false,
        });
    });

    // file size limit
    function checkFileSizeAndType() 
    {
        const input=document.getElementById('profileImage');
        if (input.files && input.files[0]) 
        {
            var fileSize = input.files[0].size; // Size in bytes
            var maxSize = 1048576; // 1MB in bytes
            if (fileSize > maxSize) 
            {
                Swal.fire({
                    title: 'File Size Limit Exceeded!',
                    text: "Please choose a smaller file. (< 1MB)",
                    icon: 'warning',
                    confirmButtonText: 'OK'
                })
                input.value = ''; // Clear the selected file
            }
            else if(!input.files[0].type.includes('image/')){
                Swal.fire({
                    title: 'Incorrect File Type!',
                    text: "Upload Images ONLY",
                    icon: 'warning',
                    confirmButtonText: 'OK'
                })
                input.value = ''; // Clear the selected file
            }
            else{
                previewImage();
            }
        }
    }

    // Function to preview selected image
    function previewImage() {
        const fileInput = document.getElementById('profileImage');
        const imagePreview = document.getElementById('profileImagePreview');

        if (fileInput.files && fileInput.files[0]) {
            const reader = new FileReader();

            reader.onload = function (e) {
                imagePreview.src = e.target.result;
            };

            reader.readAsDataURL(fileInput.files[0]);
        }
    }

    // Counter for dynamic fields
    let fieldCounter = 0;

    // Function to add dynamic fields
    function addDynamicField() {
        fieldCounter++;
        let fieldHtml = `<div class="form-group" id="dynamicField${fieldCounter}">  
                            <label for="${fieldCounter}">
                                Dynamic Field:
                            </label>
                            <button type="button" class="btn btn-danger btn-sm float-right" onclick="deleteDynamicField(${fieldCounter})">
                                <i class="fa-solid fa-trash-can "></i>
                            </button>
                            <input type="text" class="form-control" id="dynamicFieldLabel${fieldCounter}" 
                            name="${fieldCounter}" placeholder="E.g. : My Github " style="font-weight: bold;" required>
                            <input type="text" class="form-control" id="dynamicFieldValue${fieldCounter}" 
                            name="value${fieldCounter}" placeholder="E.g. : https://gihub.com/coder" required>
                        </div>`;
        $("#dynamicFieldsContainer").append(fieldHtml);

    }

    // delete DF
    function deleteDynamicField(fieldIndex) {
        $("#dynamicField" + fieldIndex).remove();
    }

    // duplicate userId warning
    document.getElementById('userId').addEventListener('input', (event) => {
        const userIds = <%- JSON.stringify(userIds) %>;
        const inputValue = document.getElementById('userId').value;
        console.log(inputValue);
        const duplicateUserIdSpan = document.getElementById('duplicateUserId');
        const alphaWarning=document.getElementById('alphaWarning');
        if (userIds.includes(inputValue.toLowerCase())) 
            duplicateUserIdSpan.style.display = 'block';
        else 
            duplicateUserIdSpan.style.display = 'none';

        if (!/^[a-zA-Z0-9]+$/.test(inputValue))
            alphaWarning.style.display="block"
        else
            alphaWarning.style.display="none"
    });

</script>
