<?php
/**@var \Magetop\Advancepreview\Block\AdvancePreview $block */

$type =  $block->getRequest()->getParam('type',1);
$token = $this->getRequest()->getParam('token','');
$token = trim($token);
if($token != '') : ?>
<?php
if($type == 1) {
    $itemId = $block->getRequest()->getParam('item_id',0);
    $url = $block->getUrl('advance_preview/product/exportPdfOffer/item_id/'.$itemId.'/token/'.$token);
}
elseif($type == 3) {
    $invoiceId = $block->getRequest()->getParam('invoice_id',0);
    $itemId = $block->getRequest()->getParam('item_id',0);
    $url = $block->getUrl('advance_preview/order/printInvoice/').'invoice_id/'.$invoiceId.'/item_id/'.$itemId.'/token/'.$token;
}
else {
    $orderId = $block->getRequest()->getParam('order_id',0);
    $url = $block->getUrl('advance_preview/order/downloadPdf/order_id/'.$orderId.'/token/'.$token);
}

?>
<div id="preview-custom-download">
    <div>
        <span id="preview-download-count-down"></span>
    </div>
    <div>
        <a href="<?php echo $url ?>"><?php echo __('Click here if file was not download automatically') ?></a>
    </div>


</div>
<input type="hidden" id="txt-download-url" value="<?php echo $url; ?>">
<input type="hidden" id="txt-custom-download-text1" value="<?php echo __('File will be downloaded after')  ?>">
<input type="hidden" id="txt-custom-download-text2" value="<?php echo __('sec')  ?>">
<input type="hidden" id="txt-custom-download-text3" value="<?php echo __('Start downloading...')  ?>">
<script>
    require([
        'jquery',
        'mage/translate'
    ],function ($,$tr) {
        var url = $('#txt-download-url').val();
        var sec = 3;
        var tinner = setInterval(function () {
            console.log(sec);
            var text = $("#txt-custom-download-text1").val() + ' ' + sec + ' ' +  $("#txt-custom-download-text2").val();
            $('#preview-download-count-down').html(text);
            if(sec == 0) {
                window.location.href = url;
                var startText =  $("#txt-custom-download-text3").val();
                $('#preview-download-count-down').html(startText);
                clearInterval(tinner);
            }
            sec--;
        },1000)
        setTimeout(function () {
            clearInterval(tinner);
        },5000)
    })
</script>
<?php else : ?>
    <div>
       <?php echo __('File not found, please check again or contact admin'); ?>
    </div>
<?php endif; ?>
