<?php

use Blended\hostlib\TransformImage;
use Blended\hostlib\Controller;
use Blended\hostlib\Backend;
use Blended\hostlib\Network;
use Blended\lang\Blended_Tags;

/**
 * Blended Loader Class
 * Extends TimberSite Class
 * 
 * @class    Blended
 * @author   Blended
 * @package  blended_fw/inc
 * @version  1.0.0
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Blended_Loader extends TimberSite {

    /**
     * Timber autoescape
     * @var Boolean
     */
    public $autoescape = true;

    /**
     * Blended_Loader Constructor
     * @global type $THEME_SETTINGS
     */
    public function __construct() {


        $this->includes();
        $this->preview_dir = '';

        //Timber autoescape
        if ($this->autoescape)
            Timber::$autoescape = true;


        add_filter('timber_context', array($this, 'add_to_context'));
        add_filter('timber/twig', array($this, 'add_to_twig'));

        $theme = wp_get_theme();
        if (false === get_option('blended_theme_enabled', false) && ( 'Blended Themes' == $theme->name || 'Blended Themes' == $theme->parent_theme )) {
            update_option("blended_theme_enabled", 1);
            global $THEME_SETTINGS;
            global $blendedConfig;
            $currentAccount = $THEME_SETTINGS->get('hub_settings', 'current_accounts');
            $AUTO_INSTALL_ACQUISITION = json_decode($blendedConfig->get("setup_configuration", "FIRSTLOGIN"), true);
            if ("anonymous" == $currentAccount && true === $AUTO_INSTALL_ACQUISITION) :
                //Clear localStorage
                $this->clearLocalStorage();

                //Load auto-acquisition
                $this->blended_initials();
            endif;
        }
        add_action('switch_theme', array($this, 'theme_deactivated'));
        parent::__construct();
    }

    public function includes() {
        require_once BD_PATH . '/inc/hostAuthenticator.php';
        require_once BD_PATH . '/hostlib/src/CommonMark.php';
    }

    public function add_to_twig($twig) {
        /* this is where you can add your own fuctions to twig */
        $twig->addExtension(new Blended_Tags());
        $twig->addExtension(new Twig_Extension_StringLoader());

        // Article functions
        $function = new \Twig_SimpleFunction('get_articles', "blended_articles");
        $twig->addFunction($function);

        $function = new \Twig_SimpleFunction('get_article', "blended_article");
        $twig->addFunction($function);

        // Navigation menu functions
        $function = new \Twig_SimpleFunction('get_nav_menu', "blended_nav_menu");
        $twig->addFunction($function);

        // Function that provides Home URL
        $function = new \Twig_SimpleFunction('home', "blended_home_url");
        $twig->addFunction($function);

        // Function that provides css links.
        $function = new \Twig_SimpleFunction('css_links', "css_links");
        $twig->addFunction($function);


        return $twig;
    }

    public function set_preview_dir($dir) {
        $this->preview_dir = $dir;
    }

    public function theme_deactivated() {

        delete_option("blended_theme_enabled");
    }

    public function clearLocalStorage() {
        ?>
        <script type="text/javascript">
            if (localStorage) {
                localStorage.removeItem('userSlug');
                localStorage.removeItem('currentAccountSlug');
                localStorage.removeItem('package');
                localStorage.removeItem('session_key');
            }

        </script>

        <?php

    }

    // Get acquisition package auto intall on theme activate.
    public function blended_initials() {
        global $ACTIVE_THEME;
        if (isset($_COOKIE[LOGGED_IN_COOKIE])) {
            $user_session = $_COOKIE[LOGGED_IN_COOKIE];
            $user_id = wp_validate_auth_cookie($user_session, 'logged_in');
        } else {
            $user_id = null;
        }
        $backend = BD()->backend($ACTIVE_THEME);
        $session = $backend->get_session_key($user_id);
        $network = BD()->network($session);
        try {
            BD()->controller()->blended_initials();
        } catch (\Exception $e) {
            wp_die($e->getMessage());
        }
    }

    /**
     * Adding theme object to $context array which will be globally available to get access from twig files
     * if $context=Timber::get_context() is used in their respective Controller.
     * Adding data to context , to get availble theme object globally within a site
     */
    public function add_to_context($context) {
        global $ACTIVE_THEME;
        global $THEME_SETTINGS;
        if ($this->preview_dir) {
            $ACTIVE_THEME = $this->preview_dir;
        }

        $template = array();
        try {
            if (isset($_COOKIE[LOGGED_IN_COOKIE])) {
                $user_session = $_COOKIE[LOGGED_IN_COOKIE];
                $user_id = wp_validate_auth_cookie($user_session, 'logged_in');
            } else {
                $user_id = null;
            }
            $backend = BD()->backend($ACTIVE_THEME);
            $session = $backend->get_session_key($user_id);
            $network = BD()->network($session);
            $theme_slug = $ACTIVE_THEME;

            if (empty($theme_slug))
                wp_die("Oops ! Please activate any blended theme.");

            try {
                $theme_object = BD()->controller()->get_package($theme_slug, "context", true, null, true);
            } catch (Exception $e) {
                wp_die("Oops ! Please go to <a href='".admin_url('admin.php?page=' . "Library&lib=Themes")."'>Blended Designs</a> and activate any blended theme.");
            }

            $context['theme_setting'] = $THEME_SETTINGS->getSection("theme_settings");
            $context['navigation_setting'] = $THEME_SETTINGS->getSection("navigation_settings");
            foreach ($context['navigation_setting'] as $key => $value) {
                $context['navigation_setting'][$key] = json_decode($value, true);
            }
            $context['menu'] = new TimberMenu();
            $context['footer_widgets'] = Timber::get_widgets('sidebar-3');
            $context['contact_widgets'] = Timber::get_widgets('sidebar-4');
            $context['sidebar'] = Timber::get_widgets('sidebar-2');
            $context['site'] = (array) $this;
            $context['post'] = new TimberPost();
            $context['user_id'] = $user_id;

            $context['theme'] = $theme_object;

            Timber::$locations = BD_PATH . '/blended_templates';

            return $context;
        } catch (Exception $e) {
            echo "<pre>";
            echo 'Caught exception: (', $e->getMessage(), ')</br>Directory or File does not Exist', ' in file ', $e->getFile(), ' on line ', $e->getLine();
            echo "</pre>";
        }
    }

}

return new Blended_Loader();

