<?php
/**
 * @package    pixelcms_articles
 *
 * @author     christophf <your@email.com>
 * @copyright  A copyright
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       http://your.url.com
 */

use Joomla\CMS\MVC\View\HtmlView;

defined('_JEXEC') or die;

/**
 * Pixelcms_articles view.
 *
 * @package  pixelcms_articles
 * @since    1.0
 */
class Pixelcms_articlesViewPixelcms_events extends HtmlView
{
    public $content;
    public $category;
	public $params;
    public $hasVimeoPlayer = false;
    public $hasYoutubePlayer = false;
    public $hasFacebookPlayer = false;
    protected $is_module = false;

    static $attachments = [
        'galleries' => 'gallery',
        'workers' => 'worker',
        'pdfs' => 'pdf',
        'files' => 'file',
        'videos' => 'video',
        'images' => 'image',
        'locations' => 'location',
        'departments' => 'department',
    ];

    protected function _setPath($type, $path)
    {
        $component = 'com_pixelcms_articles';
        $app = JFactory::getApplication();

        // Clear out the prior search dirs
        $this->_path[$type] = array();

        // Actually add the user-specified directories
        $this->_addPath($type, $path);

        // Always add the fallback directories as last resort
        switch (strtolower($type))
        {
            case 'template':
                // Set the alternative template search dir
                if (isset($app))
                {
                    $component = preg_replace('/[^A-Z0-9_\.-]/i', '', $component);
                    $fallback = JPATH_THEMES . '/' . $app->getTemplate() . '/html/' . $component . '/' . $this->getName();
                    $this->_addPath('template', $fallback);
                }
                break;
        }
    }

    public function displayFile($file)
    {
        return "<a class='pdf' target='_blank' href='{$this->params->get('pixel_cms_url')}/storage/$file->file'><span class='pdf__title'>$file->title</span></a>";
    }

    public function displayWorker($worker)
    {
        //$html[] =  "<pre>". print_r($worker, true) ."</pre>";
        if ($worker->image) {
            $thumb = preg_replace('/(^(?!http)(?:(?!thumb).)*)\.(jpe?g|png|gif)/', '$1.500-cropped.$2', $worker->image->url);
            $html[] = "<div class='worker__image' style='background-image: url({$this->params->get('pixel_cms_url')}{$thumb})'></div>";
        }
        $html[] = "<h4 class='worker__title'>$worker->first_name $worker->last_name</h4>";
        if (isset($worker->role)) {
            $html[] = "<span class=\"worker__role\">$worker->role</span>";
        }
        $html[] = "<ul class=\"worker__contact\">";
        if ($worker->email) {
            $worker->email = str_rot13($worker->email);
            $html[] = "<li><a class='emails--encrypted' href=\"mailto:$worker->email\"><i class=\"pixelcms-icons\">email</i><span>$worker->email</span></a></li>";
        }
        if ($worker->tel) {
            $telNumber = $this->getCallablePhone($worker->tel);
            $displayNumber = $this->getDisplayablePhone(($worker->tel));
            $html[] = "<li><a href=\"tel:$telNumber\"><i class=\"pixelcms-icons\">phone</i><span>$displayNumber</span></a></li>";
        }
        if ($worker->mobile) {
	        $telNumber = $this->getCallablePhone($worker->mobile);
	        $displayNumber = $this->getDisplayablePhone(($worker->mobile));
            $html[] = "<li><a href=\"tel:$telNumber\"><i class=\"pixelcms-icons\">phone_android</i><span>$displayNumber</span></a></li>";
        }
	    if ($worker->fax) {
		    $telNumber = $this->getCallablePhone($worker->fax);
		    $displayNumber = $this->getDisplayablePhone(($worker->fax));
		    $html[] = "<li><a href=\"fax:$telNumber\"><i class=\"pixelcms-icons\">print</i><span>$displayNumber</span></a></li>";
	    }

        $html[] =  "</ul>";
        return implode("\n", $html);
    }

	private function getCallablePhone($phone)
	{
		return preg_replace([
			'/[\s\/\-]/',
			'/(\+\s?\d{2})(?:\s?(?:\(0\)|0)\s?)?/',
		], [
			'',
			'$1',
		], $phone);
    }

	private function getDisplayablePhone($phone)
	{
		return preg_replace([
			//'/(\d)\s(\d)/',
			'/ - /',
			'/\+\s?\d{2}\s?(?:\s?(?:\(0\)|0)\s?)?/',
		], [
			//'$1$2',
			' ',
			'0',
		], $phone);
    }

