<?php
/*
 * ----------------------------------------------------------------------
 *
 *                          Borlabs Cookie
 *                      developed by Borlabs
 *
 * ----------------------------------------------------------------------
 *
 * Copyright 2018 Borlabs - Benjamin A. Bornschein. All rights reserved.
 * This file may not be redistributed in whole or significant part.
 * Content of this file is protected by international copyright laws.
 *
 * ----------------- Borlabs Cookie IS NOT FREE SOFTWARE -----------------
 *
 * @copyright Borlabs - Benjamin A. Bornschein, https://borlabs.io
 * @author Benjamin A. Bornschein, Borlabs ben@borlabs.io
 *
 */

namespace BorlabsCookie\Cookie\Frontend\BlockedContentTypes;

use BorlabsCookie\Cookie\Tools;
use BorlabsCookie\Cookie\Frontend\ContentBlocker;
use BorlabsCookie\Cookie\Frontend\JavaScript;

class Vimeo
{
    private static $instance;

    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self;
        }

        return self::$instance;
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    /**
     * __construct function.
     *
     * @access protected
     * @return void
     */
    protected function __construct()
    {
        add_action('borlabsCookie/bct/edit_template/vimeo', [$this, 'additionalSettingsTemplate']);
    }

    /**
     * getDefault function.
     *
     * @access public
     * @return void
     */
    public function getDefault()
    {
        $data = [
            'typeId'=>'vimeo',
            'name'=>'Vimeo',
            'description'=>'',
            'hosts'=>[
                'vimeo.com',
            ],
            'previewHTML'=>'<div class="borlabs-cookie-bct bc-bct-video bc-bct-vimeo">
    <p class="bc-thumbnail"><img src="%%thumbnail%%" alt="%%name%%"></p>
    <div class="bc-text">
        <p>'._x('To protect your personal data, your connection to Vimeo has been blocked.<br>Click on <strong>Load video</strong> to unblock Vimeo.<br>By loading the video you accept the privacy policy of Vimeo.<br>More information about Vimeos\'s privacy policy can be found here <a href="https://vimeo.com/privacy" target="_blank" rel="nofollow">Vimeo.com Privacy Policy</a>.', 'Blocked Content Types - Vimeo', 'borlabs-cookie').'</p>
        <p><label><input type="checkbox" name="unblockAll" value="1" checked> '._x('Do not block Vimeo videos in the future anymore.', 'Blocked Content Types - Vimeo', 'borlabs-cookie').'</label>
        <a role="button" data-borlabs-cookie-unblock>'._x('Load video', 'Blocked Content Types', 'borlabs-cookie').'</a></p>
    </div>
</div>',
            'globalJS'=>'',
            'initJS'=>'',
            'settings'=>[
                'responsiveIframe'=>true,
            ],
            'status'=>true,
            'undeleteable'=>true,
        ];

        return $data;
    }

    /**
     * modify function.
     *
     * @access public
     * @param mixed $id
     * @param mixed $content
     * @return void
     */
    public function modify($id, $content)
    {
        // Get settings of the Blocked Content Type
        $bctData = ContentBlocker::getInstance()->getDataOfBlockedContentType('vimeo');

        // Check if the iframe should be made responsive
        if (!empty($bctData['settings']['responsiveIframe'])) {

            // Add wrapper around the iframe, size is handled via CSS
            $content = '<div class="borlabs-cookie-responsive-iframe-wrapper">'.$content.'</div>';

            // Add the modified content to the Blocked Content list, overwrite the old content
            JavaScript::getInstance()->addBlockedContent('vimeo', $id, $content);
        }

        // Default thumbnail
        $thumbnail = BORLABS_COOKIE_PLUGIN_URL.'images/bct-no-thumbnail.png';

        // Check if the thumbnail should be saved locally
        if (!empty($bctData['settings']['saveThumbnails'])) {

            // Get the video id out of the Vimeo URL
            $videoId = [];
            preg_match('/(video\/)?([0-9]{1,})/', ContentBlocker::getInstance()->getCurrentURL(), $videoId);

            // Try to get the thumbnail from Vimeo
            if (!empty($videoId[2])) {
                $thumbnail = $this->getThumbnail($videoId[2]);
            }
        }

        // Get the title which was maybe set via title-attribute in a shortcode
        $title = ContentBlocker::getInstance()->getCurrentTitle();

        // If no title was set use the Blocked Content Type name as title
        if (empty($title)) {
            $title = $bctData['name'];
        }

        // Replace text variables
        $bctData['previewHTML'] = str_replace(
            [
                '%%name%%',
                '%%thumbnail%%',
            ],
            [
                $title,
                $thumbnail
            ],
            $bctData['previewHTML']
        );

        return $bctData['previewHTML'];
    }

    /**
     * getThumbnail function.
     *
     * @access public
     * @param mixed $videoId
     * @return void
     */
    public function getThumbnail($videoId)
    {
        // Default thumbnail in case a thumbnail can not be retrieved
        $thumbnailURL = BORLABS_COOKIE_PLUGIN_URL.'images/bct-no-thumbnail.png';;

        // Path and filename of the requested thumbnail on the HDD
        $filename = ContentBlocker::getInstance()->getCacheFolder().'/vimeo_'.$videoId.'.jpg';

        // URL of the requested thumbnail
        $webFilename = content_url().'/cache/borlabs_cookie/vimeo_'.$videoId.'.jpg';

        // Check if thumbnail does not exist
        if (!file_exists($filename)) {

            // Only try to retrieve a thumbnail when the cache folder is writable
            if (is_writable(ContentBlocker::getInstance()->getCacheFolder())) {

                // Get oembed data from vimeo
                $oembedResponse = wp_remote_get('https://vimeo.com/api/oembed.json?url='.urlencode('https://vimeo.com/'.$videoId).'&maxwidth=720');

                if (!empty($oembedResponse['body']) && Tools::getInstance()->isStringJSON($oembedResponse['body'])) {

                    $videoData = json_decode($oembedResponse['body']);

                    // Check if thumbnail is available
                    if (!empty($videoData->thumbnail_url)) {

                        // Get image from Vimeo
                        $thumbnailResponse = wp_remote_get($videoData->thumbnail_url);

                        // Get the content-type, only jpeg is accepted
                        $contentType = wp_remote_retrieve_header($thumbnailResponse, 'content-type');

                        if (!empty($thumbnailResponse) && is_array($thumbnailResponse) && $contentType == 'image/jpeg') {

                            // Save thumbnail locally
                            file_put_contents($filename, wp_remote_retrieve_body($thumbnailResponse));

                            // Update the thumbnail URL
                            $thumbnailURL = $webFilename;
                        }
                    }
                }
            }
        } else {
            // Thumbnail is already saved locally
            $thumbnailURL = $webFilename;
        }

        return $thumbnailURL;
    }

    /**
     * additionalSettingsTemplate function.
     *
     * @access public
     * @param mixed $data
     * @return void
     */
    public function additionalSettingsTemplate($data)
    {
        $checkboxResponsiveIframe   = !empty($data->settings['responsiveIframe']) ? ' checked' : '';
        $checkboxSaveThumbnails     = !empty($data->settings['saveThumbnails']) ? ' checked' : '';
        ?>
        <div class="form-group">
            <div class="form-title"><?php _ex('Responsive Iframe', 'Setting title', 'borlabs-cookie'); ?></div>
            <div class="form-field">
                <label for="responsiveIframe">
                    <input<?php echo $checkboxResponsiveIframe; ?> type="checkbox" name="settings[responsiveIframe]" id="responsiveIframe" value="1"> <span class="option-title"><?php _ex('Activate', 'Setting checkbox', 'borlabs-cookie'); ?></span>
                </label>
                <span class="description"><?php _ex('The width and height will be replaced to get the iframe responsive.', 'Setting description', 'borlabs-cookie'); ?></span>
            </div>
        </div>

        <div class="form-group">
            <div class="form-title"><?php _ex('Save thumbnails locally', 'Setting title', 'borlabs-cookie'); ?></div>
            <div class="form-field">
                <label for="saveThumbnails">
                    <input<?php echo $checkboxSaveThumbnails; ?> type="checkbox" name="settings[saveThumbnails]" id="saveThumbnails" value="1"> <span class="option-title"><?php _ex('Activate', 'Setting checkbox', 'borlabs-cookie'); ?></span>
                </label>
                <span class="description"><?php _ex('Attempts to get the thumbnail of the Vimeo video to save it locally. Your visitor\'s IP-address will not be transferred to Vimeo during this process.', 'Setting description', 'borlabs-cookie'); ?></span>
            </div>
        </div>
        <?php
    }
}
