<?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;

use BorlabsCookie\Cookie\Config;
use BorlabsCookie\Cookie\Multilanguage;

class JavaScript
{
    private static $instance;

    private $binaryContent = [];
    private $blockedContentTypes = [];

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

        return self::$instance;
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    protected function __construct()
    {
    }

    public function register()
    {
        wp_enqueue_script('borlabs-cookie', BORLABS_COOKIE_PLUGIN_URL.'javascript/borlabs-cookie.min.js', ['jquery'], BORLABS_COOKIE_VERSION);

        $codeCookieThirdParty = Config::getInstance()->get('codeCookieThirdParty');
        $codeCookieFirstParty = Config::getInstance()->get('codeCookieFirstParty');

        // Embed Google Code
        if (!empty(Config::getInstance()->get('googleAnalyticsId'))) {
            $codeCookieThirdParty .= GoogleAnalytics::getInstance()->getCode();
        }

        // Embed Facebook Pixel Code
        $codeFacebookPixel = '';
        if (!empty(Config::getInstance()->get('facebookPixelId'))) {
            $codeFacebookPixel = FacebookPixel::getInstance()->getCode();
        }

        $codeCookieThirdParty = apply_filters('borlabs_cookie_third_party_code', $codeCookieThirdParty);
        $codeCookieFirstParty = apply_filters('borlabs_cookie_first_party_code', $codeCookieFirstParty);
        $codeFacebookPixel = apply_filters('borlabs_cookie_facebook_pixel_code', $codeFacebookPixel);

        $jsConfig = [
            'ajaxURL'=>admin_url('admin-ajax.php'),
            'language'=>Multilanguage::getInstance()->getCurrentLanguageCode(),
            'codeCookieFirstParty'=>base64_encode($codeCookieFirstParty),
            'codeCookieThirdParty'=>base64_encode($codeCookieThirdParty),
            'codeFacebookPixel'=>base64_encode($codeFacebookPixel),
            'cookieBoxBlocks'=>Config::getInstance()->get('cookieBoxBlocks'),
            'cookieBoxShow'=>Config::getInstance()->get('cookieBoxShow'),
            'cookieLifetime'=>Config::getInstance()->get('cookieLifetime'),
            'cookieLifetimeOption2'=>Config::getInstance()->get('cookieLifetimeOption2'),
            'cookieLifetimeOption3'=>Config::getInstance()->get('cookieLifetimeOption3'),
            'cookieRespectDoNotTrack'=>Config::getInstance()->get('cookieRespectDoNotTrack'),
            'cookiesForBots'=>Config::getInstance()->get('cookiesForBots'),
            'executeFirstPartyCodeOnThirdParty'=>Config::getInstance()->get('executeFirstPartyCodeOnThirdParty'),
            'facebookPixelId'=>Config::getInstance()->get('facebookPixelId'),
            'googleAnalyticsId'=>Config::getInstance()->get('googleAnalyticsId'),
            'hideCookieBoxOnPage'=>Config::getInstance()->get('hideCookieBoxOnPage'),
            'cookieDomain'=>Config::getInstance()->get('cookieDomain'),
            'cookiePath'=>Config::getInstance()->get('cookiePath'),
        ];

        $jsConfig = apply_filters('borlabs_cookie_js_config', $jsConfig);

        wp_localize_script('borlabs-cookie', 'borlabsCookieConfig', $jsConfig);
        wp_localize_script('borlabs-cookie', 'borlabsCookieBlockedContent', $this->binaryContent);

        $jsCode = 'jQuery(document).ready(function() {';
        $jsCode .= "\n".$this->getBlockedContentTypeScriptsCode()."\n";
        $jsCode .= 'window.BorlabsCookie.init(borlabsCookieConfig, borlabsCookieBlockedContentTypes, borlabsCookieBlockedContent);';
        $jsCode .= '});';

        wp_add_inline_script('borlabs-cookie', $jsCode, 'after');
    }

    public function addBlockedContent($typeId, $id, $content)
    {
        $this->binaryContent[$id] = [
            'typeId'=>$typeId,
            'content'=>base64_encode(do_shortcode($content)),
        ];

        return true;
    }

    public function addBlockedContentType($typeId, $globalJS = '', $initJS = '', $settings = [])
    {
        $settings = apply_filters('borlabsCookie/bct/modify_js_settings/'.$typeId, $settings);

        $this->blockedContentTypes[$typeId] = [
            'typeId'=>$typeId,
            'global'=>$globalJS,
            'init'=>$initJS,
            'settings'=>$settings,
        ];

        return true;
    }

    public function getBlockedContentTypeScriptsCode()
    {
        $js = 'var borlabsCookieBlockedContentTypes = {';

        if (!empty($this->blockedContentTypes)) {

            foreach ($this->blockedContentTypes as $typeId => $data) {

                $js .= '"'.$typeId.'": {';
                $js .= '"global": function () { '.$data['global'].' },';
                $js .= '"init": function (id) { '.$data['init'].' },';
                $js .= '"settings": '.json_encode($data['settings']);
                $js .= '},';
            }

            $js = substr($js, 0, -1);
        }

        $js .= '};';

        return $js;
    }
}
