<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Profile</title>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body class="bg-gray-100">

<!-- Include the navbar from mainlayout -->
<div th:replace="layouts/mainLayout"></div>

<h2 class="text-2xl font-semibold mb-4 text-center">User Profile</h2>
<div class="container mx-auto p-4 flex flex-col items-center">
    <!-- Edit Profile Picture button -->
    <div class="mb-8 relative">
        <img class="rounded-full w-96 h-96 ring-2 ring-gray-300 dark:ring-gray-500" id="profilePicture" th:src="@{/api/user/profile-picture?username=}+ ${user.username}" style="width:304px;height:228px"/>
        <span data-tooltip-target="tooltip-default" class="bottom-0 left-7 absolute  w-3.5 h-3.5 rounded-full">
            <i id="editProfilePictureButton" class="fas fa-edit text-black absolute top-0 right-0 m-2 cursor-pointer"></i>
        </span>
        <div id="tooltip-default" role="tooltip" class="absolute z-10 invisible inline-block px-3 py-2 text-sm font-medium text-white transition-opacity duration-300 bg-gray-900 rounded-lg shadow-sm opacity-0 tooltip dark:bg-gray-700">
            Edit Profile Picture
            <div class="tooltip-arrow" data-popper-arrow></div>
        </div>
    </div>

    <!-- Edit Profile Picture form -->
    <div id="editProfilePictureForm" style="display: none;">
        <form id="profilePictureForm" class="mt-4 flex items-center">
            <!-- Close Button -->
            <button type="button" id="closeButton" class="text-black cursor-pointer">
                <i class="fas fa-times"></i>
            </button>

            <!-- Upload Form -->
            <input type="file" name="profilePictureFile" accept="image/*" required class="ml-4" />
            <button type="submit" class="ml-4 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-6 py-2 text-white dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
                Upload
            </button>

            <!-- Upload Error Message -->
            <p id="uploadErrorMessage" style="color: red; display: none;" class="ml-4 text-sm"></p>
        </form>
    </div>

    <div class="lg:flex lg:justify-between w-full">

    <!-- Subscription Details Card -->
        <div class="lg:w-1/3 bg-white p-6 rounded-lg shadow-md mb-8">
    <h2 class="text-2xl font-bold mb-4">Subscription Details</h2>

        <!-- Subscription Details Section -->
        <div class="mb-4">
            <p><strong>Plan Name:</strong> <span id="planName"></span></p>
            <p><strong>Max Short URLs:</strong> <span id="maxShortUrls"></span></p>
            <p><strong>Max Bio Pages:</strong> <span id="maxBioPages"></span></p>
        </div>

        <!-- Subscription EDIT Section -->
        <div class="mb-4">
            <!-- Your existing subscription form button -->
            <button class="block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button" id="subscriptionFormToggle">Change Subscription</button>

            <!-- Subscription form (initially hidden) -->
            <form id="subscriptionForm" class="hidden">
                <h1>Subscription Change</h1>
                <label>
                    <input type="radio" name="subscriptionPlan" value="free" checked>
                    Free Plan
                </label>
                <label>
                    <input type="radio" name="subscriptionPlan" value="basic">
                    Basic Plan
                </label>
                <label>
                    <input type="radio" name="subscriptionPlan" value="pro">
                    Pro Plan
                </label>
                <button class="block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button"  id="payButton">Change Subscription</button>
                <!-- Close button to hide the form -->
                <button class="block text-white bg-red-700 hover:bg-red-800 focus:ring-4 focus:outline-none focus:ring-red-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button"  id="subscriptionFormClose">Close</button>
            </form>
        </div>

    </div>

    <!-- User Information Card -->
        <div class="lg:w-1/3 bg-white p-6 rounded-lg shadow-md mb-8">
        <h2 class="text-2xl font-bold mb-4">User Information</h2>

        <!-- User Information Section -->
        <div class="mb-4">
            <p><strong>UserID:</strong> <span th:text="${user.userId}"></span></p>
            <p><strong>Username:</strong> <span id="username" th:text="${user.username}"></span></p>
            <p><strong>Email:</strong> <span id="email" th:text="${user.email}"></span></p>
            <p><strong>First Name:</strong> <span id="firstName" th:text="${user.firstName}"></span></p>
            <p><strong>Last Name:</strong> <span id="lastName" th:text="${user.lastName}"></span></p>
            <p><strong>Phone Number:</strong> <span th:text="${user.phoneNumber}"></span></p>
            <p><strong>Enabled:</strong> <span th:text="${user.enabled}"></span></p>
            <p><strong>Non-Locked:</strong> <span th:text="${user.accountNonLocked}"></span></p>
            <p><strong>Password:</strong> <span th:text="${userelevated.password}"></span></p>
            <p><strong>Profile Picture Bytes:</strong> <span th:text="${userelevated.profilePicture}"></span></p>
        </div>
        <div class="mb-4">
        <!-- Modal toggle -->
        <button id="profileEditButton" data-modal-target="crud-modal" data-modal-toggle="crud-modal" class="block text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button">
            Edit Profile
        </button>
        </div>
    </div>


    <!-- Edit Buttons Card -->
        <div class="lg:w-1/3 bg-white p-6 rounded-lg shadow-md mb-8">
        <h2 class="text-2xl font-bold mb-4">Personal Information</h2>
        <h4 class="text font-bold mb-4">Please type in the new phone number / password and press the respective buttons.</h4>
        <div class="mb-4">

            <!-- Edit Phone Number button -->
            <form th:action="@{/profile/update-phone-number}" method="post" class="mb-4">
                <input type="hidden" name="username" th:value="${user.username}" />
                <input type="text" name="newPhoneNumber" th:value="${user.phoneNumber}" />

                <button type="submit" class="text-white inline-flex items-center bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
                    Edit Phone Number
                </button>
            </form>

            <!-- Edit Password button -->
            <form id="editPasswordForm" class="mb-4">
                <input type="hidden" name="username" th:value="${user.username}" />
                <input id="passwordInput" type="password" name="password" th:value="${userelevated.password}" />

                <button type="submit" class="text-white inline-flex items-center bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
                    Edit Password
                </button>

                <p id="passwordChangeInfo"></p>
            </form>

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

    <!-- Edit Profile modal -->
    <div id="crud-modal" tabindex="-1" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
        <div class="relative p-4 w-full max-w-md max-h-full">
            <!-- Modal content -->
            <div class="relative bg-white rounded-lg shadow dark:bg-gray-700">
                <!-- Modal header -->
                <div class="flex items-center justify-between p-4 md:p-5 border-b rounded-t dark:border-gray-600">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white">
                        Update Profile
                    </h3>
                    <button type="button" class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white" data-modal-toggle="crud-modal">
                        <svg class="w-3 h-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
                            <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>
                        </svg>
                        <span class="sr-only">Close modal</span>
                    </button>
                </div>
                <!-- Modal body -->
                <form id="profileEditForm" class="p-4 md:p-5">
                    <div class="grid gap-4 mb-4 grid-cols-2">
                        <div class="col-span-2">
                            <label for="formEmail" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Email</label>
                            <input type="email" name="name" id="formEmail" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Type email" >
                        </div>
                        <div class="col-span-2 sm:col-span-1">
                            <label for="formFirstName" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">First Name</label>
                            <input type="text" name="firstName" id="formFirstName" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Type First Name" >
                        </div>
                        <div class="col-span-2 sm:col-span-1">
                            <label for="formLastName" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Last Name</label>
                            <input type="text" name="lastName" id="formLastName" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Type Last Name" >
                        </div>
                        <div class="col-span-2">
                            <label for="formUsername" class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Username</label>
                            <input type="text" name="name" id="formUsername" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-primary-600 focus:border-primary-600 block w-full p-2.5 dark:bg-gray-600 dark:border-gray-500 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Type Username" >
                        </div>
                    </div>
                    <button id="profileUpdateSubmitButton" class="text-white inline-flex items-center bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">
                        <svg class="me-1 -ms-1 w-5 h-5" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z" clip-rule="evenodd"></path></svg>
                        Update
                    </button>
                    <p id="profileFormUpdateResponse"></p>
                    <p id="forminfoMessage"></p>
                    <p id="profileFormErrorMessage"></p>

                    <!-- Add the SVG loader -->
                    <div id="loader" class="hidden">
                        Loading...
                    </div>
                </form>
            </div>
        </div>
    </div>

