<?php

namespace Nublue\CountdownTimer\Block;

use Magento\Catalog\Block\Product\View\AbstractView;
use Magento\Catalog\Block\Product\Context;
use Magento\Framework\Stdlib\ArrayUtils;
use Magento\Store\Model\ScopeInterface;

class Timer extends AbstractView
{
    /**
     * Configuration keys
     */
    const CONFIG_KEY_TIMEZONE = 'general/locale/timezone';
    const CONFIG_KEY_ENABLE = 'countdowntimer/nb_shipping_settings/enable';
    const CONFIG_KEY_COUNTDOWN_TIME = 'countdowntimer/nb_shipping_settings/countdown_time';
    const CONFIG_KEY_HIDE_UNSALEABLE = 'countdowntimer/nb_shipping_settings/hide_unsaleable';

    /**
     * @param Context $context
     * @param ArrayUtils $arrayUtils
     * @param array $data
     */
    public function __construct(Context $context, ArrayUtils $arrayUtils, array $data = []) {
        parent::__construct(
            $context,
            $arrayUtils,
            $data
        );

        date_default_timezone_set($this->getConfigValue(self::CONFIG_KEY_TIMEZONE)); 
    }

    /**
     * Is timer enabled?
     * @return string
     */
    public function returnEnabled()
    {
        return $this->getConfigValue(self::CONFIG_KEY_ENABLE);
    }

    /**
     * Get countdown text
     * @return string
     */
    public function returnCountdownText()
    {
        return $this->getConfigValue(self::CONFIG_KEY_COUNTDOWN_TIME);
    }
    
    /**
     * Check if the timer should be visible on this product
     * @return boolean
     */
    public function getVisibleOnProduct()
    {
        $product = $this->getProduct();
        $isVisible = true;
        
        // Hide if product is not available for sale.
        if (
            $this->getConfigValue(self::CONFIG_KEY_HIDE_UNSALEABLE) === '1' &&
            !$product->isSalable()
        ) {
            $isVisible = false;
        }
        
        return $isVisible;
    }
    
    /**
     * Getter for magento configuration values
     * @param string $path
     * @return string
     */
    public function getConfigValue($path)
    {
        return $this->_scopeConfig->getValue($path, ScopeInterface::SCOPE_STORE);
    }
}