<?php
/**
 * @var $this \yii\web\View
 * @var $model \app\models\front\News
 */

use yii\helpers\ArrayHelper;
use app\modules\ldjson\jsonLD;
use yii\web\UrlManager;
use app\models\Authors;
use app\models\base\Image;
use \app\models\news;
use yii\helpers\Url;

/*
$this->registerJsFile('https://platform-api.sharethis.com/js/sharethis.js#property=63ecb32f4a4876001374e328&product=inline-reaction-buttons',  [
    'position' => $this::POS_END,
    'async' => 'async',
    'defer' => 'defer'
]);
*/

$preview = $model->image;

$retina = $preview->getUrl(Image::SIZE_HD,"jpg");
$normal = $preview->getUrl(Image::SIZE_1040x586,"webp");
$bad = $preview->getUrl(Image::SIZE_680x383,'jpg');

$bad = $bad?$bad:'/images/default.jpg';

if( $retina === false || $normal === false ){
	$normal = $bad;
	$retina = $bad;
}
$normal .= "?v=".$model->rev;
$retina .= "?v=".$model->rev;
$bad .= "?v=".$model->rev;
/*
 После этой даты не выводить фото до подтверждения юриста
if( isset( $model->dt_pub ) && strtotime( $model->dt_pub ) < strtotime('2015-01-01 00:00:00') ){
	$bad = '/images/default.jpg';
	$normal = $bad;
	$retina = $bad;
};
 */

Yii::$app->og->title =($model->meta_title)?$model->meta_title:$model->title;
Yii::$app->og->description = ($model->lid && trim($model->lid) <> '')?str_replace( '"', "&quot;", strip_tags($model->lid) ):trim(str_replace( '"',"'",substr(strip_tags( $model->text ),0,150)))."...";

if( $model->active == 'N' || $model->dt_pub > date("Y-m-d H:i:s") || $model->noindex == 'Y' ){
    Yii::$app->og->noindex = 'Y';
}else{
    \Yii::$app->og->canonical = $model->getUrl(true);
    \Yii::$app->og->amp = Url::base('https').'/amp/news/'.$model->id;
    \Yii::$app->og->og_url = $model->getUrl(true);
    \Yii::$app->og->og_image = $model->image->url;
    \Yii::$app->og->og_type = "article";
    \Yii::$app->og->og_title = htmlspecialchars(($model->meta_title)?strip_tags(str_replace( '"',"&quot;",$model->meta_title)):strip_tags(str_replace( '"',"&quot;",$model->title)));
    \Yii::$app->og->og_description = ($model->lid && trim($model->lid) <> '')?str_replace( '"',"&quot;",strip_tags($model->lid)):trim(str_replace( '"',"&quot;",substr(strip_tags( $model->text ),0,150)))."...";
    \Yii::$app->og->dtpub = date( "r", strtotime( $model->dt_pub ) );
}

jsonLD::addAmicORG();
jsonLD::news( $model->title, preg_replace('/\s+/', ' ', str_replace( ["\n","\r"],' ',Yii::$app->og->description)), $model->image->url, $model->dt_pub, $model->getUrl(), $model->uid, $model->text, $model->meta_title);
jsonLD::addfaq($model->text, $model->title);
$story = new \app\models\base\Story();
$this->params['breadcrumbs'] = [
    [
        "text"=>"НОВОСТИ",
        "url"=>"/news"
    ]
];
$this->params['context'] = "post-view";
//$topic = ArrayHelper::getValue($model->topics,0);

$topic = Yii::$app->cache->getOrSet('topic-news-'.$model->id, function ()  use($model){
    return $model->getTopics()->andWhere(['show'=>"Y","active"=>1])->one();
}, News::$keysCache['topic-news-##']);

if($topic instanceof \app\models\base\NewsTopic){
    $this->params['breadcrumbs'][] =
        [
            "text"=>$topic->title,
            "url"=>"/news/".mb_strtolower($topic->url)
        ];
}
$i = 1;
foreach($this->params['breadcrumbs'] as $el){
	jsonLD::addBreadcrumb($i, $el['url'], $el['text']);
	$i++;
}

