$(document).ready(() => {
    checkShiftAndAudits();
    setInterval(checkShiftAndAudits, 180000); //Cada 3 minutos (180 mil milisegundos)
});

function checkShiftAndAudits() {
    $.get("/audits/check-shift-and-audits", function (response) {
        if (response.redirect && response.lastCashCountNeedAudit) { // Check if is there an audit to review?
            window.location.href = response.redirect;
        } else if (response.redirect && !response.lastCashCountNeedAudit) { // Is it time to close the shift?
            Swal.fire({
                icon: `${ response.allowPostpone ? "info" : "warning"}`,

                html: `
                    <h2>${translateAndReplace('common_responses_and_messages.shift_end_alert')}</h2>

                    <p style="font-size: 1.1rem; font-weight: 500;">${translateAndReplace('common_responses_and_messages.shift_end_intro')}</p>

                    <p class="mt-4">
                        ${translateAndReplace('common_responses_and_messages.shift_end_action')
                            .replace(`"${translateAndReplace("common_actions.audit")}"`, `<b>"${translateAndReplace("common_actions.audit")}"</b>`)}

                        ${ response.allowPostpone
                            ? translateAndReplace('common_responses_and_messages.shift_end_action_postpone')
                                .replace(`"${translateAndReplace("common_actions.postpone")}"`, `<b>"${translateAndReplace("common_actions.postpone")}"</b>`)
                            : ""
                        }
                    </p>

                    ${ response.allowPostpone
                        ? `<small><i>${translateAndReplace('common_responses_and_messages.shift_end_repeat')}</i></small>`
                        : ""
                    }
                `,

                allowOutsideClick: false,

                showCancelButton: response.allowPostpone,
                cancelButtonText: translateAndReplace("common_actions.postpone"),
                confirmButtonText: translateAndReplace("common_actions.audit"),
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = response.redirect;
                }
            });

        }
    });
}
