<?php

/*
 * Created on Mon Mar 25 2019
 * HomePage: http://dcforo.com/
 * Email: datdaik000@gmail.com
 * Blog: https://fb.com/dcstylexf/
 * Copyright (c) 2019 D.C Style XenForo -  All Rights Reserved
 */

namespace DC\ThreadThumbnail\XF\Pub\Controller;

use XF\Mvc\Entity\Entity;
use XF\Mvc\ParameterBag;

class Thread extends XFCP_Thread
{
    public function actionEditThumbnail(ParameterBag $params)
    {
        $thread = $this->assertViewableThread($params->thread_id);
        $forum = $thread->Forum;
        $visitor = \XF::visitor();
        
        if (!$thread->canEditThumbnail() && !$thread->canEditCover())
        {
            return $this->noPermission($error);
        }

        $listUrls = $this->getListUrls($thread);

        if ($this->isPost())
        {
            /** Thread Thumbnail */
            $thumbCustom = $this->filter('DC_ThreadThumbnail_thumbCustom', 'bool');
            $thumbUrl = $this->filter('DC_ThreadThumbnail_thumbUrl', 'str');

            if (!$thumbUrl) $thumbCustom = 0;

            if (!$thumbCustom) $thumbUrl = '';

            if ($thumbCustom && isset($thumbUrl) && !@getimagesize($thumbUrl))
            {
                return $this->error(\XF::phrase('please_enter_valid_url'));
            }

            $thread->set('DC_ThreadThumbnail_thumbCustom', $thumbCustom);
            $thread->set('DC_ThreadThumbnail_thumbUrl', $thumbUrl);


            /** Thread Cover */
            $coverCustom = 0;
            $coverImageUrl = '';
            $videoID = '';
            $videoSite = '';
            $videoUrl = '';

            $coverCustom = $this->filter('DC_ThreadThumbnail_threadCover', 'int');
            $coverImageUrl = $this->filter('DC_ThreadThumbnail_threadCoverUrl', 'str');
            $coverVideoUrl = $this->filter('DC_ThreadThumbnail_threadVideoUrl', 'str');

            switch (true)
            {
                case ($coverCustom == 1 && $coverImageUrl):
                    $thread->set('DC_ThreadThumbnail_threadCover', $coverCustom);
                break;

                case ($coverCustom == 2 && $coverVideoUrl):
                    $thread->set('DC_ThreadThumbnail_threadCover', $coverCustom);

                    /** Check media site */
                    switch (true)
                    {
                        case preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $coverVideoUrl, $matchYtb):
                            $id = $matchYtb[1];

                            $videoID = $id;

                            $videoSite = 'ytb';

                            $videoUrl = $coverVideoUrl;
                        break;

                        case preg_match('!^.+dailymotion\.com/(video|hub)/([^_]+)[^#]*(#video=([^_&]+))?|(dai\.ly/([^_]+))!', $coverVideoUrl, $matchDaily):
                            switch (true)
                            {
                                case isset($matchDaily[6]):
                                    $id = $matchDaily[6];
                                break;

                                case isset($matchDaily[4]):
                                    $id = $matchDaily[4];
                                break;

                                default:
                                    $id = $matchDaily[2];
                                break;
                            }

                            $videoID = $id;

                            $videoSite = 'daily';

                            $videoUrl = $coverVideoUrl;
                        break;

                        case preg_match('#(?:https?://)?(?:www.)?(?:player.)?vimeo.com/(?:[a-z]*/)*([0-9]{6,11})[?]?.*#', $coverVideoUrl, $matchVimeo):
                            $id = $matchVimeo[1];

                            $videoID = $id;

                            $videoSite = 'vimeo';

                            $videoUrl = $coverVideoUrl;

                        break;
                    }
                break;

                default:
                    $coverCustom = 0;

                    $coverImageUrl = '';

                    $videoID = '';

                    $videoSite = '';

                    $videoUrl = '';
                break;
            }

            $thread->set('DC_ThreadThumbnail_threadCover', $coverCustom);

            $thread->set('DC_ThreadThumbnail_threadCoverUrl', $coverImageUrl);

            $thread->set('DC_ThreadThumbnail_threadVideoUrl', $videoUrl);

            $thread->set('DC_ThreadThumbnail_threadVideoID', $videoID);

            $thread->set('DC_ThreadThumbnail_threadVideoSite', $videoSite);

            $thread->save();

            $thread->set('DC_ThreadThumbnail_tempThumbUrl', $thread->getThumbnailSmall());
            $thread->set('DC_ThreadThumbnail_tempImageUrl', $thread->getThumbnailFull());

            $thread->save();

            return $this->redirect($this->buildLink('threads', $thread));
        }