if( $model->show_author == 'Y' )
{
	$author = Authors::getAuthor( $model->author );
	$authorName = $author->name;
	\Yii::$app->og->author =$authorName;
	jsonLD::author( $authorName );
}else{
	$authorName = 'ИА Амител';
	jsonLD::author( $authorName, false );
}
if( strstr( $model->text, 'id="widgetseting"' ) && strstr( $model->text, 'windows="100"' ) ) $model->type = 2; //старый стиль широкой страницы
$GLOBALS['type_long'] = ($model->type == 6); //лонгрид

?>
<?php if(!is_null($model->embed_url) && $model->embed_url!=''):?>
<div class="row">
    <div class="col-md-12 mb-5">
        <div class="picture-cont-16x9">
            <picture class="w-100 youtube-iframe-placeholder" data-link="<?=$model->getYoutubeEmbedLink()?>">
                <source srcset="<?=$preview->getUrl(Image::SIZE_680x383,"jpg")?>" media="(min-width: 600px)">
                <source srcset="<?=$preview->getUrl(Image::SIZE_680x383,"webp")?>" media="(min-width: 600px)">
                <img src="<?=$preview->getUrl(Image::SIZE_680x383)?>" alt="<?=$model->photo_title?>" class="w-100" loading="lazy">
            </picture>
        </div>
    </div>
</div>
<?php endif;?>
<div class="row">
    <div class="<?=($model->type == 2 || $model->type == 6)?'col-md-12':'col-md-8'?>">
        <div id="post" class="post">
<?
	if( Yii::$app->user->can('editor') ){
?>
<span style="position: absolute;background-color: #a9a9a924;right: 30px;top: 10px; box-shadow: 2px 5px 5px 3px #888;"><img onclick="location='/manager/news/update?id=<?=$model['id']?>'" src="/img/edit.svg" width="25px" height="25px" style="padding:3px;cursor:pointer;"><img onclick="navigator.clipboard.writeText('https://www.amic.ru/news/<?=$model['id']?>');elementPopup(this,'Ссылка скопирована в буфер обмена');" src="/img/share-boxed.svg" width="25px" height="25px" style="padding:3px;margin-top: 2px;cursor:pointer;" ></span>
<?
	}
?>
            <?=$this->render("/layouts/breadcrumbs")?>
            <h1><?=$model->title?></h1>
            <p class="lead"><?=$model->lid?></p>
            <p class="published_at"><?=$model->getPublishedNorm()?>, <?=$authorName?> <?= ($model->mark!="" && !is_null($model->mark)) ? \yii\helpers\Html::tag('span', $model->mark,['class'=>'float-right']) : ""?></p>
            <p class="share_and_comment">
                <a href="#comments" class="comments_btn">Комментировать</a>
                <a onclick="Share.vkontakte('<?=Yii::$app->og->og_url?>','<?=addslashes(Yii::$app->og->og_title)?>','<?=Yii::$app->og->og_image?>','<?=str_replace( '"',"&quot; ",Yii::$app->og->og_description)?>')" href="#">
                    <svg class="icon icon-vk"><use xlink:href="/svg/symbol/sprite-clear.svg#vk"></use></svg>
                </a>
                <a onclick="Share.odnoklassniki('<?=Yii::$app->og->og_url?>','<?=addslashes(Yii::$app->og->og_title)?>','<?=Yii::$app->og->og_image?>','<?=str_replace( '"',"&quot; ",Yii::$app->og->og_description)?>')" href="#">
                    <svg class="icon icon-ok"><use xlink:href="/svg/symbol/sprite-clear.svg#ok"></use></svg>
                </a>
                <a onclick="navigator.clipboard.writeText('<?=Yii::$app->og->og_url?>'); elementPopup(this,'Ссылка скопирована в буфер обмена')" class="copy-link" href="#">
                    <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 8 8">
                        <use href="/img/share-boxed.svg#share"></use>
                    </svg>
                </a>
            </p>
            <p>
                <?php if($model->photo_include == 'Y' && $model->image instanceof \app\models\base\Image):?>
                    <div class="picture-cont-16x9">
                        <picture class="w-100">
                            <source srcset="<?=$normal?>, <?=$retina?> 2x" media="(min-width: 600px)">
                            <img src="<?=$bad?>" alt="<?=htmlentities($model->photo_title,ENT_QUOTES)?>" title="<?=htmlentities($model->photo_title,ENT_QUOTES)?>" class="w-100">
                        </picture>
                    </div>

                    <div class="image-title"><?=$model->photo_title?></div>
                <?php endif;?>
            </p>
            <section class="text">
                <?=$model->renderBody()?>
                 <?=($model->inscription == 2)?'<span class="advertisement">Реклама</span>':''?>
                 <?=($model->inscription == 1)?'<span class="advertisement">Реклама</span><br><span class="med_advertisement">Имеются противопоказания, необходима консультация специалиста</span>':''?>
                 <?=($model->inscription == 3)?'<span class="advertisement">Партнёр amic.ru</span>':''?>
            </section>
            <?php
			echo $this->render("@app/views/news/view/tags",["model"=>$model]);
