<?php

if(!defined('ABSPATH')) die('-1');

class AwesomeLiveChat_Admin extends AwesomeLiveChat
{
    /**
     * Boots object
     *
     * @since  1.0.0
     * @access private
     * @var object
     */
    private $Boots;

    /**
     * Settings/Options
     *
     * @since  1.0.0
     * @access private
     * @var array
     */
    private $Options;

    /**
     * Library
     *
     * @since  1.0.0
     * @access private
     * @var object
     */
    private $_;

    /**
     * Boots Admin Extension
     *
     * @since  1.0.0
     * @access private
     * @var object
     */
    private $Admin;

    /**
     * Chat Departments
     *
     * @since  1.0.0
     * @access private
     * @var array
     */
    private $Departments;

    /**
     * Get the Boots framework object.
     * Get the plugin settings.
     * Get the plugin library.
     *
     * @since  1.0.0
     * @uses   AwesomeLiveChat::boots()
     *         return boots object
     * @uses   AwesomeLiveChat::options()
     *         return options
     * @uses   AwesomeLiveChat_Library
     *         plugin library/helper
     * @access public
     * @param  void
     * @return void
     */
    public function __construct()
    {
        $this->Boots    = $this->boots();
        $this->Options  = $this->options();
        $this->_        = new AwesomeLiveChat_Library();
        $this->Admin    = $this->Boots->Admin;

        add_action('admin_menu', array($this, 'admin'));

        add_action(
            'boots_admin_print_scripts-awesome_live_chat_admin',
            array($this, 'jsAdmin')
        );
        add_action(
            'boots_admin_print_styles-awesome_live_chat_admin',
            array($this, 'cssAdmin')
        );
        add_action(
            'boots_admin_print_scripts-awesome_live_chat_operator',
            array($this, 'jsArchives')
        );
        add_action(
            'boots_admin_print_styles-awesome_live_chat_operator',
            array($this, 'cssArchives')
        );

        add_filter(
            'boots_admin_save_options-awesome_live_chat_admin',
            array($this, 'saveOptions')
        );

        add_filter(
            'boots_admin_save_options-awesome_live_chat_operator',
            array($this, 'saveOperatorConfig')
        );

        add_action(
            'boots_admin_restore_options-awesome_live_chat_admin',
            array($this, 'restoreOptions')
        );

        // Pruning of database
        add_filter('boots_admin_buttons', array($this, 'prune'));
        add_action('boots_ajax_awesome_live_chat-prune', array($this, 'ajax_prune'));

        // Licensing
        add_action('boots_ajax_awesome_live_chat-license', array($this, 'ajax_license'));
    }

    /**
     * Load the available departments
     *
     * @since  1.3.6
     * @uses   AwesomeLiveChat_Library::getAllDepartments
     * @access public
     * @param  void
     * @return null
     */
    public function loadDepartments()
    {
        if(!is_null($this->Departments)) return null;
        $this->Departments = $this->_->getAllDepartments();
    }

    /**
     * Enqueue admin settings javascript.
     *
     * @since  1.0.0
     * @uses   Boots::Enqueue Enqueue js
     * @access private
     * @param  string  base js slug
     * @return void
     */
    public function jsAdmin($base)
    {
        $this->loadDepartments();
        $Depts = array();
        foreach($this->Departments as $Dept)
        {
            $Depts[] = $Dept->name;
        }
        $this->Boots->Enqueue
        ->raw_script('ace')
            ->source('//cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js')
            ->version('1.1.3')
            ->done(true)
        ->script('awesome-live-chat-settings')
            ->source('admin/js/awesome-live-chat-settings.js')
            ->requires($base)
            ->requires('ace')
            ->vars('departments', $Depts)
            ->vars('action_prune', 'awesome_live_chat-prune')
            ->vars('nonce_prune', wp_create_nonce('awesome-live-chat-nonce-prune'))
            ->vars('action_license', 'awesome_live_chat-license')
            ->vars('nonce_license', wp_create_nonce('awesome-live-chat-nonce-license'))
            ->done(true);
    }

    /**
     * Enqueue admin settings stylesheet.
     *
     * @since  1.0.0
     * @uses   Boots::Enqueue Enqueue css
     * @access private
     * @param  string  base css slug
     * @return void
     */
    public function cssAdmin($base)
    {
        $this->Boots->Enqueue
        ->style('awesome-live-chat-operator')
            ->source('admin/css/operator.css')
            ->requires($base)
            ->done();
    }

    /**
     * Enqueue admin archives javascript.
     *
     * @since  1.0.0
     * @uses   Boots::Enqueue Enqueue js
     * @access private
     * @param  string  base js slug
     * @return void
     */
    public function jsArchives($base)
    {
        $this->Boots->Enqueue
        ->script('awesome-live-chat-archives')
            ->source('admin/js/awesome-live-chat-archives.js')
            ->requires($base)
            ->done(true);
    }

