window.columns = [
    {
        data: 'DT_RowIndex',
        orderable: false,
        searchable: false
    },
    { data: 'created_at' },
    { data: 'check_in' },
    { data: 'check_in_image' },
    { data: 'check_out' },
    { data: 'check_out_image' },
    { data: 'working_time' },
];

function updateWorkingTime() {
    const today = moment().format('YYYY-MM-DD');

    $('table tbody tr').each(function () {
        const dateCell = $(this).find('td:nth-child(2)');
        const checkOutCell = $(this).find('td:nth-child(5)');
        const workingTimeCell = $(this).find('td:nth-child(7)');

        const rowDate = moment(dateCell.text(), 'ddd, DD MMM YYYY').format('YYYY-MM-DD');
        const checkOutText = checkOutCell.text().trim();

        if (rowDate === today && checkOutText === '-') {
            const checkInCell = $(this).find('td:nth-child(3)');
            const checkInTime = checkInCell.text().trim();

            if (checkInTime && checkInTime !== '-') {
                const checkIn = moment(checkInTime, 'HH:mm:ss');
                const now = moment();

                const duration = moment.duration(now.diff(checkIn));

                const hours = duration.hours();
                const minutes = duration.minutes();
                const seconds = duration.seconds();

                let formattedTime = '';
                if (hours > 0) {
                    formattedTime = `${hours} jam ${minutes} menit ${seconds} detik`;
                } else if (minutes > 0) {
                    formattedTime = `${minutes} menit ${seconds} detik`;
                } else {
                    formattedTime = `${seconds} detik`;
                }

                workingTimeCell.text(formattedTime);
            }
        }
    });
}

$(document).ready(function () {
    if (typeof moment !== 'undefined') {
        moment.locale('id');

        updateWorkingTime();

        setInterval(updateWorkingTime, 1000);
    } else {
        console.error('moment.js library tidak ditemukan');
    }
});
