<?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var $block \Magento\Catalog\Block\Product\View */
?>
<?php $_product = $block->getProduct(); ?>
<?php $buttonTitle = __('Add to Cart'); ?>
<?php $dailydealhelper=$this->helper('Smartwave\Dailydeals\Helper\Data'); ?>
<?php if ($_product->isSaleable()): ?>
<div class="box-tocart">
    <?php if($block->getRequest()->getParam('dailydealproduct') || $dailydealhelper->isDealProduct($_product->getId())) : ?>
       <?php $productSku=$_product->getSku(); ?>
    <input type="text" id="todate" value="<?php echo $dailydealhelper->getDailydealToDate($productSku); ?>" style="display:none;" >
    <input type="text" style="display: none;" id="fromdate" value="<?php echo $dailydealhelper->getDailydealFromDate($productSku); ?>">
    <p id="countdown"></p>
    <div class="sw-dailydeal-wrapper">
      <div class="sw-dailydeal">
        <?php if($block->getRequest()->getParam('dailydealproduct')) :?>
            <p id="expired"></p> 
        <?php endif; ?>
        <div class="countdowncontainer" style="display:none;">
            <span class="dailydeal-label">
                <?php echo __('Offer Ends In:'); ?>
            </span>
            <span class="number-wrapper">
                <div class="line"></div>
                <span class="number day"><p id="countdown_days"></p></span>
                <div class="caption"><?php echo __('Days'); ?></div>
            </span>

            <span class="number-wrapper">
                <div class="line"></div>
                <span class="number hour"><p id="countdown_hours"></p></span>
                <div class="caption"><?php echo __('Hours'); ?></div>
            </span>

            <span class="number-wrapper">
                <div class="line"></div>
                <span class="number min"><p id="countdown_minutes"></p></span>
                <div class="caption"><?php echo __('Minutes'); ?></div>
            </span>

            <span class="number-wrapper">
                <div class="line"></div>
                <span class="number sec"><p id="countdown_seconds"></p></span>
                <div class="caption"><?php echo __('Seconds'); ?></div>
            </span>
        </div>
      </div>
    </div>
    <?php endif; ?>
    <div class="fieldset">
        <?php if ($block->shouldRenderQuantity()): ?>
        <div class="field qty">
            <label class="label" for="qty"><span><?php /* @escapeNotVerified */ echo __('Qty') ?>:</span></label>
            <div class="control">
                <input type="number"
                       name="qty"
                       id="qty"
                       maxlength="12"
                       value="<?php /* @escapeNotVerified */ echo $block->getProductDefaultQty() * 1 ?>"
                       title="<?php /* @escapeNotVerified */ echo __('Qty') ?>" class="input-text qty"
                       data-validate="<?php echo $block->escapeHtml(json_encode($block->getQuantityValidators())) ?>"
                       />
                <div class="qty-changer">
                    <a href="javascript:void(0)" class="qty-inc"><i class="porto-icon-up-dir"></i></a>
                    <a href="javascript:void(0)" class="qty-dec"><i class="porto-icon-down-dir"></i></a>
                </div>
            </div>
        </div>
        <?php endif; ?>
        <div class="actions">
            <button type="submit"
                    title="<?php /* @escapeNotVerified */ echo $buttonTitle ?>"
                    class="action primary tocart"
                    id="product-addtocart-button">
                <span><?php /* @escapeNotVerified */ echo $buttonTitle ?></span>
            </button>
            <?php echo $block->getChildHtml('', true) ?>
        </div>
    </div>
</div>
<?php endif; ?>
<?php if ($block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "Magento_Catalog/product/view/validation": {
                "radioCheckboxClosest": ".nested"
            }
        }
    }
</script>
<?php else : ?>
<script>
    require([
        'jquery',
        'mage/mage',
        'Magento_Catalog/product/view/validation',
        'Magento_Catalog/js/catalog-add-to-cart'
    ], function ($) {
        'use strict';

        $('#product_addtocart_form').mage('validation', {
            radioCheckboxClosest: '.nested',
            submitHandler: function (form) {
                var widget = $(form).catalogAddToCart({
                    bindSubmit: false
                });

                widget.catalogAddToCart('submitForm', $(form));

                return false;
            }
        });
    });
