<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
// @codingStandardsIgnoreFile
/**
 * Product media data template
 *
 * @var $block \Magento\Catalog\Block\Product\View\Gallery
 */
?>

<?php
$helper = $this->helper('Codazon\ThemeLayoutPro\Helper\Data');
$navDir = $helper->getConfig('pages/product_view/moreview_style')?:$block->getVar("gallery/navdir");
$thumbWidth = $helper->getConfig('images/product/product_moreview_image_width')?:$block->getImageAttribute('product_page_image_small', 'width');
$thumbHeight = $helper->getConfig('images/product/product_moreview_image_height')?:$block->getImageAttribute('product_page_image_small', 'height');
$thumbHeight = (70/$thumbWidth) * $thumbHeight;
$thumbWidth = 70;
$width = (float)$helper->getConfig('images/product/product_base_image_width')?:$block->getImageAttribute('product_page_image_medium', 'width');
$height = (float)$helper->getConfig('images/product/product_base_image_height')?:$block->getImageAttribute('product_page_image_medium', 'height');
$manifier = $block->getVar('magnifier');
$enableManifier = (bool)$helper->getConfig('pages/product_view/enable_zoom_lens');
$innerZoomConfig = false;
if ($enableManifier) {
    $innerZoom = (bool)$helper->getConfig('pages/product_view/inner_zoom');
    if ($innerZoom) {
        $manifier['enabled'] = false;
        $innerZoomConfig = [
            'themewidgets' => [
                'codazon.innerZoom' => [
                    'width'     => (float)$helper->getConfig('pages/product_view/lens_width'),
                    'height'    => (float)$helper->getConfig('pages/product_view/lens_height'),
                    'zoomRatio' => (float)$helper->getConfig('pages/product_view/inner_zoom_ratio'),
                ]
            ]
        ];
        $innerZoomConfig = json_encode($innerZoomConfig);
    } else {
        $manifier['enabled'] = $enableManifier;
        $manifier['width'] = (float)$helper->getConfig('pages/product_view/lens_width');
        $manifier['height'] = (float)$helper->getConfig('pages/product_view/lens_height');
        $manifier['top'] = '0';
        $manifier['mode'] = 'outside';
        $meidaSide = $block->getData('media_side') ? : 'left';
        $rtl = (bool)$helper->getConfig('themelayoutpro/general/enable_rtl');
        if ($meidaSide == 'right') {
            $manifier['left'] = (!$rtl) ? ((string)-$manifier['width']) : '100%';
        } else {
            $manifier['left'] = (!$rtl) ? '100%' : (string)-$manifier['width'];
        }
    }
} else {
    $manifier['enabled'] = false;
}
$manifier['fullscreenzoom'] = (int)$helper->getConfig('pages/product_view/fullscreenzoom') ? : $manifier['fullscreenzoom'];
$showCaption = (int)$helper->getConfig('pages/product_view/show_caption');
$labelHelper = $this->helper('Codazon\ProductLabel\Helper\Data');
$showLabel = (bool)$helper->getConfig('pages/product_view/display_product_labels');
$showOnRight = (bool)$helper->getConfig('pages/product_view/display_labels_on_right');
$_product = $this->getProduct();
$labelClass = $showOnRight ? 'right' : 'left';
$labelStyle = ((!$showOnRight) && ($navDir == 'vertical'))? "style=\"left: {$thumbWidth}px\"":'';

$images = $block->getGalleryImages()->getItems();
$mainImage = current(array_filter($images, function ($img) use ($block) {
    return $block->isMainImage($img);
}));
if (!empty($images) && empty($mainImage)) {
    $mainImage = $block->getGalleryImages()->getFirstItem();
}
$mainImageData = $mainImage ? $mainImage->getData('medium_image_url') : $this->helper('Magento\Catalog\Helper\Image')->getDefaultPlaceholderUrl('image');
$breakpoints = json_decode($block->getBreakpoints(), true);