?>
			<section class="share-this">
                <!-- ShareThis BEGIN -->
                <div class="sharethis-inline-reaction-buttons"></div>
                <!-- ShareThis END -->
                <div style="clear: both;"></div>
            </section>
<?
            $stn = $story->getForNews($model->id);
            if( count($stn) > 0 ){
				echo $this->render("@app/views/news/view/story",["model"=>$stn, "id"=>$model->id]);
				foreach( $stn as $a ){
					jsonLD::story( trim( stripslashes( $a['title'] ) ) );
				}
			}
            ?>
            <?php if(Yii::$app->deviceDetect->isMobile()): ?>
                <section style="height: 300px;">
                    <?=$this->render('@app/views/_etc/banners/bannerMobile3')?>
                </section>
            <?php else:?>
                <section style="height: 100px;">
                    <?=$this->render('@app/views/_etc/banners/transparant5')?>
                </section>
            <?php endif;?>
            <section class="comments" id="comments">
                <?=$this->render("view/comments/list",["model"=>$model])?>
            </section>
        </div>
    </div>
    <script>
        (function (){
            let main_view_cont = document.getElementById('post');
            let height = main_view_cont.offsetHeight;
            console.log(height)
            let style = document.createElement("style");
            style.innerHTML = "#lenta-container{ max-height:"+height+"px;}";
            main_view_cont.parentNode.append(style);
        })()
    </script>
    <div class="<?=($model->type == 2 || $model->type == 6)?'hidden':'col-md-4'?>" id="lenta-container">
        <?=$this->render("/layouts/lenta/lenta")?>
    </div>
    <div class="col-md-12">
        <h3 class="mt-3" style="font-family: Helvetica,Arial,sans-serif;
                                font-size: 20px;
                                font-weight: 700;
                                line-height: 24px;
                                color: #373e44;
                                padding-bottom: 12px;
                                padding-top: 12px;">Новости партнеров</h3>

        <?//=$this->render('@app/views/_etc/banners/partnermetrics')?>
        <div id="ferst_partner_block"></div>
<?/*
        <?=$this->render('@app/views/_etc/banners/partner3D')?>
        <?=$this->render('@app/views/_etc/banners/partner2D')?>
        <?=$this->render('@app/views/_etc/banners/partner1D')?>
*/?>
        <?php
        if(Yii::$app->deviceDetect->isMobile()){
            echo $this->render('@app/views/_etc/banners/moevideo');
        }
        ?>
    </div>
    <div class="col-md-12" id="infinity_newsfeed">
        <?=$this->render("view/infinity_newsfeed",['model'=>$model])?>
    </div>
    <div id="main-carousel" class="splide"></div>
</div>
<?php
if( strpos( $model->text, 'class="InviewElement' ) !== false ){
	echo $this->render('view/inview');
}
?>
<?php
    $this->registerJsFile("/js/splide/dist/js/splide.min.js");
    $this->registerCssFile("/js/splide/dist/css/splide.min.css")
