<?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');
$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);
/* if (isset($breakpoints['mobile']['options'])) {
    if ($mbSize = (float)$helper->getConfig('images/product/product_base_image_width_mobile')) {
        $breakpoints['mobile']['options']['options']['width'] = $mbSize;
    }
    if ($mbSize = (float)$helper->getConfig('images/product/product_base_image_height_mobile')) {
        $breakpoints['mobile']['options']['options']['height'] = $mbSize;
    }
} */

$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' => (float)$helper->getConfig('pages/product_view/moreview_margin'),
];
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
];
$maxRatio = $helper->getConfig('images/product/max_ratio');
$maxRatio = $maxRatio ? (float) $maxRatio : false;
?>
<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 $gal = $(this).addClass('loaded'), img = new Image(), conf = <?= json_encode($galleryConfig) ?>;
        function adjustOptions(conf, ratio) {
            $gal.css('max-width',''); var contwidth = $gal.width(), opt = conf.options, width, height;
            <?php if ($maxRatio) : ?>ratio = Math.min(<?= $maxRatio ?>, ratio);<?php endif ?>
            if (opt.navdir == 'horizontal') {
                opt.thumbwidth = Math.min(contwidth/4, opt.thumbwidth);
            }
            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);
            if ((window.innerWidth > 767) && $gal.parents('.pdif-sticky-col').length && (opt.navdir == 'horizontal')) {
                height = Math.min(height, window.outerHeight - conf.options.thumbheight - 260);
                width = height / 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 dG = $gal.data('gallery');
                if (dG) {dG.updateOptions(adjustOptions(dG.fotorama, ratio).options); $(window).trigger('resize');}
            }
            updateGallery();
            $gal.on('gallery:loaded', function() {  setTimeout(updateGallery, 200); }).on('fotorama:fullscreenexit', updateGallery);
            $(window).on('cdz_window_width_changed', function() {  setTimeout(updateGallery, 300); });
        });
        img.src = '<?= $mainImageData ?>';
    });
});
</script>