    public function displayDepartment($department) {
        $html[] = '';
        foreach ($department->workers as $worker) {
            $html[] = "<div class='worker worker--col-4 worker--col-2-phone worker--col-3-tablet'>";
            $html[] = $this->displayWorker($worker);
            $html[] = "</div>";
        }
        return implode("\n", $html);
    }

    public function displayPdf($pdf)
    {
        return "<a class='pdf' target='_blank' href='{$this->params->get('pixel_cms_url')}/{$this->params->get('pixel_cms_alias')}/pdfs/$pdf->alias'><img class='pdf__image' src='{$this->params->get('pixel_cms_url')}/$pdf->url'><span class='pdf__title'>$pdf->title</span></a>";
    }

    public function displayVideo($video)
    {
        if ($video->vendor_id === 2) {
            $this->hasVimeoPlayer = true;
            return "<iframe class='vimeo_player' src=\"https://player.vimeo.com/video/$video->video_id?title=0&byline=0&portrait=0\" width=\"1280\" height=\"720\" frameborder=\"0\" allowfullscreen></iframe>";
        } else if ($video->vendor_id === 3) {
            $uid = bin2hex(random_bytes(3));
            $this->hasFacebookPlayer = true;
            return "<div class=\"facebook_player fb-video\" id='fb-v-$video->video_id-$uid' data-id='fb-v-$video->video_id-$uid' data-href=\"$video->url\" data-allowfullscreen=\"true\" data-width=\"720\"></div>";
        }
        $this->hasYoutubePlayer = true;
        return "<iframe class='youtube_player' src=\"https://www.youtube-nocookie.com/embed/$video->video_id?rel=0&showinfo=0&enablejsapi=1\" width=\"1280\" height=\"720\" frameborder=\"0\" allowfullscreen></iframe>";
    }


    public function getThumbnail(string $url, int $size = 500, bool $cropped = true): string
    {
        return preg_replace('/^(?:\/)?((?!http)(?:(?!thumb).)*)\.(jpe?g|png|gif)/', ($cropped) ? "$1.$size-cropped.$2" : "$1.$size.$2", $url);
    }

    public function displayGallery($gallery)
    {
        $html = [];
        foreach ($gallery->images as $image) {
            $thumb = $this->getThumbnail($image->url);
	        $preview = $this->getThumbnail($image->url, 2560, false);
            $html[] = "<a class='gallery__item gallery__item--image img' href='{$this->params->get('pixel_cms_url')}/$preview' style='background-image: url({$this->params->get('pixel_cms_url')}/$thumb)'></a>";
        }
        foreach ($gallery->videos as $video) {
            $html[] = "<div class='gallery__item gallery__item--video' style='background-image: url($video->thumb)'></div>";
        }
        return implode('', $html);
    }

    public function hasSidebar($sidebar = ['workers','pdfs','files'])
    {
        foreach ($sidebar as $attachment) {
            if ($this->hasAttachment($attachment)) return true;
        }
        return false;
    }

    public function hasAttachment($attachment_name)
    {
        return isset($this->article->attachments->{$attachment_name}) && $this->article->attachments->{$attachment_name};
    }

