<?php

/*
Plugin Name: Awesome Live Chat
Plugin URI: http://awe5o.me/live-chat
Description: Make your customers feel awesome by providing live chat support.
Version: 1.4.2
Author: اسکریپت دات کام
Author URI: http://www.اسکریپت.com
Text Domain: awesome-live-chat
*/

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

require_once dirname(__FILE__) . '/boots/api.php';

require_once dirname(__FILE__) . '/utility.php';

/**
 * AwesomeLiveChat startup
 *
 * @package AwesomeLiveChat
 * @since   1.0.0
 */
class AwesomeLiveChat
{
    /**
     * Boots object
     *
     * @since  1.0.0
     * @access private
     * @static object
     */
    static private $Boots;

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

    /**
     * Load the Boots framework.
     * Update and save settings.
     *
     * @since  1.0.0
     * @uses   Boots
     * @uses   $wpdb  WordPress global $wpdb to access prefix
     * @access public
     * @param  array  Plugin base arguments/options
     * @return bool   Exit
     */
    public function __construct($Args = false)
    {
        if(!$Args) return false;
        self::$Boots   = new Boots('plugin', $Args);
        global $wpdb;
        $db_prefix = $wpdb->prefix;
        $Args['ALC_TABLE_DEPARTMENTS']
            = $db_prefix . $Args['ALC_TABLE_DEPARTMENTS'];
        $Args['ALC_TABLE_USERS']
            = $db_prefix . $Args['ALC_TABLE_USERS'];
        $Args['ALC_TABLE_CHAT']
            = $db_prefix . $Args['ALC_TABLE_CHAT'];
        $apiurl = $Args['APP_URL'] . '/api/v' . $Args['ALC_API_VERSION'];
        $Args['ALC_API_URL_VISITOR'] = $apiurl . '/u.php';
        $Args['ALC_API_URL_OPERATOR'] = $apiurl . '/o.php';
        self::$Options = $Args;

        // Let operators access the dashboard if blocked by woocommerce
        add_filter(
            'woocommerce_prevent_admin_access',
            array($this, 'woocommerceAllowOperatorAccess'),
            10,
            1
        );

        add_action('plugins_loaded', array($this, 'i18n'));
        add_action('plugins_loaded', array($this, 'install'));
        register_activation_hook(__FILE__, array($this, 'install'));
        register_deactivation_hook(__FILE__, array($this, 'uninstall'));
    }

    /**
     * Get Boots object.
     *
     * @since  1.0.0
     * @access protected
     * @param  void
     * @return object    Boots object
     */
    protected function boots()
    {
        return self::$Boots;
    }

    /**
     * Get options.
     *
     * @since  1.0.0
     * @access protected
     * @param  string    Option term
     * @return mixed     Options array or term value
     */
    protected function options($term = '')
    {
        return $term ? self::$Options[$term] : self::$Options;
    }

