<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Profile</title>
    <%- include('../partials/_favicon') %>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css">
    <link rel="stylesheet" href="/styles/main.css">

    <!-- Custom Styles -->
    <style>
        .profile-header {
            background: #f7f7f7;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .editable {
            word-wrap: break-word;
            /* Ensures long words do not cause overflow */
            overflow-wrap: break-word;
            /* Alternative to word-wrap for better support */
            max-height: 400px;
            /* Example max height */
            overflow-y: auto;
            /* Adds a vertical scrollbar if content exceeds max height */
        }


        .editable:hover {
            background-color: rgba(0, 0, 0, 0.05);
            /* Slight highlight on hover */
        }


        .profile-img-container:hover .overlay-btn {
            display: block;
        }

        /* Ensure the overlay button is centered over the image */
        .overlay-btn {
            display: none;
            cursor: pointer;
            transform: translate(-50%, -50%);
            top: 50%;
            left: 50%;
        }


        .icon-container {
            display: inline-block;
            margin-left: 10px;
        }

        .hidden {
            display: none;
        }


        .achievement-bar,
        .rep-bar {
            height: 20px;
        }

        .event-log li {
            margin-bottom: 10px;
        }

        /* the CSS for the popups of the trophy descriptions */
        .popup {
            position: relative;
            display: inline-block;
            cursor: pointer;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
        }

        /* The actual popup */
        .popup .popuptext {
            visibility: hidden;
            width: 160px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 8px 8px;
            position: absolute;
            z-index: 1;
            bottom: 100%;
            left: 50%;
            margin-left: -80px;
        }

        /* Popup arrow */
        .popup .popuptext::after {
            content: "";
            position: absolute;
            top: 100%;
            left: 50%;
            margin-left: -5px;
            border-width: 5px;
            border-style: solid;
            border-color: #555 transparent transparent transparent;
        }

        /* Toggle this class - hide and show the popup */
        .popup .show {
            visibility: visible;
            -webkit-animation: fadeIn 0s;
            animation: fadeIn 0s;
        }

        /* Add animation (fade in the popup) */
        @-webkit-keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }
    </style>
</head>