    /**
     * Enqueue admin archives stylesheet.
     *
     * @since  1.0.0
     * @uses   Boots::Enqueue Enqueue css
     * @access private
     * @param  string  base css slug
     * @return void
     */
    public function cssArchives($base)
    {
        $this->Boots->Enqueue
        ->style('awesome-live-chat-archives')
            ->source('admin/css/archives.css')
            ->requires($base)
            ->done();
    }

    public function saveOptions($Args)
    {
        if(!isset($Args['alc_settings']['general']['placement']))
        {
            $Args['alc_settings']['general']['placement'] = array();
        }
        if(!isset($Args['alc_settings']['general']['hide_status']))
        {
            $Args['alc_settings']['general']['hide_status'] = array();
        }
        if(!isset($Args['alc_settings']['general']['hide_website']))
        {
            $Args['alc_settings']['general']['hide_website'] = array();
        }

        $this->loadDepartments();
        $Departments = $this->Departments;
        $Depts = array();
        foreach($Departments as $Dept)
        {
            if(!(bool)$Dept->disabled)
                $Depts[] = $Dept->name;
        }
        if(implode(',', $Depts) != $Args['alc_settings']['departments'])
        {
            $Depts_N = explode(',', $Args['alc_settings']['departments']);
            $Disabled = array_diff($Depts, $Depts_N);
            if($Disabled)
            {
                $this->_->disableDepartments($Disabled);
                do_action(
                    'awesome_live_chat_operator_disabled_departments',
                    $Disabled
                );
            }
            $this->_->addDepartments($Depts_N);
        }

        $this->Boots->Database
            ->term('alc_last_modified')
            ->update(current_time('timestamp', 1));

        unset($Args['alc_settings']['departments']);
        unset($Args['alc_license_code']);

        return $Args;
    }

    public function saveOperatorConfig($Args)
    {
        $user_id = get_current_user_id();
        $this->_->setOperator(
            $user_id,
            'alc_welcome',
            $Args['alc_welcome']
        );
        if(!empty($Args['alc_pincode']))
        {
            $this->_->setOperator(
                $user_id,
                'alc_pincode',
                md5($Args['alc_pincode'])
            );
            $this->_->setOperator(
                $user_id,
                'alc_token',
                $this->_->generateOperatorToken()
            );
        }

        unset($Args['alc_welcome'], $Args['alc_pincode']);

        return $Args;
    }

    public function restoreOptions($Args)
    {
        $this->Boots->Database
            ->term('alc_settings')
            ->update($this->_->defaults(array(
                'license' => array('code', 'verified')
            )));
        $this->Boots->Database
            ->term('alc_last_modified')
            ->update(current_time('timestamp', 1));
        return true;
    }

    private function settingsAbout()
    {
        $Settings = $this->_->settings('about');
        $License = $this->Boots->Database
        ->term('alc_license', array())
        ->get();
        include dirname(__FILE__) . '/about.php';
    }

    private function settingsGeneral()
    {
        $Settings = $this->_->settings('general');
        include dirname(__FILE__) . '/general.php';
    }

    private function settingsMail()
    {
        $Settings = $this->_->settings('mail');
        include dirname(__FILE__) . '/mail.php';
    }

    private function settingsStrings()
    {
        $Settings = $this->_->settings('strings');
        include dirname(__FILE__) . '/strings.php';
    }

    private function settingsSkin()
    {
        $Settings = $this->_->settings('skin');
        include dirname(__FILE__) . '/skin.php';
    }

    private function settingsSocket()
    {
        $Settings = $this->_->settings('socket');
        include dirname(__FILE__) . '/socket.php';
    }

    private function settingsCss()
    {
        $css = stripslashes($this->_->settings('css'));
        include dirname(__FILE__) . '/css.php';
    }

    private function settingsJs()
    {
        $js = stripslashes($this->_->settings('js'));
        include dirname(__FILE__) . '/js.php';
    }

    private function settingsDepartments()
    {
        $this->loadDepartments();
        $Departments = $this->Departments;
        include dirname(__FILE__) . '/departments.php';
    }

    private function settingsBlock()
    {
        $block = $this->_->settings('block');
        include dirname(__FILE__) . '/block.php';
    }

    private function operatorArchives()
    {
        include dirname(__FILE__) . '/archives.php';
    }

    private function operatorChat()
    {
        if(!isset($_GET['page'])) return false;
        $page = $_GET['page'];
        if(
            $page == 'awesome_live_chat_operator'
            && $this->_->operatorHasDepartments()
        ) add_action('admin_footer', array($this, 'chat'));
    }

    private function operatorConfig()
    {
        include dirname(__FILE__) . '/operator-config.php';
    }

