{% extends 'layout.twig' %}
{% block body %}
    <style>
        #additional_emails > .col > div:nth-child(2) {
            display: none;
        }
        #additional_phones > .col > div:nth-child(2) {
            display: none;
        }
    </style>
    {% include 'nav.twig' %}
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">

    <div class="container mt-5">
        <div class="row flex-lg-nowrap justify-content-center">
            <div class="col-12 col-lg-10 mb-3">
                <div class="card">
                    <div class="card-body">

                        {# -- RESTORED CHANGE PHOTO MODAL -- #}
                        <div class="modal fade" id="changePhotoModal" tabindex="-1" role="dialog" aria-labelledby="changePhotoModalLabel" 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="changePhotoModalLabel">Change Profile Photo</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="uploadPhotoForm">
                                            <div class="form-group">
                                                <label for="photoInput">Upload New Photo</label>
                                                <input type="file" id="photoInput" name="profilepic" class="form-control-file" required>
                                            </div>

                                            <!-- PROGRESS BAR (starts hidden) -->
                                            <div class="progress" id="uploadProgressContainer" style="display: none; height: 20px;">
                                                <div id="uploadProgressBar" class="progress-bar" role="progressbar" style="
                                                                    transition: width .5s;     /* Optional smooth transition */
                                                                        white-space: nowrap;
                                                                        overflow: visible;
                                                                        min-width: 40px;
                                                                ">
                                                    0%
                                                </div>
                                            </div>

                                            <button type="submit" class="btn btn-primary mt-3">Upload</button>
                                        </form>

                                    </div>
                                </div>
                            </div>
                        </div>


                        {# -- RESTORED DELETE PHOTO MODAL -- #}
                        <div class="modal fade" id="deletePhotoModal" tabindex="-1" role="dialog" aria-labelledby="deletePhotoModalLabel" 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="deletePhotoModalLabel">Delete Profile Photo</h5>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                            <span aria-hidden="true">&times;</span>
                                        </button>
                                    </div>
                                    <div class="modal-body">
                                        <p>Are you sure you want to delete your profile photo? This action cannot be undone.</p>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                        <button type="button" class="btn btn-danger" id="confirmDeletePhoto">Delete</button>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <h4 class="mb-3 text-center">Profile Settings</h4>
                        <div class="e-profile">

                            <!-- USER INFO & PHOTO SECTION -->
                            <div class="text-center mb-4">
                                <div class="profile-img">
                                    <img style="width: 140px;"
                                         src="fileserver.php?folder=profile_pics&file=profile_{{userid}}"
                                         onerror="this.src='profile_pics/default'"
                                         class="rounded-circle img-thumbnail"/>
                                </div>
                                <div class="mt-2">
                                    <h4>{{ firstname }} {{ lastname }}</h4>
                                    <p class="text-muted">{{ username }}</p>
                                    <button class="btn btn-primary" data-toggle="modal" data-target="#changePhotoModal">
                                        Change Photo
                                    </button>
                                    <button class="btn btn-danger" data-toggle="modal" data-target="#deletePhotoModal">
                                        Delete Photo
                                    </button>
                                    <p class="text-muted mt-2">
                                        Note: Changes to your profile picture may take a while to update.
                                    </p>
                                </div>
                            </div>

                            <!-- FORM SECTION -->
                            <form class="form" novalidate="">
                                <h5 class="mb-3">Personal Information</h5>
                                <!-- (A) FIRST & LAST NAME -->
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="firstname">First Name</label>
                                            <input class="form-control" id="firstname" name="firstname"
                                                   value="{{ firstname }}" placeholder="Enter First Name">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="lastname">Last Name</label>
                                            <input class="form-control" id="lastname" name="lastname"
                                                   value="{{ lastname }}" placeholder="Enter Last Name">
                                        </div>
                                    </div>
                                </div>

                                <!-- (B) EMAIL -->
                                <h5 class="mb-3">Contact Information</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="email">Email</label>
                                            <input class="form-control" id="email" name="email"
                                                   value="{{ email }}" placeholder="Enter Email">
                                        </div>
                                    </div>
                                </div>

                                <!-- (C) ADDITIONAL EMAILS -->
                                <div class="mb-3">
                                    <h6>Additional Emails</h6>
                                    <div id="additional_emails">
                                        {% for e in 0..additional_emails|length - 1 %}
                                            <div class="form-group row">
                                                <div class="col-md-10">
                                                    <!-- Example: disable the first additional email (as you had) -->
                                                    <input class="form-control"
                                                           name="emails[]"
                                                           value="{{ additional_emails[e] }}"
                                                           placeholder="Enter Additional Email"
                                                            {% if e == 0 %} readonly {% endif %}>
                                                </div>
                                                <div class="col-md-2">
                                                    {% if e != 0 %}
                                                        <button class="btn btn-danger" type="button"
                                                                onclick="removeEmail(this)">Delete</button>
                                                    {% endif %}
                                                </div>
                                            </div>
                                        {% endfor %}
                                    </div>
                                    <button type="button" class="btn btn-secondary" id="add_email_button">
                                        Add Email
                                    </button>
                                </div>

                                <!-- (D) ADDITIONAL PHONES -->
                                <div class="mb-3">
                                    <h6>Additional Phone Numbers</h6>
                                    <div id="additional_phones">
                                        {% for p in 0..additional_phones|length - 1 %}
                                            <div class="form-group row">
                                                <div class="col-md-5">
                                                    <input class="form-control"
                                                           name="phones_name[]"
                                                           value="{{ additional_phones[p][0] }}"
                                                           placeholder="Phone Name">
                                                </div>
                                                <div class="col-md-5">
                                                    <input class="form-control"
                                                           name="phones_number[]"
                                                           value="{{ additional_phones[p][1] }}"
                                                           placeholder="Phone Number">
                                                </div>
                                                <div class="col-md-2">
                                                    <button class="btn btn-danger" type="button"
                                                            onclick="removePhone(this)">Delete</button>
                                                </div>
                                            </div>
                                        {% endfor %}
                                    </div>
                                    <button type="button" class="btn btn-secondary" id="add_phone_button">
                                        Add Phone
                                    </button>
                                </div>

                                <!-- (E) ADDRESS INFO -->
                                <h5 class="mb-3">Address Information</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="address_line_1">Address Line 1</label>
                                            <input class="form-control" id="address_line_1" name="address_line_1"
                                                   value="{{ address.address_line_1 }}"
                                                   placeholder="Enter Address Line 1">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="address_line_2">Address Line 2</label>
                                            <input class="form-control" id="address_line_2" name="address_line_2"
                                                   value="{{ address.address_line_2 }}"
                                                   placeholder="Enter Address Line 2">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="city">City</label>
                                            <input class="form-control" id="city" name="city"
                                                   value="{{ address.city }}" placeholder="Enter City">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="state">State</label>
                                            <input class="form-control" id="state" name="state"
                                                   value="{{ address.state }}" placeholder="Enter State">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="zipcode">Zipcode</label>
                                            <input class="form-control" id="zipcode" name="zipcode"
                                                   value="{{ address.zipcode }}" placeholder="Enter Zipcode">
                                        </div>
                                    </div>
                                </div>

                                <!-- (F) SAVE CHANGES BUTTON -->
                                <div class="text-center">
                                    <button type="button" id="save_button" class="btn btn-success">
                                        Save Changes
                                    </button>
                                </div>
                            </form>

                            {#
                            --------------------------------------------------------
                            ADD ADMIN-ONLY BOXES BELOW (for directors/admins)
                            --------------------------------------------------------
                            #}
                            {% if hasDirector %}
                                <!-- Wrap them in a row of 3 "cards" or "boxes" -->
                                <div class="row mt-4">
                                    <!-- (1) CHANGE PERMISSIONS BOX -->
                                    <div class="col-12 col-md-4 mb-3">
                                        <div class="card border-primary">
                                            <div class="card-header">
                                                <h5 class="mb-0">Change User Permissions</h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="form-group">
                                                    <label for="rankSelect">Select Rank</label>
                                                    <select id="rankSelect" class="form-control">
                                                        <option value="" {% if selectedRank is empty %}selected{% endif %}>No Rank</option>
                                                        <option value="member" {% if selectedRank == 'member' %}selected{% endif %}>Member</option>
                                                        <option value="alumni" {% if selectedRank == 'alumni' %}selected{% endif %}>Alumni</option>
                                                        <option value="admin" {% if selectedRank == 'admin' %}selected{% endif %}>Admin</option>
                                                        <option value="director" {% if selectedRank == 'director' %}selected{% endif %}>Director</option>
                                                    </select>
                                                </div>
                                                <button class="btn btn-primary" id="btnChangePermissions">
                                                    Update
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- (2) CHANGE PASSWORD BOX -->
                                    <div class="col-12 col-md-4 mb-3">
                                        <div class="card border-warning">
                                            <div class="card-header">
                                                <h5 class="mb-0">Change User Password</h5>
                                            </div>
                                            <div class="card-body">
                                                <div class="form-group">
                                                    <input type="password" id="adminNewPassword"
                                                           class="form-control mb-2"
                                                           placeholder="New Password">
                                                    <input type="password" id="adminConfirmPassword"
                                                           class="form-control mb-2"
                                                           placeholder="Confirm Password">
                                                </div>
                                                <button class="btn btn-warning" id="btnAdminChangePassword">
                                                    Change
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- (3) DELETE USER BOX -->
                                    <div class="col-12 col-md-4 mb-3">
                                        <div class="card border-danger">
                                            <div class="card-header">
                                                <h5 class="mb-0">Delete User</h5>
                                            </div>
                                            <div class="card-body">
                                                <p class="text-danger">
                                                    Deleting a user is permanent.
                                                </p>
                                                <button class="btn btn-danger" id="btnDeleteUser">
                                                    Delete User
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            {% endif %}
                            <!-- END ADMIN-ONLY BOXES -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="js/upload.js"></script>
{% endblock %}

{% block script %}
    <script>
        let emailData = [];  // Track email changes
        let phoneData = [];  // Track phone changes
        let otherData = {};  // Track changes to other fields
        const id = {{ userid }};  // The user whose profile we're editing

        // ==================== PHOTO UPLOAD & DELETION ==================== //
        // Change Photo
        $("#uploadPhotoForm").submit(async function (e) {
            e.preventDefault();

            const fileInput = $("#photoInput")[0];
            const file = fileInput.files[0];
            if (!file) {
                alert("Please select a photo to upload.");
                return;
            }

            // 1) Show the progress bar, reset it to 0% and visible
            $("#uploadProgressContainer").show();
            $("#uploadProgressBar").css("width", "0%").text("0%");

            try {
                // 2) Call uploadFile with a progressCallback
                $("#uploadProgressBar")
                    .css("width", 0 + "%")
                    .text(0 + "%");
                await uploadFile(file, "upload_profile_photo", {{ userid }}, function(progressPercentage, currentChunk, totalChunks) {
                    // 3) Update the progress bar
                    $("#uploadProgressBar")
                        .css("width", progressPercentage + "%")
                        .text(progressPercentage + "%");
                });

                location.reload();
            } catch (error) {
                alert("An error occurred while uploading the photo.");
                console.error("Upload error:", error);
            }
        });


        // Delete Photo
        $("#confirmDeletePhoto").click(function () {
            $.ajax({
                url: "api.php?method=delete_profile_photo",
                type: "POST",
                data: { id: id },
                success: function (response) {
                    if (response.status === 200) {
                        alert("Photo deleted successfully.");
                        location.reload();
                    } else {
                        alert("Failed to delete photo.");
                    }
                },
                error: function () {
                    alert("An error occurred while deleting the photo.");
                }
            });
        });

        // ==================== ADD / REMOVE EMAILS ==================== //
        $("#add_email_button").click(function () {
            const newEmailRow = `
                <div class="form-group row">
                    <div class="col-md-10">
                        <input class="form-control" name="emails[]" placeholder="Enter Additional Email">
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-danger" type="button" onclick="removeEmail(this)">Delete</button>
                    </div>
                </div>
            `;
            $("#additional_emails").append(newEmailRow);
        });
        function removeEmail(which) {
            $(which).closest('.form-group').remove();
        }

        // ==================== ADD / REMOVE PHONES ==================== //
        $("#add_phone_button").click(function () {
            const newPhoneRow = `
                <div class="form-group row">
                    <div class="col-md-5">
                        <input class="form-control" name="phones_name[]" placeholder="Phone Name">
                    </div>
                    <div class="col-md-5">
                        <input class="form-control" name="phones_number[]" placeholder="Phone Number">
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-danger" type="button" onclick="removePhone(this)">Delete</button>
                    </div>
                </div>
            `;
            $("#additional_phones").append(newPhoneRow);
        });
        function removePhone(which) {
            $(which).closest('.form-group').remove();
        }

        // ==================== TRACK CHANGES (OTHER FIELDS) ==================== //
        $("body").on('input', 'input[name="firstname"], input[name="lastname"], input[name="email"], input[name="address_line_1"], input[name="address_line_2"], input[name="city"], input[name="state"], input[name="zipcode"]', function () {
            const fieldName = $(this).attr("name");
            const fieldValue = $(this).val();
            otherData[fieldName] = fieldValue;
            $(this).css("background", "yellow");
        });

        // ==================== COLLECT EMAILS & PHONES WHEN SAVING ==================== //
        function collectEmails() {
            let emails = $("input[name='emails[]']").map(function () {
                return $(this).val().trim();
            }).get();
            emailData = emails.filter(email => email !== "");
        }
        function collectPhones() {
            let phoneNames = $("input[name='phones_name[]']").map(function () {
                return $(this).val().trim();
            }).get();
            let phoneNumbers = $("input[name='phones_number[]']").map(function () {
                return $(this).val().trim();
            }).get();
            phoneData = [];
            for (let i = 0; i < phoneNames.length; i++) {
                if (phoneNames[i] !== "" && phoneNumbers[i] !== "") {
                    phoneData.push([phoneNames[i], phoneNumbers[i]]);
                }
            }
        }

        // ==================== SAVE CHANGES (PROFILE) ==================== //
        $("#save_button").click(function () {
            collectEmails();
            collectPhones();

            let postData = {
                id: id,
                emails: emailData,
                phones: phoneData,
                ...otherData
            };
            if (Object.keys(postData).length <= 1) {
                alert("No changes to save.");
                return;
            }
            $.post("api.php?method=edit_profile", postData, function (res) {
                console.log(res);
                if (res.status == 200) {
                    alert("Changes saved successfully.");
                    $("input").css("background", "");
                    otherData = {};
                } else {
                    alert("Failed to save changes.");
                    console.log(res);
                }
            }).fail(function (err) {
                alert("Something went wrong during the save process.");
                console.log(err);
            });
        });

        // =========================================================================
        // =                       ADMIN-ONLY OPERATIONS                           =
        // =========================================================================

        // (1) CHANGE PERMISSIONS
        $("#btnChangePermissions").click(function () {
            let selectedRank = $("#rankSelect").val();
            let data = { id: id };
            if (selectedRank) {
                data[selectedRank] = "true";
            }
            $.post("api.php?method=change_permissions", data, function (res) {
                console.log(res);
                if (res.status === 200) {
                    alert("Permissions updated successfully.");
                } else {
                    alert("Failed to update permissions.");
                }
            }).fail(function (err) {
                alert("An error occurred while updating permissions.");
                console.log(err);
            });
        });

        // (2) CHANGE PASSWORD (admin sets password for user)
        $("#btnAdminChangePassword").click(function () {
            let newPass = $("#adminNewPassword").val().trim();
            let confirmPass = $("#adminConfirmPassword").val().trim();

            if (!newPass || !confirmPass) {
                alert("Please fill out both password fields.");
                return;
            }
            if (newPass !== confirmPass) {
                alert("Passwords do not match.");
                return;
            }

            $.post("api.php?method=change_password", {
                id: id,
                password: newPass,
                password_confirm: confirmPass
            }, function (res) {
                if (res.status === 200) {
                    alert("Password changed successfully.");
                } else {
                    alert("Failed to change password.");
                }
            }).fail(function (err) {
                alert("Error while trying to change password.");
                console.log(err);
            });
        });

        // (3) DELETE USER
        $("#btnDeleteUser").click(function () {
            if (!confirm("Are you sure you want to delete this user? This action cannot be undone.")) {
                return;
            }
            $.post("api.php?method=delete_user", { id: id }, function (res) {
                if (res.status === 200) {
                    alert("User deleted successfully.");
                    // Possibly redirect somewhere, e.g.:
                    window.location.href = "/modify_users.php";
                } else {
                    alert("Failed to delete user.");
                }
            }).fail(function (err) {
                alert("Error while trying to delete user.");
                console.log(err);
            });
        });
    </script>
{% endblock %}
