{% extends "base.html" %}
{% block mainblock %}

<div class="table-container">
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body p-0">
                        <div class="table-responsive w-100">
                            <table id="bmiTable" class="table table-bordered table-hover">
                                <thead class="thead-dark">
                                    <tr>
                                        <th>Datetime</th>
                                        <th>Height</th>
                                        <th>Weight</th>
                                        <th>BMI</th>
                                        <th style="width: 100px;"><span style="visibility: hidden;">Action</span></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Table data will be populated by JavaScript -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function loadBMIData() {
        $.ajax({
            url: "{{ url_for('bmi.get_bmi_data') }}",
            type: "POST",
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify({}),
            error: function(xhr, status, error) {
                console.error("Error loading BMI data:", error);
                alert("Error loading BMI data. Please try again.");
            },
            success: function(response) {
                if (response.error) {
                    console.error("Server error:", response.error);
                    alert("Error: " + response.error);
                    return;
                }

                const tableBody = $('#bmiTable tbody');
                tableBody.empty();

                if (response.data.length === 0) {
                    tableBody.append('<tr><td colspan="5" class="text-center">No BMI data available</td></tr>');
                    return;
                }

                response.data.forEach(function(item) {
                    const row = $('<tr>');
                    row.append($('<td>').text(item.datetime));
                    const heightInM = (parseFloat(item.height) / 10).toFixed(1) + ' m';
                    row.append($('<td>').text(heightInM));
                    row.append($('<td>').text(parseFloat(item.weight).toFixed(1)));
                    row.append($('<td>').text(parseFloat(item.bmi).toFixed(1)));
                    row.append(
                        $('<td>').append(
                            $('<button>')
                                .text('Remove')
                                .addClass('btn btn-sm btn-outline-danger')
                                .attr('type', 'button')
                        )
                    );
                    tableBody.append(row);
                });
            }
        });
    }

    $(document).ready(function() {
        loadBMIData();
    });
</script>

{% endblock %}

Here is my current manage_bmi.html as seen above

Below is my bmi.py controller

from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from datetime import datetime, date
from flask_login import current_user
from models.bmidaily import BMIDAILY
from models.bmilog import BMILOG
from models.users import User

bmi = Blueprint('bmi', __name__)

@bmi.route('/manage_bmi')
def manage_bmi():
    if current_user.email != "admin@abc.com":
        return render_template('manage_bmi.html', 
                         name=current_user.name, 
                         panel="Manage BMI Data")

# Route to handle AJAX request for BMI data
@bmi.route('/get_bmi_data', methods=['POST'])
def get_bmi_data():
    try:
        # Get BMI logs for the current user
        user = User.getUser(email=current_user.email)
        bmi_logs = BMILOG.objects(user=user).order_by('-datetime')
        
        # Format the data for the table
        bmi_data = []
        for log in bmi_logs:
            bmi_data.append({
                'datetime': log.datetime.strftime('%Y-%m-%d %H:%M:%S'),
                'height': log.height,
                'weight': log.weight,
                'bmi': round(log.bmi, 2)
            })
        
        return jsonify({'data': bmi_data})
    except Exception as e:
        print(f"Error: {e}")
        return jsonify({'error': str(e)}), 400

# This following functions is for GET /log, and POST /process via log.html and log.js

@bmi.route('/log')
def log():
    return render_template('log.html', name=current_user.name, panel="Logging BMI")

@bmi.route('/process',methods= ['POST'])
def process():
    weight  = float(request.form['weight'])
    height = float(request.form['height'])
    unit = request.form['unit']

    # In /log, the date of BMI log is assumed to be today
    today = date.today()
    now = datetime.now()

    try:

        # First store the bmilog, by default there the current user is already an user
        # So, if no user can be retrieved, then there is an exception

        existing_user = User.getUser(email=current_user.email)
        bmilogObject = BMILOG.createBMILOG(user=existing_user, datetime=now, weight=weight, height=height, unit=unit, bmi=0.0)
        bmilogObject.bmi = bmilogObject.computeBMI()
        bmilogObject.save()

        bmidaily = BMIDAILY.getBMIDAILY(user=existing_user, date=today) #GET INFO

        # Check whether there is existing bmidailylog for the user

        if bmidaily:

            # if Yes, update the avergeBMI
            new_bmi_average = bmidaily.updatedBMI(bmilogObject.bmi)
            bmidaily.numberOfMeasures += 1
            bmidaily.averageBMI = new_bmi_average
            bmidaily.save()

        else:

            # if No, initialize the averageBMI
            BMIDAILY.createBMIDAILY(existing_user, today, 1, bmilogObject.bmi)
            # bmidailyObject.save()

    except Exception as e:
        print(f"{e}")
        return jsonify({})

    return jsonify({'bmi' : bmilogObject.bmi})

# This following functions is for GET /log2 and POST /process via log2.html and log2.js

@bmi.route('/log2')
def log2():
    all_users = User.objects()
    return render_template('log2.html', name=current_user.name, panel="Logging BMI 2", user_list=all_users)

@bmi.route('/process2',methods= ['POST'])
def process2():

    # Get the parameters posted by form in log2.html
    weight  = float(request.form['weight'])
    height = float(request.form['height'])
    unit = request.form['unit']
    if current_user.email == "admin@abc.com":
        user_email = request.form['user_email']
    else:
        user_email = current_user.email
    date = request.form['date']

    datetime_object = datetime.strptime(date, '%Y-%m-%dT%M:%S')
    date_object= datetime_object.date()

    try:

        # First store the bmilog, by default there the current user is already an user
        # So, if no user can be retrieved, then there is an exception
        existing_user = User.getUser(email=user_email)
        bmilogObject = BMILOG.createBMILOG(user=existing_user, datetime=datetime_object, weight=weight, height=height, unit=unit, bmi=0.0)
        bmilogObject.bmi = bmilogObject.computeBMI()
        bmilogObject.save()

        bmidaily = BMIDAILY.getBMIDAILY(user=existing_user, date=date_object) #GET INFO

        # Check whether there is existing bmidailylog for the user

        if bmidaily:

            # if Yes, update the avergeBMI
            new_bmi_average = bmidaily.updatedBMI(bmilogObject.bmi)
            bmidaily.numberOfMeasures += 1
            bmidaily.averageBMI = new_bmi_average
            bmidaily.save()

        else:

            # if No, initialize the averageBMI
            BMIDAILY.createBMIDAILY(existing_user, date_object, 1, bmilogObject.bmi)
            # bmidailyObject.save()

    except Exception as e:
        print(f"{e}")
        return jsonify({})

    return redirect(url_for('bmi.log2'))

When a non-admin user clicks on the remove button to remove the BMI data for the page, the backend component must perform the following steps:
1. Get the document which the non-admin user wishes to remove from bmilog
2. Delete the document.
3. Get the corresponding document from bmidaily that records the BMI daily average for the
document deleted in step 2.
4. Update the document by reducing the number of measures.
5. If the number of measures for that date is 0, delete the document. Otherwise
update the average bmi.
6. Return data to the frontend through client-side rendering