<body class="d-flex flex-column min-vh-100">

    <main class="flex-shrink-0">
        <%- include('../partials/_navbar') %>


        <div class="container mt-5">

            <% if (errorMessage) { %>
            <div class="alert alert-<%= alertType %>  alert-dismissible fade show" role="alert">
                <%= errorMessage %>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <% } %>


            <div class="profile-header">
                <div class="row">
                    <!-- Profile Picture -->
                    <div class="col-md-auto">
                        <div class="profile-img-container position-relative text-center">
                            <img src="<%= profile.profilePicture ? 'https://bak-counter-images.ams3.digitaloceanspaces.com/'+profile.profilePicture : '/uploads/profile/blank_image.png' %>"
                                alt="Profile Picture" class="img-fluid rounded-circle" style="width: 100px; height: 100px;
                        object-fit: cover; object-position: center;">

                            <% if (profile.id===user.id) { %>
                            <div class="overlay-btn position-absolute top-0 start-50 translate-middle-x"
                                style="bottom: 10px;">
                                <button class="btn btn-light" data-bs-toggle="modal"
                                    data-bs-target="#imageOptionsModal"><i class="bi bi-pencil-square"></i></button>
                            </div>
                            <% } %>
                        </div>
                    </div>

                    <div class="col-md">
                        <h2>
                            <%= profile.name %>'s Profile
                        </h2>
                        <!-- Profile Description Display and Edit -->

                        <div class="row">
                            <div class="col">
                                <div id="descriptionText" class="editable">
                                    <% const descriptionLines=profile.profileDescription ?
                                        profile.profileDescription.split('\n') : []; %>
                                    <% descriptionLines.forEach((line)=> { %>
                                    <span>
                                        <%= line %><br>
                                    </span>
                                    <% }); %>
                                </div>
                            </div>
                            <% if (profile.id===user.id) { %>
                            <div class="col-md-3 text-end">
                                <div class="icon-container" onclick="editDescription()">
                                    <i class="bi bi-pencil" style="cursor: pointer;"></i>
                                </div>
                            </div>
                            <% } %>
                        </div>



                        <!-- Hidden Form for Editing Description -->
                        <% if (profile.id===user.id) { %>
                        <form id="descriptionForm" action="/profile/updateDescription" method="post" class="hidden">
                            <input type="hidden" name="_csrf" value="<%= csrfToken %>">

                            <textarea id="descriptionEdit" name="profileDescription" class="form-control"
                                rows="4"><%= profile.profileDescription %></textarea>
                            <div class="mt-2">
                                <button type="submit" class="btn btn-success">Save Changes</button>
                                <button type="button" id="cancelEditBtn" class="btn btn-secondary"
                                    onclick="cancelEdit()">Cancel</button>
                            </div>
                        </form>
                        <% } %>
                    </div>



                    <!-- Other Profile Sections adjusted for responsiveness -->
                    <div class="row mt-3">
                        <div class="col-12 d-flex flex-column align-items-end">
                            <div class="text-end">
                                <h5><strong>Bestuursjaar:</strong>
                                    <%= profile.bestuursjaar %>
                                </h5>
                                <h5 class="mb-0"><strong>Level:</strong>
                                    <%= level %>
                                </h5>
                                <h5><strong>Reputation:</strong>
                                    <%= reputation %>
                                </h5>

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


                </div>
            </div>





            <!-- Progress Section with Levels & Reputation -->
            <div class="card mb-3">
                <div class="card-body">
                    <h4>Progress & Achievements</h4>
                    <div class="row">
                        <div class="col-md-6">
                            <p>XP: <%= profile.xp %> / <%= nextXPLevel ? nextXPLevel : 'Max Level' %>
                            </p>
                            <div class="progress mb-2">
                                <div class="progress-bar achievement-bar" role="progressbar"
                                    style="width: <%= xpPercentage %>%" aria-valuenow="<%= profile.xp %>"
                                    aria-valuemin="0" aria-valuemax="<%= nextXPLevel ? nextXPLevel : 100 %>"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <p>REP: <%= profile.rep %> / <%= nextRepTier ? nextRepTier : 'Max Tier' %>
                            </p>
                            <div class="progress">
                                <div class="progress-bar rep-bar bg-success" role="progressbar"
                                    style="width: <%= repPercentage %>%" aria-valuenow="<%= profile.rep %>"
                                    aria-valuemin="0" aria-valuemax="<%= nextRepTier ? nextRepTier : 100 %>"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Stats Section -->
            <div class="card mb-3">
                <div class="card-body">
                    <h4>Prijzen Kast</h4>
                    <!-- <p>Bakken in x aantal uur: <%= profile.recordCounter %></p> -->

                    <div class="row row-cols-3 row-cols-sm-4 row-cols-md-6">
                        <% profile.Trophies.forEach(trophy=> { %>
                        <div class="col-md-auto" style="margin-bottom: 20px; padding: 0px 0px 0px 12px;">
                            <div class="popup" onclick="trophyDetails('<%= trophy.name %>', 'click')"
                                onmouseover="trophyDetails('<%= trophy.name %>', 'hover')"
                                onmouseout="trophyDetails('<%= trophy.name %>', 'hover')">
                                <h5><%= trophy.name %></h5>
                                <img src="<%= trophy.trophyImage %>" alt="<%= trophy.name %>" class="img-fluid rounded"
                                    style="width: 100px; height: 100px;">
                                <span class="popuptext" id="<%= trophy.name %>">
                                    <%= trophy.description %>
                                </span>
                            </div>
                        </div>
                        <% }); %>
                    </div>
                    <!-- Add more stats as needed -->
                </div>
            </div>

            <!-- Event Log Section -->
            <div class="card">
                <div class="card-body">
                    <h4>Event Log</h4>
                    <!-- Search input -->
                    <input type="text" id="searchInput" class="form-control mb-3" onkeyup="searchTable()"
                        placeholder="Search for events...">
                    <div class="table-responsive">
                        <table class="table" id="eventLogTable">
                            <thead>
                                <tr>
                                    <th>Description</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <% profile.eventLogs.forEach(event=> { %>
                                <tr>
                                    <td><%= event.description %></td>
                                    <td><%= new Date(event.createdAt).toLocaleString('nl-NL', { timeZone: 'Europe/Amsterdam' }); %>
                                    </td>
                                </tr>
                                <% }); %>
                            </tbody>
                        </table>
                        <nav aria-label="Table pagination">
                            <ul class="pagination justify-content-center">
                                <li class="page-item" id="previousPage"><a class="page-link" href="#">Previous</a></li>
                                <!-- Pagination Numbers injected by JavaScript -->
                                <li class="page-item" id="nextPage"><a class="page-link" href="#">Next</a></li>
                            </ul>
                        </nav>

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



            <form id="deletePictureForm" action="/profile/deletePicture" method="post" style="display: none;">
                <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                <!-- Optionally, include CSRF token if your framework requires it for security -->
            </form>



            <!-- Modal for Image Options -->
            <div class="modal fade" id="imageOptionsModal" tabindex="-1" aria-labelledby="imageOptionsModalLabel"
                aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="imageOptionsModalLabel">Edit Profile Picture</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <% if (profile.profilePicture) { %>
                            <button class="btn btn-danger" onclick="deleteProfilePicture()">Delete Picture</button>
                            <% } %>
                            <form id="updatePictureForm" action="/profile/updatePicture" method="post"
                                enctype="multipart/form-data">
                                <input type="hidden" name="_csrf" value="<%= csrfToken %>">
                                <input type="file" id="newProfilePicture" name="profilePicture"
                                    accept="image/png, image/jpeg, image/jpg, image/gif" class="form-control">
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save changes</button>
                        </div>
                        </form>
                    </div>
                </div>
            </div>



        </div>
    </main>

    <%- include('../partials/_footer') %>

    <!-- Bootstrap JS -->

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"
        integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>

        $(document).ready(function () {
            $('#updatePictureForm').submit(function (e) {
                e.preventDefault(); // Prevent default form submission

                var formData = new FormData(this); // Create a FormData object from the form

                $.ajax({
                    url: $(this).attr('action'), // Get form action URL
                    type: 'POST',
                    data: formData,
                    contentType: false,
                    processData: false,
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader('X-CSRF-Token', $('input[name="_csrf"]').val());
                    },
                    success: function (response) {
                        window.location.href = `/profile/${parseInt(<%= user.id %>)}?errorMessage=${encodeURIComponent(response.message || 'Unknown Success')}&alertType=success`;
                    },
                    error: function (xhr) {
                        var response = JSON.parse(xhr.responseText);
                        window.location.href = `/profile/${parseInt(<%= user.id %>)}?errorMessage=${encodeURIComponent(response.message || 'Unknown error')}&alertType=danger`;
                    }
                });
            });
        });


        function editDescription() {
            document.getElementById('descriptionText').classList.add('hidden');
            document.getElementById('descriptionForm').classList.remove('hidden');
        }

        function cancelEdit() {
            document.getElementById('descriptionText').classList.remove('hidden');
            document.getElementById('descriptionForm').classList.add('hidden');
        }



        function deleteProfilePicture() {
            // Submit the form programmatically
            document.getElementById('deletePictureForm').submit();

            // Hide the options modal
            $('#imageOptionsModal').modal('hide');
        }



        function searchTable() {
            var input, filter, table, tr, td, i, txtValue;
            input = document.getElementById("searchInput");
            filter = input.value.toUpperCase();
            table = document.getElementById("eventLogTable");
            tr = table.getElementsByTagName("tr");

            // Loop through all table rows, and hide those who don't match the search query
            for (i = 0; i < tr.length; i++) {
                td = tr[i].getElementsByTagName("td")[0]; // Column index, 0 for the first column
                if (td) {
                    txtValue = td.textContent || td.innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
            }
        }

        // When the user hovers over the trophy it opens the popup
        function trophyDetails(popup_id, click_type) {
            var is_mobile = !!navigator.userAgent.match(/iphone|android|blackberry/ig) || false;
            if ('click' === click_type && is_mobile) {
                var popup = document.getElementById(popup_id);
                popup.classList.toggle("show");
                setTimeout(function () {
                    if (popup.classList.contains("show")) {
                        popup.classList.toggle("show");
                    }
                }, 2500);
            } else if ('hover' === click_type && !is_mobile) {
                var popup = document.getElementById(popup_id);
                popup.classList.toggle("show");
            }
        }



        document.addEventListener("DOMContentLoaded", function () {
            const rowsPerPage = 15;
            const table = document.getElementById('eventLogTable');
            const tbody = table.getElementsByTagName('tbody')[0];
            const rows = tbody.getElementsByTagName('tr');
            const pageCount = Math.ceil(rows.length / rowsPerPage);
            let currentPage = 1;

            function updateTable() {
                for (let i = 0; i < rows.length; i++) {
                    rows[i].style.display = 'none';
                }
                const start = (currentPage - 1) * rowsPerPage;
                const end = Math.min(start + rowsPerPage, rows.length);
                for (let i = start; i < end; i++) {
                    rows[i].style.display = '';
                }
            }

            function setupPagination() {
                const pagination = document.querySelector('.pagination');
                pagination.innerHTML = ''; // Clear existing

                // Add Previous Page button
                const prevLi = document.createElement('li');
                prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
                prevLi.innerHTML = `<a class="page-link" href="#">Previous</a>`;
                prevLi.querySelector('a').addEventListener('click', function (e) {
                    if (currentPage > 1) {
                        currentPage--;
                        updateTable();
                        setupPagination();
                    }
                    e.preventDefault();
                });
                pagination.appendChild(prevLi);

                // Dynamically add page numbers, handle ellipses and last page
                let startPage = Math.max(currentPage - 2, 1);
                let endPage = Math.min(currentPage + 2, pageCount);

                if (startPage > 1) {
                    pagination.appendChild(createPageItem(1, currentPage === 1));
                    if (startPage > 2) {
                        pagination.appendChild(createEllipsisItem());
                    }
                }

                for (let i = startPage; i <= endPage; i++) {
                    pagination.appendChild(createPageItem(i, i === currentPage));
                }

                if (endPage < pageCount) {
                    if (endPage < pageCount - 1) {
                        pagination.appendChild(createEllipsisItem());
                    }
                    pagination.appendChild(createPageItem(pageCount, currentPage === pageCount));
                }

                // Add Next Page button
                const nextLi = document.createElement('li');
                nextLi.className = `page-item ${currentPage === pageCount ? 'disabled' : ''}`;
                nextLi.innerHTML = `<a class="page-link" href="#">Next</a>`;
                nextLi.querySelector('a').addEventListener('click', function (e) {
                    if (currentPage < pageCount) {
                        currentPage++;
                        updateTable();
                        setupPagination();
                    }
                    e.preventDefault();
                });
                pagination.appendChild(nextLi);

                updateTable();
            }

            function createPageItem(page, isCurrent) {
                const li = document.createElement('li');
                li.className = `page-item ${isCurrent ? 'active' : ''}`;
                li.innerHTML = `<a class="page-link" href="#">${page}</a>`;
                if (!isCurrent) {
                    li.addEventListener('click', function (e) {
                        currentPage = page;
                        updateTable();
                        setupPagination();
                        e.preventDefault();
                    });
                }
                return li;
            }

            function createEllipsisItem() {
                const li = document.createElement('li');
                li.className = 'page-item disabled';
                li.innerHTML = `<span class="page-link">...</span>`;
                return li;
            }

            setupPagination();
        });




    </script>

</body>

</html>