<?php

/**
 * Blended Host Authenticator
 * Extends by Backend Class
 *
 * @class    Host_Authenticator
 * @author   Blended
 * @category Core
 * @package  blended_fw/inc
 * @version  1.0.0
 */

use Blended\hostlib\Blended_ini_Parser;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

global $blendedConfig;

$blendedConfig = new Blended_ini_Parser(BD_PATH . '/hostlib/src/config.ini');

class hostAuthenticator {

    /**
     * Get Hub session_key required to communicate to Network.
     * 
     * @param  string $user_id is the current wordpress logged-in user ID
     * @return string saved Hub settings.
     */
    public function get_session_key($user_id = null) {
        /**
         * user settings.
         *
         * @access global
         * @var    string
         */
        global $blendedConfig;
        $sessions = null;
        $sessions = $blendedConfig->get("setup_configuration", "SESSION_KEY");
        $sessions = json_decode($sessions, true);
        $session = null;
        if (!empty($sessions)) {
            $sessionsList = array_keys($sessions);
            $session = $sessions[$sessionsList[0]];
        }
        return $session;
    }

    /**
     * Get site url..
     * 
     * @return string URL.
     */
    public function blended_multisite_url() {
        $siteUrl = site_url();
        return $siteUrl;
    }

    /**
     * Set Hub session_key required to communicate to Network on to current configuration.
     * 
     * @param  string $sessionKey is the current Hub logged-in user ID
     * @param  string $userId     is the current wordpress logged-in user ID
     * @return string saved sessionKey.
     */
    public function set_session_key($sessionKey, $userId = null) {
        /**
         * user settings.
         *
         * @access global
         * @var    string
         */
        global $blendedConfig;
        $sessions = $this->get_session_key();
        if (is_null($sessionKey)) {
            unset($sessions);
            $sessions = array();
        } else {
            $sessions = array($userId => $sessionKey);
        }
        $sessions = json_encode($sessions);
        $blendedConfig->setValue("setup_configuration", "SESSION_KEY", $sessions);
        $blendedConfig->save(get_template_directory() . "/hostlib/src/" . "config.ini");
        $session = $this->get_session_key($userId);
        return $session;
    }

    /**
     * Authenticating wordpress user session on every request and sets user session.
     * 
     * @param  string $hubSession is the current Hub logged-in user ID
     * @param  string $wpSession  is the current wordpress logged-in user ID
     * @return string wordpress user sessionKey.
     */
    public function blended_authenticate($hubSession, $wpSession) {
        if (isset($_COOKIE[LOGGED_IN_COOKIE])) {
            $userSession = $_COOKIE[LOGGED_IN_COOKIE];
            $userId = wp_validate_auth_cookie($userSession, 'logged_in');
        } else {
            $userId = wp_validate_auth_cookie($wpSession, 'logged_in');
            $userSession = $wpSession;
        }
        $this->set_session_key($hubSession, $userId);
        return $userSession;
    }

    /**
     * Validate wordpress user session on every request.
     * 
     * @param  string $hub_session is the current Hub logged-in user ID
     * @param  string $wp_session  is the current wordpress logged-in user ID
     * @return string|false Hub user sessionKey else offline if user not loged-in to Hub.
     */
    public function blended_session_setter($session_key, $no_user) {
        /**
         * user settings.
         *
         * @access global
         * @var    string
         */
        global $blendedConfig;
        $user_id = wp_validate_auth_cookie($session_key, 'logged_in');
        if ($no_user == true) {
            return true;
        } elseif ($user_id != false && user_can( $user_id, "manage_options" )) {
            $session = $this->get_session_key();
            if (isset($session)) {
                return $session;
            } else {
                return "offline";
            }
        } else {
            throw new \Exception('{ "status_code":"500", "message":"Session not authenticated" }');
        }
    }

    /**
     * Get nav default settings for admin
     *
     * @return array default navigations for admin nav settings
     */
    function get_nav_list() {
        /**
         * Blended API namespace.
         * Defined within network.
         *
         * @access global
         * @var    string
         */
        global $NAMESPACE;

        //Get Host/WordPress menu
        $menus = get_terms('nav_menu');
        $settings = array();
        $hostMenus = array();
        if (!empty($menus)) {
            foreach ($menus as $key => $value) {
                $hostMenus["types"] = "host";
                $hostMenus["label"] = __("WordPress - ", "blended") . $value->name;
                $hostMenus["id"] = $value->term_id;
                $hostMenus["href"] = site_url() . "/" . blended_api('') . "/" . $NAMESPACE . "/menus/" . $value->term_id;
                $settings[] = $hostMenus;
            }
        }
        //JSON Web Service
        $settings[] = array(
            "types" => "url",
            "label" => __("JSON Web Service", "blended"),
            "id" => "nav_jws",
            "data" => "#"
        );
        //Custom Static JSON
        $settings[] = array(
            "types" => "custom",
            "label" => __("Custom Static JSON", "blended"),
            "id" => "nav_csj",
            "data" => "#"
        );

        return array("items" => $settings);
    }

}
