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

use BorlabsCookie\Cookie\Frontend\Log;
use BorlabsCookie\Cookie\Multilanguage;

class Backend
{
    private static $instance;

    public $templatePath;

    private $messages = [];

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

        return self::$instance;
    }

    public function __construct()
    {
        /* Load textdomain */
        add_action('plugins_loaded', [$this, 'loadTextdomain']);

        /* Add menu */
        add_action('admin_menu', [$this, 'addMenu']);

        /* Load JavaScript & CSS */
        add_action('admin_enqueue_scripts', [$this, 'registerAdminRessources']);

        /* Add action links to plugin page */
        add_filter('plugin_action_links_'.BORLABS_COOKIE_SLUG, [$this, 'addActionLinks']);

        /* Register handler for AJAX requests */
        add_action('wp_ajax_borlabs_cookie_handler', [$this, 'handleAjaxRequest']);
        add_action('wp_ajax_nopriv_borlabs_cookie_handler', [$this, 'handleAjaxRequest']);

        $this->templatePath = realpath(dirname(__FILE__).'/../../../templates');
    }

    private function __clone()
    {
    }

    private function __wakeup()
    {
    }

    /**
     * loadTextdomain function.
     *
     * @access public
     * @return void
     */
    public function loadTextdomain()
    {
        load_plugin_textdomain('borlabs-cookie', false, dirname(BORLABS_COOKIE_SLUG).'/languages/');
    }

    /**
     * addMenu function.
     *
     * @access public
     * @return void
     */
    public function addMenu()
    {
        add_options_page(
            _x('Borlabs Cookie', 'Site title', 'borlabs-cookie'),
            _x('Borlabs Cookie', 'Menu title', 'borlabs-cookie'),
            'manage_options',
            'borlabs_cookie_settings',
            [View::getInstance(), 'display__Settings']
        );
    }

    /**
     * registerAdminRessources function.
     *
     * @access public
     * @return void
     */
    public function registerAdminRessources()
    {
        if (get_current_screen()->id == 'settings_page_borlabs_cookie_settings') {
            wp_enqueue_style(
                'borlabs_cookie_admin_css',
                plugins_url('css/'.sanitize_html_class(get_user_option('admin_color'), 'fresh').'.css', realpath(__DIR__.'/../../')),
                [],
                BORLABS_COOKIE_VERSION
            );

            wp_enqueue_style('wp-color-picker');
            wp_enqueue_script(
                'borlabs-cookie-admin',
                plugins_url('javascript/borlabs-cookie-admin.min.js', realpath(__DIR__.'/../../')),
                ['wp-color-picker'],
                BORLABS_COOKIE_VERSION,
                true
            );

            wp_localize_script(
                'borlabs-cookie-admin',
                'borlabsCookieAdmin',
                [
                    'ajax_nonce'=>wp_create_nonce('borlabs-cookie-settings'),
                ]
            );

            // CodeMirror - WordPress 4.9.x
            if (function_exists('wp_enqueue_code_editor')) {

                // Enqueue code editor and settings for manipulating HTML.
                $settings = wp_enqueue_code_editor(['type'=>'text/css']);

                if ($settings !== false) {
                    wp_add_inline_script(
                        'code-editor',
                        sprintf(
                            'jQuery( function() { if (jQuery("#stylingCustomCSS").length) { wp.codeEditor.initialize("stylingCustomCSS", %s); } } );',
                            wp_json_encode($settings)
                        )
                    );
                }
            }
        }
    }

    /**
     * addActionLinks function.
     *
     * @access public
     * @param mixed $links
     * @return void
     */
    public function addActionLinks($links)
    {
        $links[] = '<a href="'.esc_url(get_admin_url(null, 'options-general.php?page=borlabs_cookie_settings')).'">'._x('Settings', 'Action Links', 'borlabs-cookie').'</a>';

        return $links;
    }

    /**
     * handleAjaxRequest function.
     *
     * @access public
     * @return void
     */
    public function handleAjaxRequest()
    {
        if (!empty($_POST['type'])) {

            $requestType = $_POST['type'];

            /* Frontend request */
            if ($requestType == 'log') {

                if (!empty($_POST['id']) && !empty($_POST['option'])) {
                    echo json_encode(
                        [
                            'success'=>Log::getInstance()->add($_POST['id'], $_POST['option'])
                        ]
                    );
                }
            } elseif ($requestType == 'log_history') {

                if (!empty($_POST['id'])) {

                    $language = Multilanguage::getInstance()->getCurrentLanguageCode();

                    if (!empty($_POST['language'])) {
                        $language = $_POST['language'];
                    }

                    echo json_encode(Log::getInstance()->getHistory($_POST['id'], $language));
                }
            } elseif ($requestType == 'get_page') {

                /* Backend request */
                if (check_ajax_referer('borlabs-cookie-settings', false, false)) {

                    $permalink = '';

                    if (!empty($_POST['pageId'])) {
                        $permalink = get_permalink(intval($_POST['pageId']));
                    }

                    echo json_encode(['permalink'=>$permalink]);
                }
            }
        }

        wp_die();
    }

    /**
     * getMessages function.
     *
     * @access public
     * @return void
     */
    public function getMessages()
    {
        return implode("\n", $this->messages);
    }

    /**
     * addMessage function.
     *
     * @access public
     * @param mixed $message
     * @param mixed $type
     * @return void
     */
    public function addMessage($message, $type)
    {
        $this->messages[] = '<p class="'.\esc_attr($type).'">'.$message.'</p>';
    }
}