    public function attachPlayerScripts()
    {
        $html = [];
        $script = ['var play_class = "video--playing";'];
        if ($this->hasVimeoPlayer) {
            $html[] = "<script src='https://player.vimeo.com/api/player.js'></script>";
            $script[] = '
                [].slice.call(document.querySelectorAll(".vimeo_player")).forEach(function (el) {
                    var player = new Vimeo.Player(el);
                
                    player.on(\'play\', function () {
                        el.parentElement.classList.add(play_class);
                    });
                    player.on(\'pause\', function () {
                        el.parentElement.classList.remove(play_class);
                    });
                });
            ';
        }
        if ($this->hasYoutubePlayer) {
            $html[] = "<script src='https://www.youtube.com/iframe_api'></script>";
            $script[] = '
                function onYouTubeIframeAPIReady() {
                    [].slice.call(document.querySelectorAll(".youtube_player")).forEach(function (el) {
                        var player = new YT.Player(el, {
                            events: {
                                onStateChange: function onStateChange(event) {
                                    if (event.data === YT.PlayerState.PLAYING) {
                                        el.parentElement.classList.add(play_class);
                                    } else if (event.data === YT.PlayerState.PAUSED) {
                                        el.parentElement.classList.remove(play_class);
                                    }
                                }
                            }
                        });
                    });
                }
            ';
        }
        if ($this->hasFacebookPlayer) {
            $html[] = "<script src='https://connect.facebook.net/de_DE/sdk.js'></script>";
            $script[] = '
                function fbAsyncInit() {
                    FB.init({
                        appId      : \'922247001285262\',
                        xfbml      : true,
                        version    : \'v2.11\'
                    });

                    FB.Event.subscribe(\'xfbml.ready\', function(msg) {
                        console.log(msg.instance, msg);
                        if (msg.type === \'video\') {
                            msg.instance.subscribe(\'startedPlaying\', function(e) {
                                document.getElementById(msg.id).parentElement.classList.add(play_class);
                            });
                            msg.instance.subscribe(\'paused\', function(e) {
                                document.getElementById(msg.id).parentElement.classList.remove(play_class);
                            });
                            msg.instance.subscribe(\'finishedPlaying\', function(e) {
                                document.getElementById(msg.id).parentElement.classList.remove(play_class);
                            });
                        }
                    });
                };
            ';
        }
        $script = array_map(function($value) {
            return preg_replace('/[\s]{2,}/', '', $value);
        }, $script);
        $html[] = '<script>' . implode("", $script) . '</script>';
        return implode("\n", $html);
    }

    public function displayAttachment($article, $attachment_name)
    {
        $html[] = "<div class='article_attachment article_attachment--$attachment_name'>";
        // $html[] = "<pre>". print_r($article->attachments->{$attachment_name}, true) ."</pre>";

        // Checks if the attachment is set on the article.
        if (!isset($article->attachments->{$attachment_name})) return "";

        $attachment_name_singular = static::$attachments[$attachment_name];
        $attachment_count = count($article->attachments->{$attachment_name});

        foreach ($article->attachments->{$attachment_name} as $attachment) {
            $html[] = "<div class='{$attachment_name_singular}'>";
            if ($attachment_name === 'pdfs') {
                $html[] = $this->displayPdf($attachment);
            } else if ($attachment_name === 'galleries') {
                if ($attachment_count > 1) {
                    $html[] = "<h3 class='{$attachment_name_singular}__headline'>$attachment->title</h3>";
                }
                $html[] = "<div class='{$attachment_name_singular}__body'>";
                $html[] = $this->displayGallery($attachment);
                $html[] = "</div>";
            } else if ($attachment_name === 'videos') {
                $html[] = $this->displayVideo($attachment);
            } else if ($attachment_name === 'files') {
                $html[] = $this->displayFile($attachment);
            } else if ($attachment_name === 'workers') {
                $html[] = $this->displayWorker($attachment);
            } else if ($attachment_name === 'departments') {
                if ($attachment_count > 1) {
                    $html[] = "<h3 class='{$attachment_name_singular}__headline'>$attachment->title</h3>";
                }
                $html[] = "<div class='{$attachment_name_singular}__body'>";
                $html[] = $this->displayDepartment($attachment);
                $html[] = "</div>";
            }
            $html[] = "</div>";
        }
        $html[] = "</div>";
        return implode('', $html);
    }

    public function getContainerClass(): string
    {
        $viewName = $this->getName();

        $classList[] = "$viewName-wrapper";
        if ($this->params->get('is_module')) {
            $classList[] = 'mod_cms-wrapper';
            $classList[] = "$viewName-mod-wrapper";
        }

        return implode(' ', $classList);
    }

	function display($tpl = null)
	{
		// Assign data to the view
        $this->content = $this->get('Article');
        // $this->category = $this->get('Category');
		$this->params = $this->get('state')->get('params');

        if (gettype($this->content) === 'array') {
            $tpl = 'listing';
        } else {
            $this->content->description = nl2br(preg_replace('/[\r\n]{2,}/', '</p><p>',  $this->content->description));
        }

        $document = JFactory::getDocument();
        $document->addStyleSheet(JURI::base(true) . '/media/com_pixelcms_articles/css/fonts.css', [
            'version' => md5_file(JPATH_BASE . '/media/com_pixelcms_articles/css/fonts.css'),
        ]);
        $document->addStyleSheet(JURI::base(true) . '/media/com_pixelcms_articles/css/style.css', [
            'version' => md5_file(JPATH_BASE . '/media/com_pixelcms_articles/css/style.css'),
        ]);
        $document->addScript(JURI::base(true) . '/media/com_pixelcms_articles/js/script.js', [
            'version' => md5_file(JPATH_BASE . '/media/com_pixelcms_articles/js/script.js'),
        ]);

		// Display the view
		parent::display($tpl);
	}

	public function formatDate(?string $date, bool $withTime = true)
	{
	    if (is_null($date)) {
	        return '';
        }
		return DateTime::createFromFormat('Y-m-d H:i:s', $date)->format('d.m.Y'. (($withTime) ? ' \u\m H:i \U\h\r' : '') );
	}
}