?>
<script>
		var intersectionObserver = new IntersectionObserver(function(entries) {
			if (entries[0].intersectionRatio <= 0 || $(entries[0].target).html().length > 10 ) return;
        <?$code  = $this->render('@app/views/_etc/banners/mytarget')?>
		<?$code .= $this->render('@app/views/_etc/banners/partner3D')?>
        <?$code .= $this->render('@app/views/_etc/banners/partner2D')?>
        <?$code .= $this->render('@app/views/_etc/banners/partner1D')?>
        <?$code .= $this->render('@app/views/_etc/banners/partner4D')?>
			var code = <?=json_encode($code)?>;
			$(entries[0].target).html(code);
			console.log('загрузить партнёрский блок');
		});
    (function (){

		intersectionObserver.observe(document.querySelector('#ferst_partner_block'));

        var gallery = document.getElementById("gallery-0");
        if(gallery!==null) {
            var wrapper = document.createElement("div");
            wrapper.classList.add('gallery-wrapper')
            gallery.parentNode.insertBefore(wrapper, gallery)
            wrapper.append(gallery)
            var gallery_items = gallery.getElementsByTagName("img");
            var track = document.createElement("div");
            var list = document.createElement('ul');
            gallery.classList.add("splide")
            list.classList.add("splide__list")
            track.classList.add("splide__track")
            gallery.prepend(track)
            track.prepend(list)
            for (var i = 0; i < gallery_items.length; i++) {
                var img = gallery_items[i];
                var img_cont = document.createElement('li')
                img_cont.classList.add("splide__slide")
                img_cont.append(img)
                list.append(img_cont)
            }
            var main_view = document.createElement("div")
            main_view.classList.add("splide", "gallery-view");
            main_view.innerHTML = gallery.innerHTML;
            gallery.style.paddingBottom = "18px";
            gallery.style.marginBottom = 0;
            wrapper.prepend(main_view)
        }
        document.addEventListener( 'DOMContentLoaded', function () {
            //return true;
            const galleries = document.querySelectorAll('.gallery-view');
            if(galleries.length>0){
                for (let i=0; i < galleries.length; i++){
                    let element = galleries[i];
                    if(element !== null){
                        var main = new Splide(element, {
                            type      : 'fade',
                            rewind    : true,
                            pagination: false,
                            arrows    : true,
                            speed: 1000
                        } );

                        var thumbnails =new Splide( element.parentNode.querySelector('.gallery'), {
                            fixedWidth: 100,
                            fixedHeight: 60,
                            gap       : 10,
                            rewind    : true,
                            pagination: false,
                            isNavigation: true,
                            arrows    : false,
                        } );

                        main.sync( thumbnails );
                        main.mount();
                        thumbnails.mount();
                    }
                }
            }
            if(document.querySelector('.gallery-view') !== null){
                // var main = new Splide( '.gallery-view', {
                //     type      : 'fade',
                //     rewind    : true,
                //     pagination: false,
                //     arrows    : true,
                //     speed: 1000
                // } );
                // var thumbnails =new Splide( '.gallery', {
                //     fixedWidth: 100,
                //     fixedHeight: 60,
                //     gap       : 10,
                //     rewind    : true,
                //     pagination: false,
                //     isNavigation: true,
                //     arrows    : false,
                // } );
                //
                // main.sync( thumbnails );
                // main.mount();
                // thumbnails.mount();
            }
            let fullscreenBtn = null;
            let gallery_wrappers = document.querySelectorAll('.gallery-wrapper');
            for (let i = 0; i < gallery_wrappers.length; i++) {
                fullscreenBtn = document.createElement('div');
                fullscreenBtn.classList.add('fullscreenButton');
                gallery_wrappers[i].append(fullscreenBtn)
                fullscreenBtn.onclick = function (){
                    gallery_wrappers[i].classList.toggle('fullscreen')
                    gallery_wrappers[i].querySelectorAll('.gallery-view img').forEach(function (elem) {
                        elem.setAttribute('src', elem.dataset.original);
                    })
                }
            }
        } );
    })()
