<?php
/**
 * Hyva compatible template
 */
?>
<?php if ($this->returnEnabled() && $this->getVisibleOnProduct()) { ?>
    <div class="border border-black p-2 mb-4" x-cloak x-data="countDownTimer()" x-init="initCountdownTimer()">
        <div class="ml-3 my-auto font-bold text-contrast-min text-ossdarkgrey" x-html="deliveryText"></div>
    </div>
    <script type="text/javascript">
        function countDownTimer() {
            return {
                deliveryData: {},
                deliveryText: "Fetching Delivery Info...",
                async initCountdownTimer() {
                    try {
                        let url = '<?= $this->getUrl("countdowntimer/index/index") ?>'
                        const request = await fetch(url + '?ajax=1&form_key=' + hyva.getFormKey(), {
                            method: 'post',
                        });
                        this.deliveryData = await request.json();
                    } catch (err) {
                        console.warn(err);
                    }

                    // setup initial countdown display
                    // set defaults
                    var replaceTimer = "<?= $block->escapeJs("<span id=\"dynamicCountdown\" class=\"font-bold\">" . __("hours") . " ?? " . __("minutes")." ?? " . __("seconds") . "</span>"); ?>";
                    var tokenTimer = "{{TIMERS}}";
                    var tokenDate = "{{DATE}}";
                    var countdown_text = "<?= $block->escapeJs($this->returnCountdownText()); ?>";

                    // format our display
                    var startStr = countdown_text.replace(tokenTimer,replaceTimer);
                    var finalStr = startStr.replace(tokenDate, this.deliveryData.delivery_date);

                    // set display
                    this.deliveryText = ''+finalStr+'';

                    // execute countdown timer
                    this.CountDownTimer('#dynamicCountdown', this.deliveryData.cutoff, this.deliveryData.now);
                },
                CountDownTimer(id, dt, dn){
                    var self = this;
                    let end = new Date(dt);
                    let _second = 1000;
                    let _minute = _second * 60;
                    let _hour = _minute * 60;
                    let _day = _hour * 24;
                    let timer;
                    let server_now = new Date(dn);
                    let client_now = new Date();
                    let global_time_offset = server_now - client_now;

                   function showRemaining() {

                        let now = new Date();
                        now.setTime(now.getTime() + global_time_offset);
                        let distance = end - now;
                        if (distance < 0) {
                            clearInterval(timer);
                            jQuery('#cd_text').html("<?php echo $block->escapeJs(__('Please refresh the page in 1 minute to see the next delivery time.')); ?>");

                            return;
                        }
                        let days = Math.floor(distance / _day);
                        let hours = Math.floor((distance % _day) / _hour);
                        let minutes = Math.floor((distance % _hour) / _minute);
                        let seconds = Math.floor((distance % _minute) / _second);

                        let days_text = '<?= $block->escapeJs(__('d')) ?> ';
                        let days_text_singular = '<?= $block->escapeJs(__('d')) ?> ';
                        let hours_text = '<?= $block->escapeJs(__('hrs')) ?> ';
                        let hours_text_singular = '<?= $block->escapeJs(__('hr')) ?> ';
                        let minutes_text = '<?= $block->escapeJs(__('mins')) ?> ';
                        let minutes_text_singular = '<?= $block->escapeJs(__('min')) ?> ';
                        let seconds_text = '<?= $block->escapeJs(__('secs')) ?>';
                        let seconds_text_singular = '<?= $block->escapeJs(__('sec')) ?>';

                        if(days == 1) days_text = days_text_singular;
                        if(hours == 1) hours_text = hours_text_singular;
                        if(minutes == 1) minutes_text = minutes_text_singular;
                        if(seconds == 1) seconds_text = seconds_text_singular;

                        let outstring = "";
                        if(days != 0){outstring = days + days_text;}
                        if(hours != 0){outstring += hours + hours_text;}
                        outstring +=  minutes + minutes_text;
                        outstring += '<span>' + seconds + seconds_text + '</span>';

                        document.getElementById('dynamicCountdown').innerHTML = outstring;
                    }

                    timer = setInterval(showRemaining, 1000);
                },
            }
        }
    </script>
<?php } ?>
