<?php

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

class AwesomeLiveChat_Profile 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 $_;

    /**
     * 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 class
     * @access public
     * @param  void
     * @return void
     */
    public function __construct()
    {
        $this->Boots    = $this->boots();
        //$this->Options  = $this->options();
        $this->_        = new AwesomeLiveChat_Library();

        add_action(
            'awesome_live_chat_operator_disabled_departments',
            array($this, 'disableDepartments')
        );

        add_action('admin_enqueue_scripts', array($this, 'enqueue'));
        add_action('admin_init', array($this, 'hideOperatorDashboard'));
        add_action('edit_user_profile', array($this, 'departmentsField'));
        add_action('show_user_profile', array($this, 'departmentsField'));
        add_action('edit_user_profile_update', array($this, 'updateDepartmentsField'));
        add_action('personal_options_update', array($this, 'updateDepartmentsField'));
    }

    /**
     * Parse/Cast a value to an integer.
     *
     * @since  1.0.0
     * @access private
     * @param  mixed   Value to parse
     * @return int     Integer value
     */
    private function toInteger($value)
    {
        return (int) $value;
    }

    /**
     * Disable/Remove operator departments.
     * Fired using action hook when
     * departments disabled in settings.
     *
     * @since  1.0.0
     * @uses   AwesomeLiveChat_Library::getDepartment()
     *         get a department's term
     * @uses   AwesomeLiveChat_Library::getAllOperators()
     *         get all operator ids
     * @uses   AwesomeLiveChat_Library::getOperator()
     *         get operator term
     * @uses   AwesomeLiveChat_Library::setOperator()
     *         set operator term
     * @access private
     * @param  array   Department names
     * @return void
     */
    public function disableDepartments($Departments)
    {
        foreach($Departments as $dept)
        {
            $did = $this->_->getDepartment('id', 'name', $dept);
            $Disabled[] = $did;
        }
        $Operators = $this->_->getAllOperators();
        if(!$Operators) return false;
        foreach($Operators as $oid)
        {
            $Odids = $this->_->getOperator($oid, 'alc_departments');
            if($Odids && is_array($Odids))
            {
                $this->_->setOperator(
                    $oid,
                    'alc_departments',
                    array_diff($Odids, $Disabled)
                );
            }
        }
    }

    /**
     * Echo out the departments field
     * in the profile page.
     *
     * @since  1.0.0
     * @uses   current_user_can()
     *         user permission
     * @uses   get_current_user_id()
     *         get the current user id
     * @uses   AwesomeLiveChat_Library::getOperator()
     *         get operator term
     * @uses   AwesomeLiveChat_Library::getDepartment()
     *         get department term
     * @uses   AwesomeLiveChat_Library::getAllDepartments()
     *         get all departments
     * @uses   Boots::Form
     *         Boots form extension
     * @access public
     * @param  object User object
     * @return void
     */
    public function departmentsField($User)
    {
        if(current_user_can('create_users') || current_user_can('add_users'))
        {
            echo '<div class="boots-form">';
            echo '<hr /><h3>Awesome Live Chat <small>' . __('Options', 'awesome-live-chat') . '</small></h3>';
            $Departments = $this->_->getAllDepartments(true);
            $Data = array();
            foreach($Departments as $Dept)
            {
                $Data[$Dept->id] = $Dept->name;
            }
            if(!count($Data))
            {
                echo '<label>' . __('Departments', 'awesome-live-chat') . '</label>';
                _e('There are no departments to select from. If you want to assign a chat department to this user, you first need to create a department.', 'awesome-live-chat');
                echo '<hr /></div>';
                return false;
            }
            $Current = $this->_->getOperator($User->ID, 'alc_departments');
            echo $this->Boots->Form->generate('multiple', array(
                'title' => __('Departments', 'awesome-live-chat'),
                'name'  => 'alc_departments',
                'data'  => $Data,
                'value' => is_array($Current) ? $Current : array(),
                'style' => 'width: 350px;'
            ));
            echo '<hr /></div>';
        }
        else if($User->ID == get_current_user_id() && current_user_can('operate_alc'))
        {
            echo '<hr /><h3>Awesome Live Chat <small>' . __('Departments', 'awesome-live-chat') . '</small></h3>';
            _e('You are an operator for the following departments:', 'awesome-live-chat');
            echo '<p><strong>';
            $Departments = $this->_->getOperator($User->ID, 'alc_departments');
            if(is_array($Departments))
            {
                $comma = '';
                foreach($Departments as $did)
                {
                    $dept = $this->_->getDepartment('name', 'id', $did);
                    if($dept)
                    {
                        echo $comma . $dept;
                        $comma = ', ';
                    }
                }
            }
            echo '</strong></p><hr />';
        }
    }

    /**
     * Update the departments field
     * for the operator based on
     * form submission
     *
     * @since  1.0.0
     * @uses   current_user_can()
     *         user permission
     * @uses   delete_user_meta()
     *         delete a user's meta
     * @uses   AwesomeLiveChat_Library::getOperator()
     *         get operator term
     * @uses   AwesomeLiveChat_Library::setOperator()
     *         set operator term
     * @uses   AwesomeLiveChat_Library::getDepartment()
     *         get department term
     * @access public
     * @param  int    User id
     * @return bool   Exit
     */
    public function updateDepartmentsField($user_id)
    {
        if(current_user_can('create_users') || current_user_can('add_users'))
        {
            $User = new WP_User($user_id);
            if(!isset($_POST['alc_departments']) || !is_array($_POST['alc_departments']))
            {
                // remove capability
                $User->remove_cap('operate_alc');
                delete_user_meta($user_id, 'alc_departments');
                delete_user_meta($user_id, 'alc_token');
                return false;
            }
            // add capability
            $User->add_cap('operate_alc');
            $Departments = array_filter(array_map(
                array($this, 'toInteger'), $_POST['alc_departments']),
                'is_int'
            );
            $this->_->setOperator($user_id, 'alc_departments', $Departments);

            if(!$this->_->getOperator($user_id, 'alc_token'))
            {
                $this->_->setOperator($user_id, 'alc_token', $this->_->generateOperatorToken());
            }
        }
    }

    /**
     * Hide dashboard menu item
     * and area if admin doesn't allow.
     *
     * @since  1.0.0
     * @uses   $current_user
     *         WordPress global
     * @uses   $pagenow
     *         WordPress global
     * @uses   remove_menu_page()
     *         remove a menu item and page
     * @uses   wp_redirect()
     *         redirect to a url
     * @uses   Boots::Database
     *         Boots database extension
     * @access public
     * @param  void
     * @return bool   Exit
     */
    public function hideOperatorDashboard()
    {
        if($this->_->settings('general', 'restrict_op') == 'no')
            return false;
        global $current_user, $pagenow;
        if(array_shift($current_user->roles) == 'alc_operator')
        {
            remove_menu_page('index.php');
            if($pagenow == 'index.php')
            {
                $home = $this->Boots->Database->term('siteurl')->get();
                wp_redirect($home . '/wp-admin/profile.php');
            }
        }
    }

    /**
     * Enqueue Boots form
     * styles and scripts
     * in the profile page.
     *
     * @since  1.0.0
     * @uses   $pagenow
     *         WordPress global
     * @uses   Boots::Form
     *         Boots form extension
     * @access public
     * @param  void
     * @return void
     */
    public function enqueue()
    {
        global $pagenow;
        if(in_array($pagenow, array('profile.php','user-edit.php')))
        {
            $this->Boots->Form->styles();
            $this->Boots->Form->scripts();
        }
    }
}
new AwesomeLiveChat_Profile();