</script>
<script>
    Share = {
        vkontakte: function(purl, ptitle, pimg, text) {
            url  = 'https://vkontakte.ru/share.php?';
            url += 'url='          + encodeURIComponent(purl);
            url += '&title='       + encodeURIComponent(ptitle);
            url += '&description=' + encodeURIComponent(text);
            url += '&image='       + encodeURIComponent(pimg);
            url += '&noparse=true';
            Share.popup(url);
        },
        odnoklassniki: function(purl, text) {
            //url  = 'https://www.odnoklassniki.ru/dk?st.cmd=addShare&st.s=1';
            url  = 'https://connect.ok.ru/offer?';
            url += '&st.comments=' + encodeURIComponent(text);
            url += '&url='    + encodeURIComponent(purl);
            Share.popup(url);
        },
        facebook: function(purl, ptitle, pimg, text) {
            url  = 'http://www.facebook.com/sharer.php?s=100';
            url += '&p[title]='     + encodeURIComponent(ptitle);
            url += '&p[summary]='   + encodeURIComponent(text);
            url += '&p[url]='       + encodeURIComponent(purl);
            url += '&p[images][0]=' + encodeURIComponent(pimg);
            Share.popup(url);
        },
        twitter: function(purl, ptitle) {
            url  = 'https://twitter.com/share?';
            url += 'text='      + encodeURIComponent(ptitle);
            url += '&url='      + encodeURIComponent(purl);
            url += '&counturl=' + encodeURIComponent(purl);
            Share.popup(url);
        },
        mailru: function(purl, ptitle, pimg, text) {
            url  = 'http://connect.mail.ru/share?';
            url += 'url='          + encodeURIComponent(purl);
            url += '&title='       + encodeURIComponent(ptitle);
            url += '&description=' + encodeURIComponent(text);
            url += '&imageurl='    + encodeURIComponent(pimg);
            Share.popup(url)
        },

        popup: function(url) {
            window.open(url,'','toolbar=0,status=0,width=626,height=436');
        }
    };
    const elementPopup = function (element, text)
    {
        console.log(element)
        const positionY = element.offsetTop;
        const positionX = element.offsetLeft;
        let popup = document.createElement("div")
        popup.style.position = 'absolute';
        popup.style.top = (positionY - 35) + 'px';
        popup.style.left = positionX + "px";
        popup.style.color = "white";
        popup.style.background = "#00000052";
        popup.style.borderRadius =  "5px";
        popup.style.padding =  "1px 20px";
        popup.style.opacity = "1";
        popup.style.transition = "0.3s";
        popup.innerHTML = text
        popup.classList.add('element-popup')
        element.parentNode.append(popup)
        setTimeout(function (){
            popup.style.opacity=0
            console.log(popup.style.transition)
        },3000)
    }

</script>
<?php if($model->mark!="" && !is_null($model->mark) && is_null(\Yii::$app->request->get('erid'))):?>
    <script>
        (function (){
            const url  = new URL(location.href);
            url.searchParams.append('erid','<?=$model->mark?>')
            window.history.pushState({},'',url);
        })()
    </script>
<?php endif;?>
<script>
    (function (){
        const placeholders = document.getElementsByClassName('youtube-iframe-placeholder');
        if(placeholders.length>0){
            for(let i =0;i<placeholders.length;i++){
                placeholders[i].onclick = function (){
                    const waiting = document.createElement("div");
                    waiting.style.position = "absolute";
                    waiting.style.width = "100%";
                    waiting.style.height = "100%";
                    waiting.style.background = "url('/img/loading.gif')";
                    waiting.style.backgroundPosition = "center";
                    waiting.style.backgroundRepeat = "no-repeat";
                    waiting.style.backgroundSize = "contain";
                    waiting.style.zIndex = 1;
                    this.replaceWith(waiting);
                    const iframe = document.createElement("iframe");
                    iframe.src = this.dataset.link+"?autoplay=1";
                    iframe.style.position = "absolute";
                    iframe.style.zIndex = 2;
                    iframe.width = "100%";
                    iframe.height = "100%";
                    iframe.title = "YouTube video player";
                    iframe.frameBorder = "0";
                    iframe.allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture";
                    iframe.allowFullscreen = true;
                    waiting.parentNode.append(iframe);
                }
            }
        }
    })()
</script>
<?
if(	Yii::$app->deviceDetect->isMobile() ){
	$this->registerJs(
<<<JS
$(function () {
	loadScript( 'https://platform-api.sharethis.com/js/sharethis.js#property=63ecb32f4a4876001374e328&product=inline-reaction-buttons', 8000 );
});
JS
    ,
    $this::POS_READY,
    'sharethis'
	);
}else{
	$this->registerJs(
<<<JS
$(function () {
	loadScript( 'https://platform-api.sharethis.com/js/sharethis.js#property=63ecb32f4a4876001374e328&product=inline-reaction-buttons', 100 );
});
JS
    ,
    $this::POS_READY,
    'sharethis'
	);
}
