<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Block\Product\View;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Aitoc\PreOrders\Helper\Settings as SettingsHelper;
use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Aitoc\PreOrders\Api\Data\Source\PaymentTypeInterface;
use Magento\Framework\Registry;
use Magento\Framework\Exception\LocalizedException;


class SubscribeToNotification extends Template
{
    /**
     * @var SettingsHelper
     */
    private $settingsHelper;

    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @var Registry
     */
    private $registry;

    /**
     * @param Context $context
     * @param SettingsHelper $settingsHelper
     * @param PreOrderHelper $preOrderHelper
     * @param Registry $registry
     * @param array $data
     */
    public function __construct(
        Context $context,
        SettingsHelper $settingsHelper,
        PreOrderHelper $preOrderHelper,
        Registry $registry,
        array $data = []
    ) {
        $this->settingsHelper = $settingsHelper;
        $this->preOrderHelper = $preOrderHelper;
        $this->registry = $registry;
        parent::__construct($context, $data);
    }

    /**
     * @return string
     */
    public function getFormAction()
    {
        return $this->getUrl('preorders/notification/subscribe');
    }

    /**
     * @return int
     */
    public function getProductId()
    {
        $product = $this->registry->registry('product');
        return $product->getId();
    }

    /**
     * @return bool
     * @throws LocalizedException
     */
    public function canShow()
    {
        $result = false;
        if ($this->settingsHelper->getPaymentTypeSetting() == PaymentTypeInterface::TYPE_NOTIFICATION) {
            $productId = $this->getProductId();
            if ($this->preOrderHelper->isProductPreOrder($productId)) {
                $result = true;
            }
        }
        return $result;
    }
}