Time Calculation (PHP, JS, MYSQL) [closed]

I have the following script ready for calculating the attendance of staff

index.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Table</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center mb-5">Dynamic Table</h1>
        <form id="myForm">
            <table class="table">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Start Time</th>
                        <th>End Time</th>
                        <th>Time Taken</th>
                        <th>Total Time Taken</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <input type="text" name="description[]" class="form-control">
                        </td>
                        <td>
                            <input type="datetime-local" name="start_time[]" class="form-control start_time" required>
                        </td>
                        <td>
                            <input type="datetime-local" name="end_time[]" class="form-control end_time" required>
                        </td>
                        <td>
                            <input type="text" name="time_taken[]" class="form-control time_taken" readonly>
                        </td>
                        <td>
                            <input type="text" name="total_time_taken[]" class="form-control total_time_taken" readonly>
                        </td>
                        <td>
                            <i class="fas fa-trash delete-row" style="display: none;"></i>
                        </td>
                    </tr>
                </tbody>
            </table>
            <button type="button" class="btn btn-primary" id="addRow">Add Row</button>
            <button type="button" class="btn btn-primary" id="validate" style="display: none;">Validate</button>
            <button type="submit" class="btn btn-primary" id="submit" style="display: none;">Submit</button>
            <p class="error-message"></p>
        </form>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

script.js

$(document).ready(function() {
    let rowCounter = 1;
    let totalTimeTaken = 0;

    // Function to calculate time difference
    function calculateTimeDifference(start, end) {
        const startDate = new Date(start);
        const endDate = new Date(end);

        const diffInMilliseconds = Math.abs(endDate - startDate);
        const days = Math.floor(diffInMilliseconds / (1000 * 60 * 60 * 24));
        const hours = Math.floor((diffInMilliseconds % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((diffInMilliseconds % (1000 * 60 * 60)) / (1000 * 60));

        return `${days} days ${hours} hrs ${minutes} mins`;
    }

    // Function to calculate total time taken
    function calculateTotalTimeTaken(timeTakenArray) {
        let totalTimeTaken = 0;

        timeTakenArray.forEach(timeTaken => {
            totalTimeTaken += timeTaken;
        });

        return totalTimeTaken;
    }

    // Function to create a new row
    function createNewRow() {
        if (rowCounter > 1) {
            $('input[name="start_time[]"]:last').attr('readonly', true);
            $('.delete-row:last').show();
        }

        const rowHtml = `<tr>
                <td>
                    <textarea name="description[]" class="form-control" rows="1"></textarea>
                </td>
                <td>
                    <input type="datetime-local" name="start_time[]" class="form-control start_time" required>
                </td>
                <td>
                    <input type="datetime-local" name="end_time[]" class="form-control end_time" required>
                </td>
                <td>
                    <input type="text" name="time_taken[]" class="form-control time_taken" readonly>
                </td>
                <td>
                    <input type="text" name="total_time_taken[]" class="form-control total_time_taken" readonly>
                </td>
                <td>
                    <i class="fas fa-trash delete-row"></i>
                </td>
            </tr>
        `;

        $('#myForm table tbody').append(rowHtml);
        rowCounter++;
    }

    // Function to remove the last row
    function removeLastRow() {
        if (rowCounter > 1) {
            $('table tbody tr:last-child').remove();
            rowCounter--;
        }
    }

    // Event listener for adding a new row
    $('#addRow').click(function() {
        createNewRow();
    });

    // Event listener for removing the last row
    $(document).on('click', '.delete-row', function() {
        removeLastRow();
    });

    // Event listener for datetime input
    $(document).on('change', '.start_time, .end_time', function() {
        const row = $(this).closest('tr');
        const startTime = row.find('.start_time').val();
        const endTime = row.find('.end_time').val();

        if (endTime < startTime) {
            row.find('.end_time').addClass('is-invalid');
            row.find('.start_time').addClass('is-invalid');
            $('.error-message').text('End time cannot be less than start time.');
        } else {
            row.find('.end_time').removeClass('is-invalid');
            row.find('.start_time').removeClass('is-invalid');
            $('.error-message').text('');

            const timeTaken = calculateTimeDifference(startTime, endTime);
            row.find('.time_taken').val(timeTaken);

            const timeTakenArray = $('input[name="time_taken[]"]').map(function() {
                return $(this).val();
            }).get();

            let currentRowTotalTimeTaken = calculateTotalTimeTaken(timeTakenArray);

            if (rowCounter > 1) {
                currentRowTotalTimeTaken += timeTaken;
            } else {
                currentRowTotalTimeTaken = timeTaken;
            }

            row.find('.total_time_taken').val(currentRowTotalTimeTaken);
            totalTimeTaken = currentRowTotalTimeTaken;
        }
    });

    // Event listener for form submission
    $('#myForm').on('submit', function(e) {
        e.preventDefault();

        if ($('.is-invalid').length > 0) {
            return;
        }

        $.ajax({
            url: 'submit.php',
            method: 'post',
            data: $(this).serialize(),
            success: function(response) {
                console.log(response);
                alert('Data submitted successfully!');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error(textStatus, errorThrown);
                alert('Error occurred while submitting data.');
            }
        });
    });

    // Show/hide buttons
    $('#addRow').click(function() {
        $('#validate').show();
    });

    $('button[type="button"]').click(function() {
        if ($(this).attr('id') === 'validate') {
            $('#submit').show();
            $(this).hide();
        }

        if ($(this).attr('id') === 'submit') {
            $(this).hide();
        }
    });
});

submit.php

<?php
// Database connection
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get data from the form
$description = $_POST['description'];
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$time_taken = $_POST['time_taken'];
$total_time_taken = $_POST['total_time_taken'];

// Insert into the database
for ($i = 0; $i < count($description); $i++) {
    $sql= "INSERT INTO your_table (description, start_time, end_time, time_taken, total_time_taken)
            VALUES ('{$description[$i]}', '{$start_time[$i]}', '{$end_time[$i]}', '{$time_taken[$i]}', '{$total_time_taken[$i]}')";

    if ($conn->query($sql) === FALSE) {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Close the connection
$conn->close();
?>

I need the value as below,
First row time taken = 1 days 16 hrs 32 mins | Total time taken = 1 days 16 hrs 32 mins
Second row time taken = 8 mins | Total time taken = 1 days 16 hrs 40 mins

The total time taken should be the sum of all time taken upto the current row. But when i run the code, the total time taken just add the text values like below

First row time taken = 1 days 16 hrs 32 mins | Total time taken = 1 days 16 hrs 32 mins
Second row time taken = 8 mins | Total time taken = 1 days 16 hrs 32 mins 0 days 0 hrs 8 mins

I tried changing the type of input from text to date-time with no luck.

Secondly
I would like to validate if the end time of the first/previous row is equal to the start time of the current row if not to throw an error.

I’m not able to retrieve the live value of the fields since js is run when the documents is loaded.