<?php

/**
 * Plugin Name:       Doobert Chatbot
 * Plugin URI:        https://doobert.com
 * Description:       Doobert’s Chatbot answers questions based on YOUR site’s pages and posts.
 * Version:           1.7
 * Requires at least: 6.2
 * Requires PHP: 7.4
 * Author:            doobert
 * Author URI:        https://doobert.com/
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       doobert-chatbot
 * Domain Path:       /languages
 *
 * @package           Doobert_Chatbot
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

if (!defined('DOOBERT_CHAPI_URL')) {
    define('DOOBERT_CHAPI_URL', plugin_dir_url(__FILE__));
}

if (!defined('DOOBERT_CHAPI_PLUGIN_DIR')) {
    define('DOOBERT_CHAPI_PLUGIN_DIR', plugin_dir_path(__FILE__));
}
/**
 * Set the hyperlink color using the <a> tag.
 */
if (!defined('HYPER_LINK')) {
    define('HYPER_LINK', 'style=color:#56aeff;');
}

/**
 * Define the Doobert API base URL used for all server-side requests.
 */

if (!defined('DOOBERT_API_BASE_URL')) {
    define('DOOBERT_API_BASE_URL', 'https://app.doobert.com/api/v1/' );
}
/**
 *  Petcolove api base url
 */
if (!defined('PETCOLOVE_LOCATION')) {
    define('PETCOLOVE_LOCATION', 'https://petcolove.org/lost/search-results/' );
}
/**
 * Load plugin text domain for translation
 */
add_action('init', function () {
    load_plugin_textdomain('doobert-chatbot', false, dirname(plugin_basename(__FILE__)) . '/languages');
});

/**
 * Include necessary files
 */
include_once DOOBERT_CHAPI_PLUGIN_DIR . 'doobert-chatbot-api-methods.php';
include_once DOOBERT_CHAPI_PLUGIN_DIR . 'admin/doobert-chatbot-with-api-admin.php';
include_once DOOBERT_CHAPI_PLUGIN_DIR . 'front/doobert-chatbot-with-api-front.php';
include_once DOOBERT_CHAPI_PLUGIN_DIR . 'doobert-chatbot-api-handle.php';

/**
 * Register plugin activation hook
 */
register_activation_hook(__FILE__, 'doobert_chatbot_on_activation');

if (!function_exists('doobert_chatbot_on_activation')) {

    function doobert_chatbot_on_activation() {

        $settings = get_option('doobert-chatbot-custom-settings');
        if (empty($settings)) {
            $array = array(
                'enable_doobert' => 'enable',
                'display_pages' => '',
                'def_msg_to_show' => 'Hello, how can I help you today?',
                'def_options_to_show' => 'Foster a Dog;Foster a Cat;Donate;Volunteer',
                'contact_us_page' => ''
            );
            update_option('doobert-chatbot-custom-settings', $array);
        }

        global $wpdb;
        $table_name = $wpdb->prefix . 'doobert_chatbot_history';

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name));
        if (!$table_exists) {
            $sql = "CREATE TABLE $table_name (
                id INT NOT NULL AUTO_INCREMENT,
                question LONGTEXT,
                answer LONGTEXT,
                datatime VARCHAR(50),
                meta_data VARCHAR(255),
                PRIMARY KEY (id)
            )";
            dbDelta($sql);
        }

        $column_exists = $wpdb->get_var($wpdb->prepare(
                        "SELECT COLUMN_NAME 
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE table_name = %s AND column_name = %s 
            AND table_schema = %s",
                        $table_name, 'meta_data', DB_NAME
        ));
        if (!$column_exists) {
            $wpdb->query("ALTER TABLE $table_name ADD meta_data VARCHAR(255)");
        }

        $table_name = $wpdb->prefix . 'doobert_translations_data';

        $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name));
        if (!$table_exists) {
            $sql = "CREATE TABLE $table_name (
                id INT(11) NOT NULL AUTO_INCREMENT,
                language VARCHAR(255) NOT NULL,
                translations LONGTEXT,
                status VARCHAR(10) NOT NULL,
                code VARCHAR(100) NOT NULL,
                PRIMARY KEY (id)
            ) ENGINE=InnoDB;";
            dbDelta($sql);
        }
        // $table_name = $wpdb->prefix . 'petcolove_token';
        // $table_exists = $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name));
        // if (!$table_exists) {
        //     $sql = "CREATE TABLE $table_name (
        //         id INT(11) NOT NULL AUTO_INCREMENT,
        //         access_token VARCHAR(1000) DEFAULT NULL,
        //         expire_at DATETIME DEFAULT NULL,
        //         PRIMARY KEY (id)
        //     ) ENGINE=InnoDB;";
        //     dbDelta($sql);
        // }

        if (!wp_next_scheduled('doobertbottest_daily_cron_hook')) {
            wp_schedule_event(time(), 'daily', 'doobertbottest_daily_cron_hook');
        }
    }

}