</script>
<?php endif; ?>
<script type="text/javascript">
require([
    'jquery'
], function ($) {
    var app = {
        isAppleDevice: function() {
          if (navigator.userAgent.match(/(iPhone|iPod|iPad|Safari)/) != null) {
            return true;
          }
          return false;
        }
    }
    // Timer for LEFT time for Dailydeal product
    var _second = 1000;
    var _minute = _second * 60;
    var _hour = _minute * 60;
    var _day = _hour * 24;
    var timer;

    function showRemaining(currentdate) {
      var cid='countdown';
      var startdateid='fromdate';
      var id='todate';
      var daysid='countdown_days';
      var hoursid='countdown_hours';
      var minutesid='countdown_minutes';
      var secondsid='countdown_seconds';

      var enddate = new Date($('#'+id).val());
      var dealstartdate=new Date($('#'+startdateid).val());
      if (app.isAppleDevice() && $('#'+id).val() && $('#'+startdateid).val()) {
        var edate = $('#'+id).val();
        var edateParts = edate.substring(0,10).split('-');
        var etimePart = edate.substr(11);
        enddate = edateParts[1] + '/' + edateParts[2] + '/' + edateParts[0] + ' ' + etimePart;
        enddate = new Date(enddate).getTime();

        var sdate = $('#'+startdateid).val();
        var sdateParts = sdate.substring(0,10).split('-');
        var stimePart = sdate.substr(11);
        dealstartdate = sdateParts[1] + '/' + sdateParts[2] + '/' + sdateParts[0] + ' ' + stimePart;
        dealstartdate = new Date(dealstartdate).getTime();
      }
      // Get Current Date from magentodatetime

      var currentdate=new Date(currentdate).getTime();
      //Get Difference between Two dates
      var distance = enddate - currentdate;
      if (distance < 0) {
        $('#expired').html("<div class='offermessage' >EXPIRED!</div>");
      } else if(dealstartdate > currentdate) {
        $('.countdowncontainer').hide();
        var msg="<div class='offermessage' > Coming Soon..<br>Deal Start at:<br>"+$('#'+startdateid).val()+"</div>";
        $('#expired').html(msg);
      } else {
        var days = Math.floor(distance / _day);
        var hours = Math.floor((distance % _day) / _hour);
        var minutes = Math.floor((distance % _hour) / _minute);
        var seconds = Math.floor((distance % _minute) / _second);
        if(hours < 10)
            hours = "0" + hours;
        if(minutes < 10)
            minutes = "0" + minutes;
        if(seconds < 10)
            seconds = "0" + seconds;
        $('.countdowncontainer').show();
        $('#'+daysid).html(days);
        $('#'+hoursid).html(hours);
        $('#'+minutesid).html(minutes);
        $('#'+secondsid).html(seconds);
      }
    }

    //Set date as magentodatetime
    var date = new Date('<?php echo $dailydealhelper->getcurrentDate() ?>');
    if (app.isAppleDevice()) {
      var mdate = '<?php echo $dailydealhelper->getcurrentDate() ?>';
      var dateParts = mdate.substring(0,10).split('-');
      var timePart = mdate.substr(11);
      date = dateParts[1] + '/' + dateParts[2] + '/' + dateParts[0] + ' ' + timePart;
      date = new Date(date);
    }
    var day   = date.getDate();
    var month = date.getMonth();
    var year  = date.getFullYear();
    var hours = date.getHours();
    var minutes = "0" + date.getMinutes();
    var seconds = "0" + date.getSeconds();

    var fulldate = year+'/'+(month+1)+'/'+day+' '+hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
    // Set Interval
    timer = setInterval(function()
    {
        date.setSeconds(date.getSeconds() + 1);
        var month=date.getMonth();
        var currentdatetime=date.getFullYear()+"/"+(month+1)+"/"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
        showRemaining(currentdatetime);
    }, 1000);
});
</script>