    /**
     * SQL for departments table.
     *
     * @since 1.3.8
     * Add wpdb charset collate
     * @uses   $wpdb  WordPress global $wpdb to access prefix
     *
     * @since  1.0.0
     * @uses   AwesomeLiveChat::$Options['ALC_TABLE_DEPARTMENTS']
     *         Departments table name
     * @access private
     * @param  void
     * @return string  Departments table sql
     */
    private function sqlTableDepartments()
    {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table_departments = self::$Options['ALC_TABLE_DEPARTMENTS'];
        return "CREATE TABLE $table_departments (
            id int(11) unsigned NOT NULL AUTO_INCREMENT,
            name VARCHAR(100) NOT NULL,
            description VARCHAR(255) DEFAULT '' NOT NULL,
            disabled tinyint(1) DEFAULT 0,
            created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            updated_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY name (name)
        ) $charset_collate;";
    }

    /**
     * SQL for users table.
     *
     * @since 1.3.8
     * Add wpdb charset collate
     * @uses   $wpdb  WordPress global $wpdb to access prefix
     *
     * @since  1.0.0
     * @uses   AwesomeLiveChat::$Options['ALC_TABLE_USERS']
     *         Users table name
     * @access private
     * @param  void
     * @return string  Users table sql
     */
    private function sqlTableUsers()
    {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table_users = self::$Options['ALC_TABLE_USERS'];
        return "CREATE TABLE $table_users (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            operator_id bigint(20) unsigned DEFAULT 0 NOT NULL,
            department int(11) unsigned NOT NULL,
            token VARCHAR(100) NOT NULL,
            name VARCHAR(255) NOT NULL,
            email VARCHAR(255) NOT NULL,
            website VARCHAR(255) DEFAULT '' NOT NULL,
            gravatar VARCHAR(255) DEFAULT '' NOT NULL,
            status VARCHAR(20) DEFAULT 'waiting' NOT NULL,
            ip VARCHAR(255) NOT NULL,
            uri VARCHAR(255) DEFAULT '' NOT NULL,
            country VARCHAR(255) DEFAULT '' NOT NULL,
            city VARCHAR(255) DEFAULT '' NOT NULL,
            cc VARCHAR(2) DEFAULT '' NOT NULL,
            ping_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            PRIMARY KEY  (id),
            UNIQUE KEY token (token)
        ) $charset_collate;";
    }

    /**
     * SQL for chat table.
     *
     * @since 1.3.8
     * Add wpdb charset collate
     * @uses   $wpdb  WordPress global $wpdb to access prefix
     *
     * @since  1.0.0
     * @uses   AwesomeLiveChat::$Options['ALC_TABLE_CHAT']
     *         Chat table name
     * @access private
     * @param  void
     * @return string  Chat table sql
     */
    private function sqlTableChat()
    {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table_chat = self::$Options['ALC_TABLE_CHAT'];
        return "CREATE TABLE $table_chat (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            guid varchar(16) DEFAULT '',
            user_id bigint(20) unsigned NOT NULL,
            operator_id bigint(20) unsigned NOT NULL,
            message text NOT NULL,
            seen tinyint(1) DEFAULT 0,
            operator tinyint(1) DEFAULT 0,
            created_at datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
            PRIMARY KEY  (id)
        ) $charset_collate;";
    }

    /**
     * Create departments, users and chat tables
     * in the WordPress database.
     *
     * @since  1.0.0
     * @uses   dbDelta() WordPress function to save sql table
     * @uses   AwesomeLiveChat::sqlTableDepartments()
     *         Receive SQL for departments table
     * @uses   AwesomeLiveChat::sqlTableUsers()
     *         Receive SQL for users table
     * @uses   AwesomeLiveChat::sqlTableChat()
     *         Receive SQL for chat table
     * @access private
     * @param  void
     * @return void
     */
    private function createTables()
    {
        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($this->sqlTableDepartments());
        dbDelta($this->sqlTableUsers());
        dbDelta($this->sqlTableChat());
    }

    /**
     * Add operator role as 'alc_operator'.
     * Set permission to 'read' and 'operate_alc'.
     *
     * @since  1.0.0
     * @uses   add_role() WordPress function to add a role
     * @access private
     * @param  void
     * @return void
     */
    private function addOperatorRole()
    {
        add_role(
            'alc_operator',
            __('Chat Operator', 'awesome-live-chat'),
            array(
                'read' => true,
                'operate_alc' => true
            )
        );
    }

    public function woocommerceAllowOperatorAccess($redirect)
    {
        if (current_user_can('operate_alc')) {
            return false;
        }
        return $redirect;
    }

    /**
     * Internationalization.
     *
     * @since  1.0.0
     * @uses   load_plugin_textdomain()
     *         WordPress function to load plugin locale (.mo) file
     * @access public
     * @param  void
     * @return void
     */
    public function i18n()
    {
        load_plugin_textdomain(
            'awesome-live-chat',
            false,
            dirname( plugin_basename( __FILE__ ) ) . '/languages'
        );
    }

    /**
     * Setup tables, operator role and
     * version information if new.
     *
     * @action awesome_live_chat_install
     *
     * @since  1.0.0
     * @uses   delete_transient()
     *         Delete a transient
     * @uses   Boots::Database
     * @uses   AwesomeLiveChat::createTables()
     *         Creates tables
     * @uses   AwesomeLiveChat::addOperatorRole()
     *         Adds operator role
     * @access public
     * @param  void
     * @return bool
     */
    public function install()
    {
        $version = self::$Boots->Database
            ->term('awesome_live_chat')
            ->get();
        if($version && version_compare(
            self::$Options['APP_VERSION'],
            $version,
            '<='
        )) return false;
        $this->createTables();
        $this->addOperatorRole();
        delete_transient('awesome_live_chat_about');
        do_action('awesome_live_chat_install', $version);
        self::$Boots->Database
            ->term('awesome_live_chat')
            ->update(self::$Options['APP_VERSION']);
    }

    /**
     * Uninstallation.
     *
     * @action awesome_live_chat_uninstall
     *
     * @since  1.2.7
     * @access public
     * @param  void
     * @return bool
     */
    public function uninstall()
    {
        $version = self::$Options['APP_VERSION'];
        do_action('awesome_live_chat_uninstall', $version);
    }
}

new AwesomeLiveChat(array(
    'ABSPATH'     => __FILE__,
    'APP_ID'      => 'awesome_live_chat',
    'APP_NICK'    => 'Awesome Live Chat',
    'APP_VERSION' => '1.4.2',
    'APP_ICON'    => 'images/icon.png',
    'APP_LOGO'    => 'images/logo.png',
    // plugin specific
    'NOTIFIER_URL'          => 'http://api.awe5o.me/v1/packages/live-chat',
    'IP2COUNTRY_URL'        => 'http://freegeoip.net/json',
    'ALC_API_VERSION'       => '1',
    'ALC_TABLE_DEPARTMENTS' => 'alc_departments',
    'ALC_TABLE_USERS'       => 'alc_users',
    'ALC_TABLE_CHAT'        => 'alc_chat'
));

require_once dirname(__FILE__) . '/library.php';
require_once dirname(__FILE__) . '/updater.php';
require_once dirname(__FILE__) . '/profile.php';
require_once dirname(__FILE__) . '/metabox.php';
require_once dirname(__FILE__) . '/admin/index.php';
require_once dirname(__FILE__) . '/backend/index.php';
require_once dirname(__FILE__) . '/frontend/index.php';