    public function admin()
    {
        $this->loadDepartments();
        $this->Admin->menu(
            'awesome_live_chat_admin',
            'Awesome Live Chat',
            'Awesome Live Chat'
        )->icon('dashicons-format-chat', true);
        $this->Admin->menu('awesome_live_chat_admin', __('Settings', 'awesome-live-chat'))
            ->layout('grid')
            ->restore(
                __('Restore to factory', 'awesome-live-chat'),
                __('Are you sure?', 'awesome-live-chat'),
                __('Yes', 'awesome-live-chat'),
                __('Cancel', 'awesome-live-chat')
            );
        $this->settingsAbout();
        $this->settingsGeneral();
        $this->settingsMail();
        $this->settingsStrings();
        $this->settingsSkin();
        $this->settingsCss();
        $this->settingsJs();
        $this->settingsDepartments();
        $this->settingsBlock();
        $this->settingsSocket();
        $this->Admin->menu(
            'awesome_live_chat_operator',
            __('Operator', 'awesome-live-chat'),
            __('Operator', 'awesome-live-chat'),
            'operate_alc'
        )->layout('grid');
        $this->operatorChat();
        $this->operatorConfig();
        $this->operatorArchives();
        $this->Admin->done(__('Save', 'awesome-live-chat'));
    }

    public function chat()
    {
        include dirname(__FILE__) . '/../backend/chat.php';
    }

    public function prune($slug)
    {
        switch($slug)
        {
            case 'awesome_live_chat_admin':
                echo '
                    <a href="#" class="button-secondary js-prune">
                        ' . __('Prune database', 'awesome-live-chat') . '
                    </a>
                    <div id="awesome_live_chat_prune_lb" style="display:none;">
                        <h3>' . __('Prune database', 'awesome-live-chat') . '</h3>
                        <hr />
                        ' . __('Remove', 'awesome-live-chat') . '
                        <select name="awesome_live_chat_prune_what">
                            <option value="all">' . __('All', 'awesome-live-chat') . '</option>
                            <option value="expired" selected="selected">' . __('Expired', 'awesome-live-chat') . '</option>
                        </select> ' . __('records', 'awesome-live-chat') . ' <br />' . __('in', 'awesome-live-chat') . '
                        <select name="awesome_live_chat_prune_where">
                            <option value="every">' . __('Every', 'awesome-live-chat') . '</option>
                            <option value="departments">' . __('Departments', 'awesome-live-chat') . '</option>
                            <option value="visitors">' . __('Visitors', 'awesome-live-chat') . '</option>
                            <option value="chat">' . __('Chat', 'awesome-live-chat') . '</option>
                        </select> ' . __('database table', 'awesome-live-chat') . '.
                        <hr />
                        <a href="#" class="button-primary js-prune-ok" rel="modal:close">' . __('Prune', 'awesome-live-chat') . '</a>
                        <a href="#" class="button-secondary js-prune-cancel" rel="modal:close">' . __('Cancel', 'awesome-live-chat') . '</a>
                    </div>
                ';
                break;
            default: break;
        }
    }

    public function ajax_prune($nonce)
    {
        header('content-type: application/json; charset=' . $this->Boots->Database->term('blog_charset')->get());
        if(!wp_verify_nonce($nonce, 'awesome-live-chat-nonce-prune'))
        {
            die(json_encode(array('error'=>__('insecure access', 'awesome-live-chat'))));
        }

        $what = isset($_POST['what'])
            ? sanitize_text_field($_POST['what'])
            : false;
        $where = isset($_POST['where'])
            ? sanitize_text_field($_POST['where'])
            : false;
        if(
            !in_array($what, array('all', 'expired'))
            || !in_array($where, array('every', 'departments', 'visitors', 'chat'))
        ) die(json_encode(array(false)));

        if($where == 'every')
        {
            $this->_->pruneTable('departments', $what);
            $this->_->pruneTable('visitors', $what);
            $this->_->pruneTable('chat', $what);
        } else $this->_->pruneTable($where, $what);

        do_action('awesome_live_chat-ajax-prune');
        die(json_encode(array('success' => true)));
    }

    public function ajax_license($nonce)
    {
        header('content-type: application/json; charset=' . $this->Boots->Database->term('blog_charset')->get());
        if(!wp_verify_nonce($nonce, 'awesome-live-chat-nonce-license'))
        {
            die(json_encode(array('error'=>__('insecure access', 'awesome-live-chat'))));
        }

        $what = isset($_POST['what'])
            ? $_POST['what']
            : false;

        $License = $this->Boots->Database
        ->term('alc_license', array())
        ->get();

        switch($what)
        {
            case 'activate':
                $key = isset($_POST['key'])
                ? sanitize_text_field($_POST['key'])
                : false;
                if(!$key) die(json_encode(array('verified' => false)));
                $verified = apply_filters('awesome_live_chat_verify', $key);
                $License['key'] = $key;
                $License['verified'] = $verified;
                $this->Boots->Database
                ->term('alc_license')
                ->update($License);
                die(json_encode(array('verified' => $verified)));
            break;
            case 'revoke':
                do_action('awesome_live_chat_unverify', $License['key']);
                $this->Boots->Database
                ->term('alc_license')
                ->update(array());
                die(json_encode(array('revoked' => true)));
            break;
        }
    }
}
new AwesomeLiveChat_Admin();
