<% console.log(user.degree); %>
<%-include ('./header')%>
    <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-pen mr-2"></i>Edit My Profile</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="/profile/edit" enctype="multipart/form-data" id="userForm">
                            <!-- 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="<%= user.profileImage %>" alt="Profile Image Preview">
                            </div>
                            <!-- Remaining fields -->
                            <div class="form-group">
                                <label for="userId">UserID:</label>
                                <input type="text" class="form-control" id="userId" name="userId" value="<%= user.userId %>" readonly>
                            </div>
                            <div class="form-group">
                                <label for="username">Name:</label>
                                <input type="text" class="form-control" id="username" name="username" value="<%= user.userName %>" required>
                            </div>
                            <div class="form-group">
                                <label for="email">Email:</label>
                                <input type="email" class="form-control" id="email" name="email" value="<%= user.userEmail %>" required>
                            </div>
                            <div class="form-group">
                                <label for="roll">Roll (Optional):</label>
                                <input type="number" class="form-control" id="roll" name="roll" value="<%= user.userRoll %>">
                            </div>
                            <div class="form-group">
                                <label for="department">Department:</label>
                                <input type="text" class="form-control" id="department" name="department" value="<%= user.userDepartment %>">
                            </div>

                            <div class="form-group">
                                <label for="degree">Degree:</label>
                                <select name="degree" id="degree" class="custom-select" multiple>
                                    <option value="B.Sc" <%= (user.degree.includes('B.Sc')) ? 'selected' : ''%> >B.Sc</option>
                                    <option value="M.Sc" <%= (user.degree.includes('M.Sc')) ? 'selected' : ''%> >M.Sc</option>
                                    <option value="B.Tech" <%= (user.degree.includes('B.Tech')) ? 'selected' : ''%> >B.Tech</option>
                                    <option value="M.Tech" <%= (user.degree.includes('M.Tech')) ? 'selected' : ''%> >M.Tech</option>
                                    <option value="MCA" <%= (user.degree.includes('MCA')) ? 'selected' : ''%>  >M.C.A</option>
                                    <option value="B.E" <%= (user.degree.includes('B.E')) ? 'selected' : ''%> >B.E.</option>
                                    <option value="M.E" <%= (user.degree.includes('M.E')) ? 'selected' : ''%> >M.E.</option>
                                    <option value="PhD" <%= (user.degree.includes('PhD')) ? 'selected' : ''%> >PhD</option>
                                </select>
                            </div>
                            <% if (user.passout) { %>
                                <div class="form-group">
                                    <label for="passout">Passout:</label>
                                    <input type="date" class="form-control" id="passout" name="passout" value="<%= user.passout.toISOString().split('T')[0] %>">
                                </div>
                            <% } %>
                            <div class="form-group">
                                <label for="bio">Bio:</label>
                                <textarea class="form-control" id="bio" name="bio" rows="3" required><%= user.bio %></textarea>
                            </div>
                            <!-- Add more fields button -->
                            <button type="button" class="btn btn-warning mb-3" id="addFieldBtn">
                                <i class="fa-solid fa-plus mr-2"></i>Add More Fields
                            </button>
                            <!-- Dynamic fields container -->
                            <div id="dynamicFieldsContainer">
                                <!-- Dynamic FIELDS ADDED HERE!! -->
                                <% fieldCounter=1%>
                                <% for(df of user['dynamicFields']) { %>
                                    <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="Enter Label"  style="font-weight: bold;" 
                                            value="<%= df.field %>">
                                        <input type="text" class="form-control" id="dynamicFieldValue<%= fieldCounter %>" 
                                            name="value<%= fieldCounter %>" placeholder="Enter Value"
                                            value="<%= df.value %>">
                                    </div>
                                    <% fieldCounter++ %>
                                <% } %>
                                <span style="display:none" id="noOfFields"><%= fieldCounter %></span>
                            </div>

                            <button type="submit" class="btn btn-primary btn-register" id="submitBtn">
                                <i class="fa-solid fa-floppy-disk mr-1"></i>Save Changes
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
<%-include ('./footer')%>

<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]);
        }
    }

    fieldCounter = $('#noOfFields').text()
    // 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();
    }

    // Event listener for Add More Fields button
    $("#addFieldBtn").click(function () {
        addDynamicField();
    });

</script>