$options = [
    'nav' => $block->getVar("gallery/nav"),
    'showCaption' => $showCaption,
    'width' => $width,
    'height' => $height,
    'thumbwidth' => (float)$thumbWidth,
    'thumbheight' => (float)$thumbHeight,
    'transition' => $block->getVar("gallery/transition/effect"),
    'navtype' => $block->getVar("gallery/navtype"),
    'navdir' => $navDir,
    'thumbmargin' => 10,
];
if ($temp = $block->getVar("gallery/loop")) {
    $options['loop'] = $temp;
}
if ($temp = $block->getVar("gallery/keyboard")) {
    $options['keyboard'] = $temp;
}
if ($temp = $block->getVar("gallery/arrows")) {
    $options['arrows'] = $temp;
}
if ($temp = $block->getVar("gallery/allowfullscreen")) {
    $options['allowfullscreen'] = $temp;
}
if ($temp = $block->getVar("gallery/transition/duration")) {
    $options['transitionduration'] = (float)$temp;
}
if ($temp = $block->getVar("gallery/navarrows")) {
    $options['navarrows'] = $temp;
}
if ($temp = $block->getVar("gallery/allowfullscreen")) {
    $options['allowfullscreen'] = $temp;
}
$fullscreen = [
    'nav' => $block->getVar("gallery/fullscreen/nav"),
    'navdir' => $navDir,
    'navtype' => $block->getVar("gallery/fullscreen/navtype"),
    'transition' => $block->getVar("gallery/fullscreen/transition/effect"),
];
if ($temp = $block->getVar("gallery/fullscreen/loop")) {
    $fullscreen['loop'] = $temp;
}
if ($temp = $block->getVar("gallery/fullscreen/navarrows")) {
    $fullscreen['navarrows'] = $temp;
}
if ($temp = $block->getVar("gallery/fullscreen/navarrows")) {
    $fullscreen['navarrows'] = $temp;
}
if ($temp = $block->getVar("gallery/fullscreen/arrows")) {
    $fullscreen['arrows'] = $temp;
}
if ($temp = $block->getVar("gallery/fullscreen/caption")) {
    $fullscreen['showCaption'] = $temp;
}
if ($temp = $block->getVar("gallery/fullscreen/transition/duration")) {
    $fullscreen['transitionduration'] = (float)$temp;
}
$galleryConfig = [
    'mixins'        => ['magnifier/magnify'],
    'magnifierOpts' => $manifier,
    'data'          => json_decode($block->getGalleryImagesJson()),
    'options'       => $options,
    'fullscreen'    => $fullscreen,
    'breakpoints'   => $breakpoints
];
?>
<div class="gallery-container">
    <?php if ($showLabel) : ?>
    <div class="<?= $labelClass ?> label-wrap <?= $navDir ?>" data-role="label-wrap" <?= $labelStyle ?>>
        <?= $showLabel?$labelHelper->showLabel($_product):''; ?>
    </div>
    <?php endif ?>
    <div class="gallery-placeholder _block-content-loading" <?= $innerZoomConfig ? "data-mage-init='{$innerZoomConfig}'" : '' ?> data-gallery-role="gallery-placeholder">
        <img alt="main product photo" class="gallery-placeholder__image" src="<?= $mainImageData ?>" />
    </div>
</div>
<script type="text/x-magento-init">
{
    "[data-gallery-role=gallery-placeholder]": {
        "mage/gallery/gallery": <?= json_encode($galleryConfig) ?>
    }
}
</script>
<script>
require(['jquery'], function($, themewidgets) {
    $('[data-gallery-role=gallery-placeholder]:not(.loaded)').each(function() {
        var $gallery = $(this).addClass('loaded'), img = new Image(), conf = <?= json_encode($galleryConfig) ?>;
        function adjustOptions(conf, ratio) {
            var contwidth = $gallery.width(), opt = conf.options, width, height;
            if ((window.innerWidth > 767) && (opt.navdir == 'vertical')) {
                width = contwidth;
                height = (contwidth - opt.thumbwidth - opt.thumbmargin) * ratio + opt.thumbmargin*2;
            } else {
                width = contwidth;
                height = contwidth * ratio;
            }
            conf.options.thumbheight = Math.round(opt.thumbwidth * ratio);
            conf.options.width = width;
            conf.options.height = height;
            return conf;
        }
        $(img).on('load', function() {
            var $img = $(this), ratio = img.height/img.width;
            var updateGallery = function() {
                var dataGallery = $gallery.data('gallery');
                if (dataGallery) {
                    dataGallery.updateOptions(adjustOptions(dataGallery.fotorama, ratio).options);
                }
            }
            updateGallery();
            $gallery.on('gallery:loaded fotorama:fullscreenexit', updateGallery);
            $(window).on('cdz_window_width_changed', updateGallery);
        });
        img.src = '<?= $mainImageData ?>';
    });
});
</script>