
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
/**
 * Settings Page for Giga Messenger Bots
 *
 * @author Gary <gary@giga.ai>
 */

namespace GigaAI;

use GigaAI\Http\Request;
use GigaAI\Http\ThreadSettings;
use GigaAI\Storage\Eloquent\Instance;

class Settings
{
    /**
     * Store all tabs to display in settings page
     *
     * @var array
     */
    private $tabs = [];
    
    /**
     * Current active tab
     *
     * @var string
     */
    private $current_tab = 'basics';
    
    /**
     * Settings of current opening instance
     *
     * @var array|mixed
     */
    private $settings = [];
    
    private $title = '';
    
    /**
     * Constructor only to define hooks
     *
     */
    public function __construct()
    {
        add_action('admin_menu', [$this, 'admin_menu']);
        
        add_action('admin_init', [$this, 'admin_init']);
        
        add_action('admin_enqueue_scripts', [$this, 'admin_enqueue'], 99);
        
        $this->tabs = [
            'basics'              => __('Basics', 'giga-messenger-bots'),
            'greeting'            => __('Greeting Text', 'giga-messenger-bots'),
            'get-started'         => __('Get Started Button', 'giga-messenger-bots'),
            'persistent-menu'     => __('Persistent Menu', 'giga-messenger-bots'),
            'domain-whitelisting' => __('Domain Whitelisting', 'giga-messenger-bots'),
            'account-linking'     => __('Account Linking', 'giga-messenger-bots'),
            'auto-stop'           => __('Auto Stop', 'giga-messenger-bots'),
            // 'target-audience'     => __('Target Audience', 'giga-messenger-bots')
        ];
    }
    
    /**
     * Create admin menu under Settings
     *
     * @return void
     */
    public function admin_menu()
    {
        add_menu_page(
            __('Giga AI', 'giga-messenger-bots'),
            __('Giga AI', 'giga-messenger-bots'),
            'manage_options',
            'giga',
            [$this, 'settings'],
            GIGA_URL . 'assets/img/giga-ai.png'
        );
        
        add_submenu_page('giga',
            __('Settings', 'giga-messenger-bots'),
            __('Settings', 'giga-messenger-bots'),
            'manage_options', 'giga',
            [$this, 'settings']
        );
    }
    
    /**
     * Enqueue styles and script in admin.
     *
     * @return void
     */
    public function admin_enqueue()
    {
        if (is_array($this->settings)) {
            wp_localize_script('giga-messenger-bots', 'settings', $this->settings);
        }
        
        $supported_locales = giga_get_supported_locales();
        $default_persistent_menu = giga_get_default_persistent_menu();
        
        wp_localize_script('giga-messenger-bots', 'supportedLocales', $supported_locales);
        wp_localize_script('giga-messenger-bots', 'defaultPersistentMenu', $default_persistent_menu);
        
        wp_enqueue_script('giga-messenger-bots');
    }
    
    /**
     * All plugin settings saved in this method
     */
    public function admin_init()
    {
        register_setting('giga_messenger_bots', 'giga_messenger_bot_settings');
        
        $this->settings = giga_setting();
        
        if (isset($this->settings['page_id']) && $this->settings['page_id'] && ! isset($_GET['_action']) && ! isset($_GET['_instance_id'])
            && file_exists(GIGA_INC_DIR . 'settings/_partials/multipage.php')
        ) {
            $this->tabs['multipage'] = __('Multipage', 'giga-messenger-bots');
        }
        
        $this->current_tab = (isset($_GET['tab']) && array_key_exists($_GET['tab'], $this->tabs)) ? trim($_GET['tab']) : 'basics';
        
        // Delete Page
        if (isset($_GET['_action']) && $_GET['_action'] === 'delete') {
            $this->deleteInstance($_GET['_instance_id']);
        }
        
        if (isset($_POST['_page_now']) && $_POST['_page_now'] == 'giga') {
            
            if ( ! check_admin_referer('giga_settings_nonce', 'giga_settings_nonce')) {
                return;
            }
            
            $this->save_plugin_settings();
            
            Session::flash([
                'status'  => 'success',
                'message' => __('Settings saved!', 'giga-messenger-bots'),
            ]);
            
            if ($_POST['_action'] === 'create') {
                giga_refresh([
                    '_instance_id' => $_POST['page_id'],
                ]);
            }
            
            giga_refresh();
        }
    }
    