</div>
<div th:replace="layouts/footerLayout"></div>
<script>
    document.getElementById('payButton').addEventListener('click', function() {
        var selectedPlan = document.querySelector('input[name="subscriptionPlan"]:checked').value;
        var name = document.getElementById("firstName").innerText.concat(" "+document.getElementById("lastName").innerText) ;
        var username = document.getElementById("username").innerText;
        var options = {
            key: 'rzp_live_aHYzHmS8uzVwo9',
            subscription_id: getSubscriptionId(selectedPlan),
            name: 'The URL Shortener Company',
            description: getPlanDescription(selectedPlan),
            handler: function(response) {
                var paymentDetails = {
                    razorpay_payment_id: response.razorpay_payment_id,
                    razorpay_subscription_id: response.razorpay_subscription_id,
                    razorpay_signature: response.razorpay_signature
                };
                url: '/api/subscription/change?username='+username+'&newPlanName='+selectedPlan;
                fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(paymentDetails)
                })
                    .then(response => response.json())
                    .then(data => {
                        alert('Subscription changed successfully!');
                        console.log(data);
                    })
                    .catch(error => {
                        console.error('Error changing subscription:', error);
                    });
            },
            prefill: {
                name: name
             //   email: 'gaurav.kumar@example.com',
             //   contact: '+919876543210'
            },
            theme: {
                color: '#F37254'
            }
        };

        var rzp = new Razorpay(options);
        rzp.open();
    });

    function getSubscriptionId(selectedPlan) {
        // Dynamically set subscription ID based on the selected plan
        if (selectedPlan === 'free') {
            return 'your_free_plan_subscription_id';
        } else if (selectedPlan === 'basic') {
            return 'sub_NODa7MwhWw2yOi';
        } else if (selectedPlan === 'pro') {
            return 'your_pro_plan_subscription_id';
        } else {
            // Default to a placeholder subscription ID
            return 'your_default_plan_subscription_id';
        }
    }

    function getPlanDescription(selectedPlan) {
        // Dynamically set plan description based on the selected plan
        if (selectedPlan === 'free') {
            return 'Your Free Plan Description';
        } else if (selectedPlan === 'basic') {
            return 'Your Basic Plan Description';
        } else if (selectedPlan === 'pro') {
            return 'Your Pro Plan Description';
        } else {
            // Default to a placeholder description
            return 'Unknown Plan';
        }
    }



    // Fetch subscription details for the current user
    const fetchSubscriptionDetails = async () => {
        const username = document.getElementById("username").innerText; // Replace with the actual username or retrieve it dynamically

        try {
            const response = await fetch(`/api/subscription/details/${username}`);
            const data = await response.json();

            // Process the subscription details data
            displaySubscriptionDetails(data);
        } catch (error) {
            console.error("Error fetching subscription details:", error);
        }
    };

    // Display Subscription Details on the Page
    const displaySubscriptionDetails = (subscriptionDetails) => {
        // Access the subscription details properties and update the UI
        const planName = subscriptionDetails.planName;
        const maxShortUrls = subscriptionDetails.maxShortUrl;
        const maxBioPages = subscriptionDetails.maxBioPages;

        // Update UI elements with subscription details
        document.getElementById("planName").innerText = planName;
        document.getElementById("maxShortUrls").innerText = maxShortUrls;
        document.getElementById("maxBioPages").innerText = maxBioPages;
    };

    // Call the function to fetch and display subscription details
    fetchSubscriptionDetails();


    document.getElementById('editProfilePictureButton').addEventListener('click', function () {
        document.getElementById('editProfilePictureForm').style.display = 'block';
    });

    document.getElementById('profilePictureForm').addEventListener('submit', function (e) {
        const username = document.getElementById("username").innerText;
        e.preventDefault();

        var fileInput = document.querySelector('input[name="profilePictureFile"]');
        var formdata = new FormData();
        formdata.append("file", fileInput.files[0]);

        var requestOptions = {
            method: 'POST',
            body: formdata,
            redirect: 'follow'
        };

        fetch(`/api/user/profile-picture?username=`+username, requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Upload failed');
                }
                return response.text();
            })
            .then(result => {
                console.log(result);
                // Refresh the profile picture after successful upload
                document.getElementById('profilePicture').src = `/api/user/profile-picture?username=`+username;
                // Hide the form after successful upload
                document.getElementById('editProfilePictureForm').style.display = 'none';
            })
            .catch(error => {
                console.error('Upload failed:', error);
                document.getElementById('uploadErrorMessage').style.display = 'block';
            });
    });
    // Add event listener to hide the form and tooltip when the close button is clicked
    closeButton.addEventListener('click', function () {
        document.getElementById('editProfilePictureForm').style.display = 'none';
    });



    document.addEventListener('DOMContentLoaded', function () {
        const username = document.getElementById("username").innerText;
        const editButton = document.getElementById('profileEditButton');
        const modal = document.getElementById('crud-modal');
        const closeButton = document.getElementById('closeButton');
        const profileFormUpdateResponse = document.getElementById('profileFormUpdateResponse');
        const forminfoMessage = document.getElementById('forminfoMessage');
        const profileUpdateSubmitButton = document.getElementById('profileUpdateSubmitButton');
        const loader = document.getElementById('loader');
        const profileFormErrorMessage = document.getElementById('errorMessage');



        editButton.addEventListener('click', function () {
            modal.classList.remove('hidden');
        });

        closeButton.addEventListener('click', function () {
            modal.classList.add('hidden');
        });

        profileUpdateSubmitButton.addEventListener('click', function (event) {
            event.preventDefault();

            const formEmail = document.getElementById('formEmail').value;
            const formFirstName = document.getElementById('formFirstName').value;
            const formLastName = document.getElementById('formLastName').value;
            const formUsername = document.getElementById('formUsername').value;



            // Check if any of the form fields is blank
            if (formEmail === '' && formFirstName === '' && formLastName === '' && formUsername === '') {
                profileFormErrorMessage.innerText = 'Please fill in at least one field.';
                return;
            }

            // Create the request body
            const requestBody = {};

            // Add fields to the request body only if they are not blank
            if (formEmail !== '') {
                requestBody.email = formEmail;
            }
            if (formFirstName !== '') {
                requestBody.firstName = formFirstName;
            }
            if (formLastName !== '') {
                requestBody.lastName = formLastName;
            }
            if (formUsername !== '') {
                requestBody.username = formUsername;
            }

            // Show loader while waiting for the response
            loader.classList.remove('hidden');

            // Make the update profile request
            fetch(`/api/user/update?username=`+username, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Basic YW1pdDoxMjM0cXdlcg=='
                },
                body: JSON.stringify(requestBody),
                redirect: 'follow'
            })
                .then(response => response.text())
                .then(result => {
                    profileFormUpdateResponse.innerText=result;

                    console.log(result);

                    // Hide loader after receiving the response
                    loader.classList.add('hidden');

                    // Display info message
                    forminfoMessage.innerText = 'Page will be refreshed in 2 seconds.';

                    // Close the modal after 2 seconds (2000 milliseconds)
                    setTimeout(function () {
                        modal.classList.add('hidden');
                        // Optionally, you can refresh the page
                        window.location.reload();
                    }, 2000);
                })
                .catch(error => {
                    console.error('Error updating profile:', error);
                    profileFormUpdateResponse.innerText='Error updating profile:'+error;
                    // Optionally, you can show an error message here
                });
        });
    });

    // JavaScript to toggle form visibility and handle close button
    document.getElementById('subscriptionFormToggle').addEventListener('click', function() {
        document.getElementById('subscriptionForm').classList.toggle('hidden');
        document.getElementById('subscriptionFormToggle').classList.toggle('hidden');
    });

        document.getElementById('subscriptionFormClose').addEventListener('click', function() {
        document.getElementById('subscriptionForm').classList.add('hidden');
        document.getElementById('subscriptionFormToggle').classList.toggle('hidden');
    });

    // JavaScript to handle form submission
    document.getElementById('editPasswordForm').addEventListener('submit', function (event) {
        const username = document.getElementById("username").innerText;
        const passwordChangeInfo = document.getElementById("passwordChangeInfo");



        event.preventDefault(); // Prevent the default form submission

        var myHeaders = new Headers();
        myHeaders.append("Content-Type", "application/json");

        var password = document.getElementById('passwordInput').value;
        const email = document.getElementById("email").innerText;

        console.log("EMAIL IS"+email);
        console.log("PASSWORD IS"+password);

        var raw = JSON.stringify({
            "email" : email,
            "password": password
        });

        var requestOptions = {
            method: 'POST',
            headers: myHeaders,
            body: raw,
            redirect: 'follow'
        };

        fetch("/api/user/update?username="+username, requestOptions)
            .then(response => response.text())
            .then(result => {
                console.log(result);
                passwordChangeInfo.innerText = "Password Change Successful"+ result;
            })
            .catch(error => {
                passwordChangeInfo.innerText = "Password Change Failed";
                console.error('Error updating password:', error) ;
            })
    });
</script>
</body>
</html>