        $viewParams = [
            'thread' => $thread,
            'listUrls' => $listUrls
        ];

        return $this->view('DC\ThreadThumbnail:EditThumbnail', 'DC_ThreadThumbnail_edit_thumbnail', $viewParams);
    }

    protected function getListUrls($thread)
    {
        $ytb = \XF::options()->DC_ThreadThumbnail_youtube;
        $vimeo = \XF::options()->DC_ThreadThumbnail_vimeo;
        $daily = \XF::options()->DC_ThreadThumbnail_dailymotion;
        
        $message = $thread->FirstPost->message;
        $baseUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]";    

        $listUrls = [];

        /** List external images */
        preg_match_all('/\[img.*?](.*?)\[\/img]/i', $message, $matches);
        if ($matches)
        {
            $urls = $matches[1];
            
            foreach ($urls AS $url)
            {
                $linkInfo = \XF::app()->stringFormatter()->getLinkClassTarget($url);
                
                if(\XF::app()->options()->imageLinkProxy['images'])
                {
                    $proxyUrl = \XF::app()->stringFormatter()->getProxiedUrlIfActive('image', $url);
                    $url = $baseUrl . $proxyUrl;
                }

                $listUrls[] = $url;
            }
        }

        /** List attachments */
        $attachments = $thread->FirstPost->Attachments;
        foreach ($attachments as &$attachment)
        {
            if ($attachment->has_thumbnail)
            {
                $attachmentUrl = $baseUrl . \XF::app()->router()->buildLink('attachments', $attachment);
                $listUrls[] = $attachmentUrl;
            }
        }

        /** List youtube thumbnail */
        if ($ytb)
        {
            preg_match_all('#\[media=youtube\](.+?)\[/media\]#i', $message, $matchesYtb);

            if($matchesYtb)
            {
                $urls = $matchesYtb[0];
    
                foreach ($urls AS $url)
                {
                    preg_match('#\[media=youtube\](.+?)\[/media\]#i', $url, $matchUrlYtb);

                    if (@file_get_contents('https://img.youtube.com/vi/'.$matchUrlYtb[1].'/mqdefault.jpg'))
                    {
                        $url = 'https://img.youtube.com/vi/'.$matchUrlYtb[1].'/maxresdefault.jpg';

                        if (!file_exists($url))
                        {
                            $url = 'https://img.youtube.com/vi/'.$matchUrlYtb[1].'/mqdefault.jpg';
                        }

                        $listUrls[] = $url;
                    }
                }
            }
        }

        /** List vimeo thumbnail */
        if ($vimeo)
        {
            preg_match_all('#\[media=vimeo\](.+?)\[/media\]#i', $message, $matchesVimeo);

            if ($matchesVimeo)
            {
                $urls = $matchesVimeo[0];
    
                foreach ($urls AS $url)
                {
                    preg_match('#\[media=vimeo\](.+?)\[/media\]#i', $url, $matchUrlVimeo);

                    if (@file_get_contents('https://vimeo.com/api/v2/video/'.$matchUrlVimeo[1].'.json'))
                    {
                        $url = file_get_contents('https://vimeo.com/api/v2/video/'.$matchUrlVimeo[1].'.json');

                        $url = json_decode($url);

                        $listUrls[] = $url[0]->thumbnail_medium;
                    }
                }
            }
        }

        /** List dailymotion thumbnail */
        if ($daily)
        {
            preg_match_all('#\[media=dailymotion\](.+?)\[/media\]#i', $message, $matchesDaily);

            if ($matchesDaily)
            {
                $urls = $matchesDaily[0];
    
                foreach ($urls AS $url)
                {
                    preg_match('#\[media=dailymotion\](.+?)\[/media\]#i', $url, $matchUrlDaily);
    
                    if (@file_get_contents('https://www.dailymotion.com/thumbnail/video/'.$matchUrlDaily[1]))
                    {
                        $url = 'https://www.dailymotion.com/thumbnail/video/'.$matchUrlDaily[1];

                        $listUrls[] = $url;
                    }
                }
            }
        }

        return $listUrls;
    }
}