    /**
     * Save plugin settings
     *
     * @return void
     */
    private function save_plugin_settings()
    {
        $old_setting = $this->settings;
        
        $new_setting = [];
        
        $defaults = giga_default_settings();
        
        // Sanitize data before update
        foreach ($defaults as $key => $value) {
            
            $new_setting[$key] = $value;
            
            if (isset($old_setting[$key])) {
                $new_setting[$key] = $old_setting[$key];
            }
            
            if (isset($_POST[$key])) {
                
                if (is_string($_POST[$key])) {
                    $new_setting[$key] = sanitize_text_field($_POST[$key]);
                }
                
                // We don't use sanitize_text_field for these special fields. Should do our logic.
                if ($key === 'whitelisted_domains' || $key === 'auto_stop') {
                    $new_setting[$key] = $_POST[$key];
                }
            }
        }
        
        /** Handle Auto Stop */
        if (isset($_POST['check_auto_stop'])) {
            if ( ! isset($new_setting['auto_stop'])) {
                $new_setting['auto_stop'] = [];
            }
            
            if ( ! isset($new_setting['auto_stop']['stop_when']) || empty($new_setting['auto_stop']['stop_when'])) {
                $new_setting['auto_stop']['stop_when'] = '*';
            }
            
            if ( ! isset($new_setting['auto_stop']['restart_when']) || empty($new_setting['auto_stop']['restart_when'])) {
                $new_setting['auto_stop']['restart_when'] = ':)';
            }
        }
        
        // User uncheck the check auto stop in auto stop tab
        if ( ! isset($_POST['check_auto_stop']) && isset($_POST['auto_stop'])) {
            $new_setting['auto_stop'] = false;
        }
        
        if (isset($_POST['_setting_tab']) && $_POST['_setting_tab'] === 'multipage') {
            $new_setting['multipage'] = isset($_POST['multipage']);
        }
        
        // Persistent Menu rendered via AngularJS as object so we have to decode it
        if ( ! empty($new_setting['persistent_menu']) && ! is_array($new_setting['persistent_menu'])) {
            $new_setting['persistent_menu'] = json_decode(stripslashes($_POST['persistent_menu']), true);
        }
        
        if ( ! empty($new_setting['greeting']) && ! is_array($new_setting['greeting'])) {
            $new_setting['greeting'] = json_decode(stripslashes($_POST['greeting']), true);
        }
        
        // If Page Access Token changed. Send subscribe request to Facebook. Also set the status.
        if ( ! empty($new_setting['page_access_token'])) {
            // Modify token because it only change when page loaded.
            Request::$token = $new_setting['page_access_token'];
            
            // Send subscribe request to Facebook each time Settings changed
            $status = Request::sendSubscribeRequest();
            
            if (isset($status->success) && $status->success == 1) {
                $new_setting['connection_status'] = 'success';
            } else {
                $new_setting['connection_status'] = 'error';
            }
        }
        
        // Allows users filter the value before the update
        $new_setting = apply_filters('giga_settings_before_update', $new_setting);
        
        // Validation
        if (empty($new_setting['page_id'])) {
            Session::flash([
                'status'  => 'error',
                'message' => __('Please enter your Page ID', 'giga-messenger-bots'),
            ]);
            
            giga_refresh();
        }
        
        if (empty($new_setting['page_access_token'])) {
            Session::flash([
                'status'  => 'error',
                'message' => __('Please enter your page access token', 'giga-messenger-bots'),
            ]);
            
            giga_refresh();
        }
        
        // Only save the settings for main instance
        if (empty($_POST['_instance_id']) && empty($_POST['_action'])) {
            update_option('giga_messenger_bots', $new_setting);
        }
        
        if ( ! empty($new_setting['page_id'])) {
            Instance::updateOrCreate([
                'id' => $new_setting['page_id'],
            ], [
                'name'   => isset($new_setting['page_name']) ? esc_html($new_setting['page_name']) : esc_html($new_setting['page_id']),
                'meta'   => $new_setting,
                'status' => 'running',
            ]);
        }
        
        // Convert whitelisted domains to array before passing to Giga AI
        $new_setting_whitelisted_domains = '';
        if ( ! empty($new_setting['whitelisted_domains']) && ! is_array($new_setting['whitelisted_domains'])) {
            // Keep the old text value to check later
            $new_setting_whitelisted_domains = $new_setting['whitelisted_domains'];
            $new_setting['whitelisted_domains'] = preg_split('/\r\n|[\r\n]/', $new_setting['whitelisted_domains']);
        }
        
        if (empty($new_setting['whitelisted_domains']) || ! is_array($new_setting['whitelisted_domains'])) {
            $new_setting['whitelisted_domains'] = [];
        }
        
        array_unshift($new_setting['whitelisted_domains'], get_site_url());
        
        // Set bot to the new settings
        \GigaAI\Core\Config::set($new_setting);
        
        // Switch back to text instead of array. This helps check with old value to update or not later.
        $new_setting['whitelisted_domains'] = $new_setting_whitelisted_domains;
        
        $this->updateMessengerProfile();
        
        // Update Payloads Array
        giga_update_payload_cache($new_setting['persistent_menu']);
        
        do_action('giga_settings_saved');
    }
    
