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

/**
 * @var $block \Magento\Catalog\Block\Product\View
 */
?>
<?php
$_helper = $this->helper(Magento\Catalog\Helper\Output::class);
$_product = $block->getProduct();
$ampHelper = $this->helper(Codazon\GoogleAmpManager\Helper\Data::class);
$submitUrl = $ampHelper->filterUrl($ampHelper->filterCartUrl(
    $block->escapeUrl($block->getSubmitUrl($_product))
));
$hasCustomOptions = false;
if ($optionsBlock = $this->getLayout()->getBlock('product.info.options')) {
    $hasCustomOptions = count($optionsBlock->decorateArray($optionsBlock->getOptions())) > 0;
}
$allowDisplayOptions = in_array($_product->getTypeId(), ['configurable', 'downloadable', 'grouped']);
?>

<div class="product-add-form">
    <form data-product-sku="<?= $block->escapeHtmlAttr($_product->getSku()) ?>"
        action-xhr="<?= $submitUrl ?>" method="post"
        id="product_addtocart_form"<?php if ($_product->getOptions()) :?> enctype="multipart/form-data"<?php endif; ?>
        on="submit: AMP.setState({addtocart_text: '<?= __('Adding ...') ?>'});
        submit-success: AMP.setState({
            addtocart_text: '<?= __('Add to Cart') ?>'
        }), cartInfo.refresh, cdz-minicart-list.refresh"
    >
        <input type="hidden" name="ajax" value="1" />
        <input type="hidden" name="product" value="<?= (int)$_product->getId() ?>" />
        <input type="hidden" name="selected_configurable_option" value="" />
        <input type="hidden" name="related_product" id="related-products-field" value="" />
        <input type="hidden" name="item"  value="<?= (int)$block->getRequest()->getParam('id') ?>" />
        <?= $block->getBlockHtml('formkey') ?>
        <?php if (!$block->hasOptions()) :?>
            <?= $block->getChildHtml('product_info_form_content') ?>
        <?php else : ?>
            <?php if ($hasCustomOptions || !$allowDisplayOptions) : ?>
                <?= $block->getBlockHtml('amp_product_options_reference'); ?>
            <?php else : ?>
                <?= $block->getChildChildHtml('options_container') ?>
            <?php endif ?>
        <?php endif ?>
        <div submit-success>
            <template type="amp-mustache">
                {{#message}}
                <p class="cdz-amp-msg {{message_type}}">
                    <span class="cdz-amp-text">{{{message}}}</span>
                    {{#success}}
                    <a class="cdz-amp-link" href="{{cart_url}}"><?= __('View cart') ?></a>
                    {{/success}}
                </p>
                {{/message}}
            </template>
        </div>
    </form>
</div>