<?php

use Blended\hostlib\Controller;
use Blended\hostlib\Backend;
use Blended\hostlib\Network;
use Blended\hostlib\Blended_ini_Parser;
use Blended\hostlib\TransformImage;
use Blended\Orm\DB_Backend;

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

if (!class_exists('Blended_FW')) :

    final class Blended_FW {

        /**
         * Theme version.
         *
         * @var string
         */
        public $version = '1.0.0';

        /**
         * The single instance of the class.
         */
        protected static $_instance = null;

        /**
         * Backend instance
         * @var Backend Object 
         */
        public $backend = null;

        /**
         * Controller instance
         * @var Controller Object 
         */
        public $controller = null;

        /**
         * Network instance
         * @var Network Object 
         */
        public $network = null;

        /**
         * Blended Loader
         * @var Blended_Loader object 
         */
        public $loader = null;

        /**
         * Backend Class Constructor Argument
         * @var string
         */
        public $backend_slug = null;

        /**
         * Network key
         * @var string
         */
        public $network_key = null;

        /**
         * Blended Theme Framework Instance.
         *
         * @return Main instance.
         */
        public static function instance() {
            if (is_null(self::$_instance)) {
                self::$_instance = new self();
            }
            return self::$_instance;
        }

        /**
         * Constructor.
         */
        public function __construct() {

            //Check if required plugins are loaded
            if (!$this->plugins_installed())
                return;
            $this->blended_config();
            $this->includes();
            $this->init_hooks();


            do_action('blended_loaded');
        }


        /**
         * @todo Delete this method ASAP
         * Blended Config Variables
         * @global Blended_ini_Parser $blendedConfig
         * @global Blended_ini_Parser $THEME_SETTINGS
         * @global type $ACTIVE_THEME
         * @global type $CACHE_IMAGE_DIRECTORY
         */
        public function blended_config() {
         
            global $blendedConfig, $THEME_SETTINGS, $ACTIVE_THEME, $CACHE_IMAGE_DIRECTORY;
            $blendedConfig = new Blended_ini_Parser(BD_PATH . "/hostlib/src/config.ini");
            $THEME_SETTINGS = new Blended_ini_Parser(BD_PATH . "/hostlib/src/theme_settings.ini");
            $ACTIVE_THEME = $blendedConfig->get("setup_configuration", "ACTIVE_THEME");
            $CACHE_IMAGE_DIRECTORY = BD_PATH . '/' . $blendedConfig->get("backend_multimedia_directory", "IMAGE_DIRECTORY");
        }

        /**
         * Hooks.
         */
        private function init_hooks() {
            add_action('after_setup_theme', array($this, 'setup'));
            add_action('wp_logout', array($this->loader, 'clearLocalStorage'));
            add_action('widgets_init', array($this, 'widgets_init'));
            add_action("wp_enqueue_scripts", array($this, "scripts"));

            /**
             * @todo Temporary now 
             */
            if (class_exists('Blended\hostlib\Blended_ini_Parser')) {

                global $NAMESPACE, $blendedConfig;
                $NAMESPACE = $blendedConfig->get('swagger', 'BASE_PATH_2');

                /**
                 * @todo Add rest handler class
                 */
                require_once ( BD_PATH . '/inc/routes.php');

                // Overriding default wp-json prefix to 'blended' here.
                add_filter('rest_url_prefix', "blended_api");
            }
            /** END */
        }

        /**
         * Include required files.
         */
        public function includes() {

            require_once BD_PATH . '/inc/blended_helper_functions.php';
            require_once BD_PATH . '/inc/class-blended-post-types.php';

            //Load Blended Framework
            $this->loader = require_once BD_PATH . '/inc/class-bd-loader.php';

            
            //Include admin instances.
            if (is_admin())
                require_once BD_PATH . '/inc/admin/class-blended-admin.php';

            require_once BD_PATH . '/inc/article_functions.php';
            require_once BD_PATH . '/inc/navigation_functions.php';
            require_once BD_PATH . '/inc/class-blended-shortcodes.php';
            require_once BD_PATH . '/inc/class-wc-support.php';
            require_once BD_PATH . '/inc/comment-functions.php';
        }

        public function setup() {

            /**
             * Posts and comments RSS feed links to head.
             */
            add_theme_support('automatic-feed-links');

            /*
             * Post Thumbnails on posts and pages.
             */
            add_theme_support('post-thumbnails');

            //Nav Menus.
            register_nav_menus(array(
                'primary' => __('Primary Menu', 'blended'),
                'secondary' => __('Secondary Menu', 'blended')
            ));

            //Custom Image Sizes
            add_image_size('admin-list-thumb', 80, 80, true);
            add_image_size('gallery-list-thumb', 360, 260, true);
        }

        public function widgets_init() {

            register_sidebar(array(
                'name' => __('Main Widget Area', 'blended'),
                'id' => 'sidebar-1',
                'description' => __('Appears in the footer section of the site.', 'blended'),
                'before_widget' => '<aside id="%1$s" class="widget %2$s">',
                'after_widget' => '</aside>',
                'before_title' => '<h3 class="widget-title">',
                'after_title' => '</h3>'
            ));

            register_sidebar(array(
                'name' => __('Secondary Widget Area', 'blended'),
                'id' => 'sidebar-2',
                'description' => __('Appears on posts and pages in the sidebar.', 'blended'),
                'before_widget' => '<aside id="%1$s" class="widget %2$s">',
                'after_widget' => '</aside>',
                'before_title' => '<h3 class="widget-title">',
                'after_title' => '</h3>'
            ));

            register_sidebar(array(
                'name' => __('Footer Widget Area', 'blended'),
                'id' => 'sidebar-3',
                'description' => __('Appears on Footer Area.', 'blended'),
                'before_widget' => '<div class="one_third-md footer-content__col">',
                'after_widget' => '</div>',
                'before_title' => '<h3 class="widget-title">',
                'after_title' => '</h3>'
            ));

            register_sidebar(array(
                'name' => __('Contact Map', 'blended'),
                'id' => 'sidebar-4',
                'description' => __('Appears on Contact Page.', 'blended'),
                'before_widget' => '<div class="map-responsive">',
                'after_widget' => '</div>',
                'before_title' => '<h3 class="widget-title">',
                'after_title' => '</h3>'
            ));
        }

        /**
         * Load Scripts
         */
        public function scripts() {
            wp_enqueue_script('jquery');
        }

        public function plugins_installed() {

            //First install required plugins
            require_once BD_PATH . '/inc/tgmaBlended.php';

            /**
             * Backward compatibility
             * Now check if any plugin is deactive
             */
            $required_plugins = array(
                array(
                    "key" => "timber-library/timber.php",
                    "notice" => __(sprintf("Blended themes requires %s to be activated ", "<strong>Timber</strong>"), "blended")
                )
            );

            $all_set = true;

            foreach ($required_plugins as $key => $plugin):

                /**
                 * @todo Check network installation if required by using 
                 * || is_plugin_active_for_network( $plugin['key'] ) in if
                 */
                if (!in_array($plugin['key'], (array) apply_filters('active_plugins', get_option('active_plugins')))):
                    $notice = $plugin['notice'];

                    //Admin notice
                    //add_action('admin_notices', function() use($notice) {
                    //    printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr("notice notice-error"), $notice);
                    //});
                    //Frontend notice
                    if (!is_admin())
                        wp_die($notice);

                    //Looks like this plugin is not activated
                    $all_set = false;
                endif;

            endforeach;

            return $all_set;
        }
        
        /**
         * Get Backend Class
         * @param string $slug
         * @return Backend Object
         */
        public function backend($slug = null) {
            global $blendedConfig;
	    $switch = $blendedConfig->get("setup_configuration", "BACKEND");
            $this->backend_slug = $slug;
	    switch ($switch) {
	       case "DB":
		 $backend = new DB_Backend($this->backend_slug);
                 return $this->backend = $backend;
	       case "FS":
		 $backend = new Backend($this->backend_slug);
                 return $this->backend = $backend;
	       default:
		 $backend = new Backend($this->backend_slug);
                 return $this->backend = $backend;
	    }            
        }
        
        /**
         * Get Network class 
         * @param string $sessionKey
         * @return Network Object
         */
        public function network($sessionKey = null) {
            $this->network_key = $sessionKey;
            return $this->network = new Network($this->network_key);
        }
        
        /**
         * Get Controller Class
         * @return Controller Object
         */
        public function controller() {
            if (!$this->backend_slug)
                $this->backend();

            if (!$this->network_key)
                $this->network();

            return $this->controller = new Controller($this->backend, $this->network);
        }

    }

    endif;

function BD() {
    return Blended_FW::instance();
}