    private function updateMessengerProfile()
    {
        $messages = \GigaAI\Http\MessengerProfile::updateMessengerProfile();
        
        // Printing Messages
        foreach ($messages as $level => $message) {
            if (isset($message->error)) {
                Session::flash([
                    'status'  => 'error',
                    'message' => $message->error->message,
                ]);
                
                giga_refresh();
            }
        }
    }
    
    private function deleteInstance($id)
    {
        Instance::destroy($id);
        
        Session::flash([
            'status'  => 'success',
            'message' => 'Page deleted!',
        ]);
        
        wp_safe_redirect(admin_url('admin.php?page=giga'));
        exit;
    }
    
    /**
     * Check if multipage is enabled or not
     *
     * @return bool
     */
    private function is_multipage()
    {
        return (isset($this->settings['multipage']) && $this->settings['multipage']);
    }
    
    /**
     * Safe print the setting output
     */
    private function sanitized_field_value($field)
    {
        $field_value = isset($this->settings[$field]) ? $this->settings[$field] : '';
        
        echo esc_attr($field_value);
    }
    
    public function settings()
    {
        ?>
        <div class="wrap giga" id="bot-settings">
            <?php
            $this->title = __('Settings', 'giga-messenger-bots');
            
            if (giga_is_multipage()) {
                if ( ! empty($this->settings['page_id'])) {
                    $this->title = __('PAGE ID:', 'giga-messenger-bots') . ' <span class="small">' . $this->settings['page_id'] . '</span>';
                }
                if ( ! empty($this->settings['page_name'])) {
                    $this->title = __('PAGE:', 'giga-messenger-bots') . ' <span class="small">' . $this->settings['page_name'] . '</span>';
                }
                if (isset($_GET['_action']) && $_GET['_action'] === 'create') {
                    $this->title = __('Create New Page', 'giga-messenger-bots');
                }
                
                Component::make('instances-selector', [
                    'title' => $this->title,
                ]);
            } else { ?>
                <h1><?php echo $this->title ?></h1>
            <?php } ?>

            <div class="clearfix"></div>

            <h2 class="nav-tab-wrapper wp-clearfix">
                <?php foreach ($this->tabs as $url => $title) : ?>
                    <a href="<?php echo add_query_arg('tab', $url); ?>"
                       class="nav-tab <?php echo ($this->current_tab === $url) ? 'nav-tab-active' : '' ?>">
                        <?php echo $title ?>
                    </a>
                <?php endforeach; ?>
            </h2>

            <div class="clearfix"></div>
            
            <?php Component::make('admin-message'); ?>

            <form action="options.php" method="post" id="poststuff" ng-app="Bot">
                <?php settings_fields('giga_messenger_bots'); ?>

                <div class="settings-tab-content">
                    <table class="form-table">
                        <tbody>
                        <?php require_once GIGA_INC_DIR . 'settings/_partials/' . $this->current_tab . '.php'; ?>
                        </tbody>
                    </table>

                    <input type="hidden" name="_page_now" value="giga">
                    <input type="hidden" name="_action"
                           value="<?php echo isset($_GET['_action']) ? $_GET['_action'] : ''; ?>">
                    <input type="hidden" name="_instance_id"
                           value="<?php echo isset($_GET['_instance_id']) ? $_GET['_instance_id'] : ''; ?>">
                    <input type="hidden" name="_setting_tab" value="<?php echo $this->current_tab ?>">
                    <?php
                    wp_nonce_field('giga_settings_nonce', 'giga_settings_nonce');
                    submit_button();
                    ?>
                </div>
            </form>
        </div>
        <?php
    }
}

new Settings;