/**
 * Plugin daily cron function
 */
if (!function_exists('doobertbottest_daily_cron_function')) {

    function doobertbottest_daily_cron_function() {
        global $wpdb;
        $doobert_api_token_value = get_option('doobert_api_token_value');
        if (!empty($doobert_api_token_value)) {
            $doobert_api_token_value = openssl_decrypt($doobert_api_token_value, 'aes-256-cbc', 'doobert', 0, 16);
        }
        if (!empty($doobert_api_token_value)) {

            $table_name = $wpdb->prefix . 'doobert_chatbot_history';
            $results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}doobert_chatbot_history");
            if (!empty($results)) {
                $data = array();
                foreach ($results as $key => $res) {
                    $question = $res->question;
                    $answer = $res->answer;
                    $datetime = $res->datatime;
                    $meta_data = isset($res->meta_data) ? $res->meta_data : '';
                    $version = '';
                    $is_quick_response = 0;
                    if (!empty($meta_data)) {
                        $meta_data = maybe_unserialize($meta_data);
                        $version = isset($meta_data['version']) ? $meta_data['version'] : '';
                        if (!empty($version)) {
                            $version = 'v ' . $version;
                        }
                        $is_quick_response = isset($meta_data['is_quick_response']) ? $meta_data['is_quick_response'] : '';
                    }

                    $data["data[$key][user_question]"] = $question;
                    $data["data[$key][chat_response]"] = $answer;
                    $data["data[$key][chatbot_version]"] = $version;    
                    $data["data[$key][is_quick_response]"] = $is_quick_response;
                    $data["data[$key][date_time]"] = $datetime;
                }
                $data['website'] = site_url();

                $request_args = array(
                    'body' => $data,
                    'headers' => array(
                        'Authorization' => 'Bearer ' . $doobert_api_token_value,
                    ),
                );
                $response = wp_remote_post('https://app.doobert.com/api/v1/plugin/log-chat', $request_args);
                if (is_wp_error($response)) {
                    
                } else {
                    $result = json_decode(wp_remote_retrieve_body($response), true);
                    if (isset($result['status']) && $result['status'] == 1) {
                        $wpdb->query("TRUNCATE TABLE {$wpdb->prefix}doobert_chatbot_history");
                    }
                }
            }
        }
    }

}



/**
 * Add settings link on plugin activation
 */
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'doobert_settings_link_doobert');

if (!function_exists('doobert_settings_link_doobert')) {

    function doobert_settings_link_doobert(array $links) {
        $url = get_admin_url() . "?page=doobert-chatbot-settings";
        $settings_link = '<a href="' . $url . '">' . __('Settings', 'doobert-chatbot') . '</a>';
        $links[] = $settings_link;
        $link2 = '<a target="_blank" href="https://app.doobert.com/chatbot-premium-plans">Upgrade to Premium</a>';
        $links[] = $link2;
        return $links;
    }

}

/**
 * Sends installation data (e.g., plugin version) 
 * to a remote API endpoint when the plugin is activated.
*/
add_action('doobertbottest_daily_cron_hook', 'doobertbottest_daily_cron_function');
if (!function_exists('wp_chatbot_installation')) {
    function wp_chatbot_installation() {
        if(!function_exists( 'get_plugin_data' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
        }
        // Get version
        $plugin_data = get_plugin_data( __FILE__ );
        $version = isset( $plugin_data['Version'] ) ? $plugin_data['Version'] : '1.4';
        $api_url=DOOBERT_API_BASE_URL. 'wp_chatbot_installation';
        $data = [
            'version' => $version,
            'site_url' => get_site_url(),
        ];
        $response = wp_remote_post($api_url, [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body'    => json_encode($data),
            'timeout' => 10,
        ]);
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            return ['error' => $error_message];
        }
        $body = wp_remote_retrieve_body($response);
        if (is_wp_error($response)) {
            return ['error' => $response->get_error_message()];
        }
        return wp_remote_retrieve_body($response);
    }
}
register_activation_hook( __FILE__, 'wp_chatbot_installation' );
