<?php
/**
 * Plugin Name: GSheetConnector for JetFormBuilder
 * Plugin URI: https://wordpress.org/plugins/gsheetconnector-for-jetform
 * Description: Send your Jet Forms data to your Google Sheets.
 * Version: 1.0.4
 * Author: GSheetConnector
 * Author URI: https://www.gsheetconnector.com/
 * License:      GPLv2
 * License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: gsheetconnector-for-jetform
 * Requires Plugins: jetformbuilder
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

if (!function_exists('is_plugin_active')) {
    require_once ABSPATH . 'wp-admin/includes/plugin.php';
}

if (is_plugin_active('gsheetconnector-for-jetform-pro/gsheetconnector-for-jetform-pro.php')) {
    return;
}

// Declare some global constants

define('GSHFJF_JETFORM_CONNECTOR_VERSION', '1.0.4');
define('GSHFJF_JETFORM_CONNECTOR_DB_VERSION', '1.0.4');
define('GSHFJF_JETFORM_CONNECTOR_ROOT', __DIR__);
define('GSHFJF_JETFORM_CONNECTOR_BASE_NAME', plugin_basename(__FILE__));
define('GSHFJF_JETFORM_CONNECTOR_PATH', plugin_dir_path(__FILE__));
define('GSHFJF_JETFORM_CONNECTOR_URL', plugins_url('/', __FILE__));
define('GSHFJF_JETFORM_CONNECTOR_AUTH_URL', 'https://oauth.gsheetconnector.com/auth-api.php');
define('GSHFJF_JETFORM_CONNECTOR_AUTH_REDIRECT_URI', admin_url('edit.php?post_type=jet-form-builder&page=jetform-google-sheet-config'));
define('GSHFJF_JETFORM_CONNECTOR_AUTH_PLUGIN_NAME', 'cf7gsheetconnector');
define('GSHFJF_JETFORM_CONNECTOR_API_URL', 'https://oauth.gsheetconnector.com/api-cred-old-api.php');
// define('GSHFJF_JETFORM_CONNECTOR_VERSION_API_URL', 'https://oauth.gsheetconnector.com/api-cred.php');

if (!class_exists('GSHFJF_JetForm_Connector_Utility')) {
    include GSHFJF_JETFORM_CONNECTOR_ROOT . '/includes/class-gs-utility.php';
}

// Include Library Files
// require_once GSHFJF_JETFORM_CONNECTOR_ROOT . '/lib/vendor/autoload.php';
include_once GSHFJF_JETFORM_CONNECTOR_ROOT . '/lib/google-sheets.php';
require_once GSHFJF_JETFORM_CONNECTOR_ROOT . '/includes/class-gsc-error-logs.php';

class GSHFJF_JetForm_Connector_Init
{

    /**
     * Constructor to register hooks and initialize plugin functionality.
     *
     * - Handles activation, deactivation, and uninstall hooks
     * - Adds admin menu and plugin action links
     * - Loads scripts, styles, and necessary classes
     * - Sets up integration with Jet Forms submissions
     *
     * @access public
     * @since 1.0.0 Initial version
     */

    public function __construct()
    {
        // Run on plugin activation
        register_activation_hook(__FILE__, array($this, 'gshfjf_jetform_connector_activate'));

        // Run on plugin deactivation
        register_deactivation_hook(__FILE__, array($this, 'gshfjf_jetform_connector_deactivate'));

        // Run on plugin uninstall
        register_uninstall_hook(__FILE__, array('GSHFJF_JetForm_Connector_Init', 'gshfjf_jetform_connector_uninstall'));

        // Run upgrade tasks
        add_action('admin_init', array($this, 'gshfjf_run_on_upgrade'));

        // Check if Jet Forms plugin is active
        add_action('admin_init', array($this, 'gshfjf_validate_parent_plugin_exists'));

        // Add custom action links (like settings) on plugin page
        add_filter('plugin_action_links_' . GSHFJF_JETFORM_CONNECTOR_BASE_NAME, array($this, 'gshfjf_connector_plugin_action_links'));

        // Add admin menu page
        add_action('admin_menu', array($this, 'gshfjf_add_admin_menu'), 99);

        // Load CSS and JS files
        add_action('init', array($this, 'gshfjf_load_css_and_js_files'));

        // Load required PHP classes
        add_action('init', array($this, 'gshfjf_load_all_classes'));

        // Send form data to Google Sheets on submission
        add_action('jet-form-builder/form-handler/after-send', [$this, 'gshfjf_send_jetform_to_google_sheets'], 10, 1);

        // AJAX call to clear debug logs
        add_action('wp_ajax_gshfjf_clear_logs', array($this, 'gshfjf_clear_logs'));
    }

    /**
     * If Jet Form  plugin is not installed or activated then throw the error
     *
     * @access public
     * @return mixed error_message, an array containing the error message
     *
     * @since 1.0.0 initial version
     */

    public function gshfjf_jet_form_missing_notice()
    {
        $plugin_error = GSHFJF_JetForm_Connector_Utility::instance()->admin_notice(array(
            'type' => 'error',
            'message' => __('Google Sheet Connector Add-on requires JetFormBuiler plugin to be installed and activated.', 'gsheetconnector-for-jetform')
        ));
        echo wp_kses_post($plugin_error);
    }

    /**
     * Validate parent Plugin Jet Form exist and activated
     * @access public
     * @since 1.0.0
     */

    public function gshfjf_validate_parent_plugin_exists()
    {
        $plugin = plugin_basename(__FILE__);
        if ((!is_plugin_active('jetformbuilder/jet-form-builder.php')) || (!file_exists(plugin_dir_path(__DIR__) . 'jetformbuilder/jet-form-builder.php'))) {
            add_action('admin_notices', array($this, 'gshfjf_jet_form_missing_notice'));
            add_action('network_admin_notices', array($this, 'gshfjf_jet_form_missing_notice'));
            deactivate_plugins($plugin);
            if (isset($_GET['activate'])) {

                if (
                    isset($_GET['_wpnonce']) &&
                    wp_verify_nonce(
                        sanitize_text_field(wp_unslash($_GET['_wpnonce'])),
                        'activate-plugin_' . $plugin
                    )
                ) {
                    unset($_GET['activate']);
                }
            }
        }
    }

    /**
     * Add custom link for the plugin beside activate/deactivate links
     * @param array $links Array of links to display below our plugin listing.
     * @return array Amended array of links.    * 
     * @since 1.0.0
     */

    public function gshfjf_connector_plugin_action_links($links)
    {
        // We shouldn't encourage editing our plugin directly.
        unset($links['edit']);
        // Add our custom links to the returned array value.
        return array_merge(
            array(
                '<a href="' . admin_url('edit.php?post_type=jet-form-builder&page=jetform-google-sheet-config&tab=integration') . '">' . __('Settings', 'gsheetconnector-for-jetform') . '</a>',
            ),
            $links
        );
    }

    /**
     * Send Jet Forms form submission data to connected Google Sheets feed.
     *
     * This function:
     *  - Retrieves the latest submission data from Jet Forms.
     *  - Flattens and formats field data.
     *  - Adds additional metadata (e.g. IP, user info, time).
     *  - Maps field names to user-friendly labels.
     *  - Sends the structured data to the appropriate connected Google Sheet tabs.
     *
     * @param int   $entry_id  The ID of the Jet Forms entry.
     * @param array $formData  The form data submitted.
     * @param object $form     The Jet Forms form object.
     */

    public function gshfjf_send_jetform_to_google_sheets($handler)
    {
        global $wpdb;

        try {

            // NONCE CHECK

            if (!isset($_POST['_wpnonce'])) {
                return;
            }

            $nonce = sanitize_text_field(wp_unslash($_POST['_wpnonce']));

            if (wp_verify_nonce($nonce, 'jet-form-builder')) {
                return;
            }

            // FORM ID
            $form_id = 0;

            if (!empty($handler->form_id)) {
                $form_id = $handler->form_id;
            } else {
                return;
            }

            $records_table = $wpdb->prefix . 'jet_fb_records';


            $record = $wpdb->get_row(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}jet_fb_records WHERE form_id = %d ORDER BY id DESC LIMIT 1",
                    $form_id
                ),
                ARRAY_A
            );

            if (empty($record)) {
                return;
            }

            $record_id = $record['id'];
            $content_id = $record['from_content_id'];
            // $form_id = !empty($content_id) ? $content_id : $form_id;

            $fields = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}jet_fb_records_fields WHERE record_id = %d",
                    $record_id
                ),
                ARRAY_A
            );

            $flat_data = [];

            foreach ($fields as $field) {

                $label = $field['field_name'];

                if (!empty($field['field_attrs'])) {
                    $attrs = json_decode($field['field_attrs'], true);
                    if (!empty($attrs['label'])) {
                        $label = $attrs['label'];
                    }
                }

                $value = wp_strip_all_tags($field['field_value']);
                $flat_data[$label] = $value;
            }

            $file_url = '';

            if (!empty($_FILES)) {

                $upload_dir = wp_upload_dir();
                $base_dir   = $upload_dir['basedir'] . '/jet-form-builder/';

                foreach ($_FILES as $file) {

                    if (empty($file['name'])) {
                        continue;
                    }

                    $filename = sanitize_file_name($file['name']);
                    $search_name = pathinfo($filename, PATHINFO_FILENAME);
                    $search_name = strtolower(str_replace([' ', '_'], '-', $search_name));

                    $iterator = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($base_dir, RecursiveDirectoryIterator::SKIP_DOTS)
                    );

                    foreach ($iterator as $f) {

                        if (!$f->isFile()) {
                            continue;
                        }

                        $current = sanitize_file_name($f->getFilename());
                        $current_name = strtolower(pathinfo($current, PATHINFO_FILENAME));

                        if (
                            $current_name === $search_name ||
                            str_starts_with($current_name, $search_name . '-')
                        ) {

                            $relative_path = str_replace($upload_dir['basedir'] . '/', '', $f->getPathname());
                            $relative_path = str_replace('\\', '/', $relative_path);
                            $file_url = $upload_dir['baseurl'] . '/' . $relative_path;
                            break 2;
                        }
                    }
                }
            }

            if (!empty($file_url)) {
                $flat_data['File Upload'] = $file_url;
                $flat_data['file_upload'] = $file_url;
            }

            $flat_data['Submission ID'] = $record['id'];
            $form_title = get_the_title($form_id);
            $form_title = trim((string) $form_title);

            if ($form_title === '') {
                $form_title = 'Untitled Form (#' . $content_id . ')';
            }

            $flat_data['Form'] = $form_title;
            $flat_data['Referrer'] = $record['referrer'];
            $flat_data['Status'] = $record['status'];

            $user = get_user_by('id', $record['user_id']);
            $flat_data['Submitted By'] = $user ? $user->user_login : '';

            $ip_address = $record['ip_address'];

            if (empty($ip_address)) {
                if (isset($_SERVER['HTTP_CLIENT_IP'])) {
                    $ip_address = sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
                } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    $ip_address = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
                } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                    $ip_address = sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
                } else {
                    $ip_address = '';
                }
            }

            $flat_data['Ip Address'] = $ip_address;

            $user_agent = isset($record['user_agent'])
                ? sanitize_text_field($record['user_agent'])
                : (isset($_SERVER['HTTP_USER_AGENT'])
                    ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']))
                    : ''
                );
            $flat_data['User Agent'] = $user_agent;

            if (!empty($ip_address) || !empty($user_agent)) {
                $wpdb->update(
                    $records_table,
                    [
                        'ip_address' => $ip_address,
                        'user_agent' => $user_agent,
                    ],
                    ['id' => $record_id],
                    ['%s', '%s'],
                    ['%d']
                );
            }

            $flat_data['Created'] = "'" . $record['created_at'];
            $feeds = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}gshfjf_jetform_db_settings WHERE form_id = %d AND status = %d",
                    $handler->form_id,
                    1
                )
            );

            if (empty($feeds) && $content_id && $content_id !== $form_id) {
                $feeds = $wpdb->get_results(
                    $wpdb->prepare(
                        "SELECT * FROM {$wpdb->prefix}gshfjf_jetform_db_settings WHERE form_id = %d AND status = %d",
                        $content_id,
                        1
                    )
                );

                if (!empty($feeds)) {
                    $form_id = $content_id;
                }
            }

            foreach ($feeds as $feed) {
                $spreadsheetData = maybe_unserialize($feed->sheet_details);
                $spreadsheet_id = $spreadsheetData['sheet-id'] ?? '';
                $tab_name = $spreadsheetData['sheet-tab-name'] ?? '';
                $tab_id = $spreadsheetData['tab-id'] ?? '';

                $doc = new GSHFJF_JetForm_GoogleSheet();
                $doc->setSpreadsheetId($spreadsheet_id);
                $doc->setWorkTabId($tab_id);

                $doc->add_row_feed(
                    $spreadsheet_id,
                    $tab_name,
                    $flat_data
                );
            }
        } catch (Exception $e) {

            GSHFJF_JetForm_Connector_Utility::gshfjf_debug_log(
                'JetForms GSheetConnector Error: ' . $e->getMessage()
            );
        }
    }

    /**
     * Register the Google Sheet submenu under the Jet Forms menu in the WordPress admin.
     * @since 1.0.0
     */

    public function gshfjf_add_admin_menu()
    {
        $current_role = GSHFJF_JetForm_Connector_Utility::instance()->get_current_user_role();

        if ($current_role === "administrator" || current_user_can('manage_shop_settings')) {

            add_submenu_page(
                'edit.php?post_type=jet-form-builder',
                __('Google Sheet', 'gsheetconnector-for-jetform'),
                __('Google Sheet', 'gsheetconnector-for-jetform'),
                'manage_options',
                'jetform-google-sheet-config',
                array($this, 'gshfjf_google_sheet_configuration')
            );
        }
    }

    /**
     * Render the Google Sheet configuration page.
     * Loads the settings template from the includes/pages directory.
     * @since 1.0.0
     */

    public function gshfjf_google_sheet_configuration()
    {
        include(GSHFJF_JETFORM_CONNECTOR_PATH . "includes/pages/google-sheet-settings.php");
    }

    /**
     * Called on activation.
     * Creates the site_options (required for all the sites in a multi-site setup)
     * If the current version doesn't match the new version, runs the upgrade
     *
     * @since 1.0.0
     */

    private function run_on_activation()
    {
        // Save plugin version.
        $plugin_options = get_site_option('gshfjf_google_sheet_info');

        if (false === $plugin_options) {
            $gshfjf_google_sheet_info = array(
                'version' => GSHFJF_JETFORM_CONNECTOR_VERSION,
                'db_version' => GSHFJF_JETFORM_CONNECTOR_DB_VERSION,
            );
            update_site_option('gshfjf_google_sheet_info', $gshfjf_google_sheet_info);
        } elseif (GSHFJF_JETFORM_CONNECTOR_DB_VERSION != $plugin_options['version']) {
            $this->gshfjf_run_on_upgrade();
        }

        // Fetch and save the API credentails.
        GSHFJF_JetForm_Connector_Utility::instance()->save_api_credentials();
        $this->add_admin_database();
    }

    /**
     * Do things on plugin activation
     *
     * @since 1.0.0
     */

    public function gshfjf_jetform_connector_activate($network_wide)
    {
        global $wpdb;
        $this->run_on_activation();
        if (function_exists('is_multisite') && is_multisite()) {
            // check if it is a network activation - if so, run the activation function for each blog id
            if ($network_wide) {
                // Get all blog ids
                $blogids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->base_prefix}blogs");
                foreach ($blogids as $blog_id) {
                    switch_to_blog($blog_id);
                    $this->run_for_site();
                    restore_current_blog();
                }
                return;
            }
        }
        // for non-network sites only
        $this->run_for_site();
    }

    /**
     * Called on activation.
     * Creates the options and DB (required by per site)
     *
     * @since 1.0.0
     */

    private function run_for_site()
    {
        try {
            if (!get_option('gshfjf_jetform_token')) {
                update_option('gshfjf_jetform_token', '');
            }
            if (!get_option('gshfjf_jetform_verify')) {
                update_option('gshfjf_jetform_verify', '');
            }
            if (!get_option('gshfjf_jetform_access_code')) {
                update_option('gshfjf_jetform_access_code', '');
            }
            if (!get_option('gshfjf_jetform_tab_roles_setting')) {
                update_option("gshfjf_jetform_tab_roles_setting", array());
            }
        } catch (Exception $e) {
            GSHFJF_JetForm_Connector_Utility::gshfjf_debug_log('Something Wrong : - ' . $e->getMessage());
        }
    }

    /**
     * Deactivate the plugin
     *
     * @since 1.0.0
     */

    public function gshfjf_jetform_connector_deactivate($network_wide)
    {
        // register_deactivation_hook(__FILE__, 'clear_cron_job');
    }

    /**
     *  Runs on plugin uninstall.
     *  a static class method or function can be used in an uninstall hook
     *
     *  @since 1.0.0
     */

    public static function gshfjf_jetform_connector_uninstall()
    {
        global $wpdb;
        // self::run_on_uninstall();
        if (function_exists('is_multisite') && is_multisite()) {
            // Get all blog ids; foreach of them call the uninstall procedure
            $blog_ids = $wpdb->get_col("SELECT blog_id FROM {$wpdb->base_prefix}blogs");

            // Get all blog ids; foreach them and call the install procedure on each of them if the plugin table is found
            foreach ($blog_ids as $blog_id) {
                switch_to_blog($blog_id);
                GSHFJF_JetForm_Connector_Init::delete_for_site();
                restore_current_blog();
            }
            return;
        }
        GSHFJF_JetForm_Connector_Init::delete_for_site();
    }

    /**
     * Called on uninstall - deletes site_options
     *
     * @since 1.0.0
     */

    private static function run_on_uninstall()
    {
        if (!defined('ABSPATH') && !defined('WP_UNINSTALL_PLUGIN')) {
            exit();
        }

        delete_site_option('gshfjf_google_sheet_info');
    }

    /**
     * Called on uninstall - deletes site specific options
     *
     * @since 1.0.0
     */

    private static function delete_for_site()
    {

        try {
            $saved_value = get_option('gshfjf_uninstall_setting');
            if ($saved_value === '1') {

                // db version
                delete_site_option('gshfjf_google_sheet_info');

                // Method Save
                delete_option('gshfjf_jetform_manual_setting');
                delete_option('gshfjf_sheet_fetch_date');
                delete_option('gshfjf_jetform_tab_roles_setting');

                // Auto Method
                delete_option('gshfjf_jetform_access_code');
                delete_option('gshfjf_jetform_verify');
                delete_option('gshfjf_jetform_token');
                delete_option('gshfjf_is_new_client_secret_free');
                delete_option('gshfjf_jetform_email_account');

                // Delete API Credentials   
                delete_option('gshfjf_jetform_free_api_creds');
                delete_site_option('gshfjf_jetform_free_api_creds');

                // Drop the table if it exists
                global $wpdb;

                $wpdb->query(
                    "DROP TABLE IF EXISTS {$wpdb->prefix}gshfjf_jetform_db_settings"
                );
            }
        } catch (Exception $e) {
            GSHFJF_JetForm_Connector_Utility::gshfjf_debug_log('Something Wrong : - ' . $e->getMessage());
        }
    }

    /**
     * Google Sheets page action.
     * This method is called when the menu item "Google Sheets" is clicked.
     * @since 1.0.0
     */

    public function gshfjf_load_css_and_js_files()
    {
        add_action('admin_print_styles', array($this, 'add_css_files'));
        add_action('admin_print_scripts', array($this, 'add_js_files'));
    }

    /**
     * Enqueue admin JavaScript files and pass localized variables.
     *
     * Loads main and pro extension scripts, and passes AJAX URL and nonce.
     *
     * @access public
     * @since 1.0.0 Initial version
     */

    public function add_js_files()
    {
        if (is_admin() && isset($_SERVER['REQUEST_URI'])) {

            $request_uri = sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']));

            if (isset($_REQUEST['page']) && preg_match_all('/page=wpcf7-new(.*)|page=jetform-google-sheet-config(.*)|page=wpcf7(.*)/', $request_uri, $matches)) {

                wp_enqueue_script(
                    'gshfjf-jetform-connector-js-free',
                    GSHFJF_JETFORM_CONNECTOR_URL . 'assets/js/gs-connector.js',
                    array('jquery'),
                    GSHFJF_JETFORM_CONNECTOR_VERSION,
                    true
                );
                wp_enqueue_script(
                    'gshfjf-jetform-extensions-js-free',
                    GSHFJF_JETFORM_CONNECTOR_URL . 'assets/js/gs-connector-extensions.js',
                    array('jquery'),
                    GSHFJF_JETFORM_CONNECTOR_VERSION,
                    true
                );
            }
        }

        wp_localize_script('gshfjf-jetform-connector-js-free', 'gshfjf_vars', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('gshfjf-ajax-nonce')
        ]);

        if (is_admin()) {
            wp_enqueue_script(
                'gsc-connector-systeminfo-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/js/gs-connector-systeminfo.js',
                array(),
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                true
            );
        }
    }

    /**
     * Enqueue css
     *
     * @since 1.0.0
     */

    public function add_css_files()
    {
        if (is_admin() && (isset($_GET['page']) && ($_GET['page'] == 'jetform-google-sheet-config'))) {
            wp_enqueue_style(
                'gshfjf_jetform-css-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/gs-jetform.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-header-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/header.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-footer-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/footer.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-extra-style-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/extra-style.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-global-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/global.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-responsive-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/responsive.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-pro-feature',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/pro-feature.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );

            wp_enqueue_style(
                'gsc-connector-font-awesome-free',
                GSHFJF_JETFORM_CONNECTOR_URL . 'assets/css/fontawesome.css',
                [],
                GSHFJF_JETFORM_CONNECTOR_VERSION,
                'all'
            );
        }
    }

    /**
     * 
     * Load all the classes - as part of init action hook
     *
     * @since 1.0.0
     */

    public function gshfjf_load_all_classes()
    {
        if (!class_exists('GSHFJF_JetForm_Integration_Service')) {
            include GSHFJF_JETFORM_CONNECTOR_PATH . 'includes/pages/integration/class-jetform-integration-service.php';
        }
        if (!class_exists('GSHFJF_JetForm_Feed_Service')) {
            include GSHFJF_JETFORM_CONNECTOR_PATH . 'includes/pages/feed/gs-feed-service.php';
        }
        if (!class_exists('GSHFJF_JetForm_Role_Settings')) {
            include(GSHFJF_JETFORM_CONNECTOR_PATH . 'includes/pages/gs-jetform-role-setting.php');
        }
        if (!class_exists('GSHFJF_JetForm_Extensions')) {
            include(GSHFJF_JETFORM_CONNECTOR_PATH . 'includes/pages/extensions/gs-jetform-extension-service.php');
        }
    }

    /**
     * called on upgrade.
     * checks the current version and applies the necessary upgrades from that version onwards
     * @since 1.0.0
     */

    public function gshfjf_run_on_upgrade() {}

    /**
     * Function for creating database table
     * @since 1.0.0
     */

    public function add_admin_database()
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'gshfjf_jetform_db_settings';
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE $table_name (
        id BIGINT(20) NOT NULL AUTO_INCREMENT,
        form_id BIGINT(20) NOT NULL,
        feed_name VARCHAR(500) NOT NULL,
        sheet_details LONGTEXT NULL,
        sheet_data_feed LONGTEXT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        status TINYINT(1) NOT NULL DEFAULT 1,
        PRIMARY KEY (id)
        ) ENGINE=InnoDB $charset_collate;";

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

        //  global $wpdb;
        $table = $wpdb->prefix . 'gshfjf_error_logs';
        $charset = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE {$table} (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        error_id VARCHAR(191) NOT NULL,
        code INT NOT NULL,
        message TEXT NOT NULL,
        details LONGTEXT NULL,
        created_at DATETIME NOT NULL,
        PRIMARY KEY (id),
        KEY error_id (error_id),
        KEY code (code)
    ) {$charset};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
        $table = $wpdb->prefix . 'gshfjf_jetform_activity_log';

        $charset = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            date DATETIME NOT NULL,
            form_id BIGINT NOT NULL,
            form_name VARCHAR(255),
            entry_id BIGINT,
            status VARCHAR(20),
            error_type VARCHAR(50),
            message TEXT,
            sheet_id VARCHAR(255),
            user_id BIGINT,
            ip_address VARCHAR(45),
            PRIMARY KEY (id)
        ) $charset;";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    /**
     * 
     * System information.
     * @since 1.0.0
     */

    public function gshfjf_system_info()
    {

        global $wpdb;

        // Get WordPress version.
        $wp_version = get_bloginfo('version');

        // Get theme info.
        $theme_data = wp_get_theme();
        $theme_name_version = $theme_data->get('Name') . ' ' . $theme_data->get('Version');
        $parent_theme = $theme_data->get('Template');

        if (!empty($parent_theme)) {
            $parent_theme_data = wp_get_theme($parent_theme);
            $parent_theme_name_version = $parent_theme_data->get('Name') . ' ' . $parent_theme_data->get('Version');
        } else {
            $parent_theme_name_version = 'N/A';
        }

        // Check plugin version and subscription plan.
        $plugin_version = defined('GSHFJF_JETFORM_CONNECTOR_VERSION') ? GSHFJF_JETFORM_CONNECTOR_VERSION : 'N/A';
        $plugin_data = get_plugin_data(__FILE__);
        $plugin_name = $plugin_data['Name'];
        $subscription_plan = 'FREE';

        $api_token_auto = get_option('gshfjf_jetform_token');
        $auth_method = get_option('gshfjf_jetform_manual_setting');
        $auth = "";


        if ($auth_method === '0') {
            $gshfjf_google_sheet_auto = new GSHFJF_JetForm_GoogleSheet();
            $email_account_auto = $gshfjf_google_sheet_auto->gsheet_print_google_account_email();
            $connected_email = !empty($email_account_auto) ? esc_html($email_account_auto) : 'Not Connected';
            $auth = 'Authenticated Using Existing Method';
        } else {
            // Auto authentication is the  method available.
            $connected_email = 'Not Connected';
            $auth = 'No Method';
        }

        // Check Google Permission.
        $gsc_verify_status = get_option('gshfjf_jetform_verify');
        $search_permission = ($gsc_verify_status === 'valid') ? 'Granted' : 'Denied';

        // Create the system info HTML.
        $system_info  = '<div class="system-statuswc">';
        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-info-button" class="info-button">'
            . esc_html__('GSheetConnector Status', 'gsheetconnector-for-jetform') .
            '<span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
        $system_info .= '<table>';

        $system_info .= '<tr>
    <td>' . esc_html__('Plugin Name', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-600 common-badge-table info-name-blue">' . esc_html($plugin_name) . '</td>
</tr>';

        $system_info .= '<tr>
    <td>' . esc_html__('Plugin Version', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-600 common-badge-table info-name-blue">' . esc_html($plugin_version) . '</td>
</tr>';

        $system_info .= '<tr>
    <td>' . esc_html__('Plugin Subscription Plan', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-600 common-badge-table pro-badge">' . esc_html($subscription_plan) . '</td>
</tr>';

        $system_info .= '<tr>
    <td>' . esc_html__('Connected Email Account', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-600">' . esc_html($connected_email) . '</td>
</tr>';

        $system_info .= '<tr>
    <td>' . esc_html__('Authentication method for connecting to Google Sheets', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-600">' . esc_html($auth) . '</td>
</tr>';
        $permission_class = ($search_permission === 'Granted') ? 'permission-given' : 'permission-not-given';
        $system_info .= '<tr>
    <td>' . esc_html__('Google Drive Permission', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-700 permission-badge ' . esc_attr($permission_class) . '">
        ' . esc_html($search_permission) . '
    </td>
</tr>';

        $system_info .= '<tr>
    <td>' . esc_html__('Google Sheet Permission', 'gsheetconnector-for-jetform') . '</td>
    <td class="fw-700 permission-badge ' . esc_attr($permission_class) . '">
        ' . esc_html($search_permission) . '
    </td>
</tr>';

        $system_info .= '</table>';
        $system_info .= '</div>';
        // Add WordPress info.
        // Create a button for WordPress info.

        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-wordpress-info-button" class="info-button">'
            . esc_html__('WordPress', 'gsheetconnector-for-jetform') .
            '<span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="wordpress-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
        $system_info .= '<table>';

        $system_info .= '<tr><td>' . esc_html__('Version', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html(get_bloginfo('version')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Site Language', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(get_bloginfo('language')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Debug Mode', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-yellow">' . esc_html(WP_DEBUG ? __('Enabled', 'gsheetconnector-for-jetform') : __('Disabled', 'gsheetconnector-for-jetform')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Home URL', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_url(get_home_url()) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Site URL', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_url(get_site_url()) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Permalink structure', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(get_option('permalink_structure')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Is this site using HTTPS?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(is_ssl() ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Is this a multisite?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(is_multisite() ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Can anyone register on this site?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(get_option('users_can_register') ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Is this site discouraging search engines?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(get_option('blog_public') ? __('No', 'gsheetconnector-for-jetform') : __('Yes', 'gsheetconnector-for-jetform')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Default comment status', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(get_option('default_comment_status')) . '</td></tr>';

        $server_ip = isset($_SERVER['REMOTE_ADDR']) ? filter_var(wp_unslash($_SERVER['REMOTE_ADDR']), FILTER_VALIDATE_IP) : '';

        if (filter_var($server_ip, FILTER_VALIDATE_IP) === false) {
            $environment_type = __('Unknown', 'gsheetconnector-for-jetform');
        } else {
            $known_local_ips = array('127.0.0.1', '::1');
            $isLocalhost = in_array($server_ip, $known_local_ips, true);
            $environment_type = $isLocalhost
                ? __('Localhost', 'gsheetconnector-for-jetform')
                : __('Production', 'gsheetconnector-for-jetform');
        }

        // Environment Type Row
        $system_info .= '<tr><td>' . esc_html__('Environment type', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-yellow">' . esc_html($environment_type) . '</td></tr>';

        // User Count
        $user_count  = count_users();
        $total_users = isset($user_count['total_users']) ? (int) $user_count['total_users'] : 0;

        $system_info .= '<tr><td>' . esc_html__('User Count', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($total_users) . '</td></tr>';

        // Communication with WordPress.org
        $system_info .= '<tr><td>' . esc_html__('Communication with WordPress.org', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(get_option('blog_publicize') ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) . '</td></tr>';

        // Close WordPress Info Table
        $system_info .= '</table>';
        $system_info .= '</div>';



        /* ===============================
        Active Theme Information
        ================================= */

        $active_theme = wp_get_theme();

        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-active-info-button" class="info-button">'
            . esc_html__('Active Theme', 'gsheetconnector-for-jetform') .
            '<span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="active-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
        $system_info .= '<table>';

        $system_info .= '<tr><td>' . esc_html__('Name', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html($active_theme->get('Name')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Version', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html($active_theme->get('Version')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Author', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . wp_kses_post($active_theme->get('Author')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Author website', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_url($active_theme->get('AuthorURI')) . '</td></tr>';

        $system_info .= '<tr><td>' . esc_html__('Theme directory location', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($active_theme->get_template_directory()) . '</td></tr>';

        $system_info .= '</table>';
        $system_info .= '</div>';

        // Get a list of other plugins you want to check compatibility with.
        $other_plugins = array(
            'plugin-folder/plugin-file.php', // Replace with the actual plugin slug
            // Add more plugins as needed.
        );
        $active_plugins = get_option('active_plugins', array());
        // Network Active Plugins.
        if (is_multisite()) {
            $network_active_plugins = get_site_option('active_sitewide_plugins', array());
            if (!empty($network_active_plugins)) {
                $system_info .= '<div class="mb-20 mt-20"><button id="show-netplug-info-button" class="info-button">Network Active plugins<span class="dashicons dashicons-arrow-down"></span></div>';
                $system_info .= '<div id="netplug-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
                $system_info .= '<table>';
                foreach ($network_active_plugins as $plugin => $plugin_data) {
                    $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin);
                    $system_info .= '<tr><td>' . $plugin_data['Name'] . '</td><td>' . $plugin_data['Version'] . '</td></tr>';
                }
                // Add more network active plugin statuses here...
                $system_info .= '</table>';
                $system_info .= '</div>';
            }
        }
        // Active plugins.
        // Total active plugins count
        $total_active_plugins = is_array($active_plugins) ? count($active_plugins) : 0;

        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-acplug-info-button" class="info-button">'
            . esc_html__('Active Plugins', 'gsheetconnector-for-jetform') .
            ' (' . esc_html($total_active_plugins) . ')
    <span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="acplug-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
        $system_info .= '<table>';

        // Retrieve all active plugins data.
        $active_plugins_data = array();
        $active_plugins = get_option('active_plugins', array());

        // Include the necessary WordPress file.
        require_once ABSPATH . 'wp-admin/includes/plugin.php';

        $all_plugins = get_plugins();
        foreach ($active_plugins as $plugin) {
            if (isset($all_plugins[$plugin])) {
                $plugin_data = $all_plugins[$plugin];
                $active_plugins_data[$plugin] = array(
                    'name' => $plugin_data['Name'],
                    'version' => $plugin_data['Version'],
                    'count' => 0, // Initialize the count to zero.
                );
            }
        }

        // Count the number of active installations for each plugin.
        foreach ($all_plugins as $plugin_file => $plugin_data) {
            if (array_key_exists($plugin_file, $active_plugins_data)) {
                ++$active_plugins_data[$plugin_file]['count'];
            }
        }

        // Sort plugins based on the number of active installations (descending order).
        uasort(
            $active_plugins_data,
            function ($a, $b) {
                return $b['count'] - $a['count'];
            }
        );

        // Display the top 5 most used plugins.
        $counter = 0;
        foreach ($active_plugins_data as $plugin_data) {
            $system_info .= '<tr><td>' . $plugin_data['name'] . '</td><td class="fw-600 common-badge-table info-name-blue">' . $plugin_data['version'] . '</td></tr>';
            // ++$counter;
            // if ( $counter >= 5 ) {
            // break;
            // }
        }

        $system_info .= '</table>';
        $system_info .= '</div>';

        /* ===============================
        Webserver Configuration
        ================================= */

        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-server-info-button" class="info-button">'
            . esc_html__('Server', 'gsheetconnector-for-jetform') .
            '<span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="server-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';

        $system_info .= '<p class="text-dark"><b>' .
            esc_html__(
                'The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.',
                'gsheetconnector-for-jetform'
            ) .
            '</b></p>';

        $system_info .= '<table>';
        // Add Server information.
        $system_info .= '<tr>
<td>' . esc_html__('Server Architecture', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(php_uname('s')) . '</td>
</tr>';

        $server_software = isset($_SERVER['SERVER_SOFTWARE'])
            ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE']))
            : '';

        $system_info .= '<tr>
<td>' . esc_html__('Web Server', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($server_software) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('PHP Version', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html(PHP_VERSION) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('PHP SAPI', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(php_sapi_name()) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('PHP Max Input Variables', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(ini_get('max_input_vars')) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('PHP Time Limit', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(ini_get('max_execution_time')) . ' ' . esc_html__('seconds', 'gsheetconnector-for-jetform') . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('PHP Memory Limit', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(ini_get('memory_limit')) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Max Input Time', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(ini_get('max_input_time')) . ' ' . esc_html__('seconds', 'gsheetconnector-for-jetform') . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Upload Max Filesize', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(ini_get('upload_max_filesize')) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('PHP Post Max Size', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(ini_get('post_max_size')) . '</td>
</tr>';

        /* cURL Safe Check */
        $curl_version = function_exists('curl_version') ? curl_version() : array();
        $curl_display = isset($curl_version['version']) ? $curl_version['version'] : esc_html__('Not Installed', 'gsheetconnector-for-jetform');

        $system_info .= '<tr>
<td>' . esc_html__('cURL Version', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($curl_display) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Is SUHOSIN Installed?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' .
            esc_html(extension_loaded('suhosin') ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Is the Imagick Library Available?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' .
            esc_html(extension_loaded('imagick') ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Are Pretty Permalinks Supported?', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' .
            esc_html(get_option('permalink_structure') ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td>
</tr>';

        global $wp_filesystem;

        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }

        $htaccess_path = ABSPATH . '.htaccess';

        $is_writable = (isset($wp_filesystem) && $wp_filesystem->exists($htaccess_path) && $wp_filesystem->is_writable($htaccess_path));

        $system_info .= '<tr>
<td>' . esc_html__('.htaccess Rules', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' .
            esc_html($is_writable ? __('Writable', 'gsheetconnector-for-jetform') : __('Not Writable', 'gsheetconnector-for-jetform')) .
            '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Current Time', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(current_time('mysql')) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Current UTC Time', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(current_time('mysql', true)) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Current Server Time', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html(gmdate('Y-m-d H:i:s')) . '</td>
</tr>';

        $system_info .= '</table>';
        $system_info .= '</div>';


        /* ===============================
        Database Configuration
        ================================= */

        $system_info .= '<div class="mb-20 mt-20">
<button id="show-database-info-button" class="info-button">'
            . esc_html__('Database', 'gsheetconnector-for-jetform') .
            '<span class="dashicons dashicons-arrow-down"></span>
</button>
</div>';

        $system_info .= '<div id="database-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
        $system_info .= '<table>';
        $database_extension = 'mysqli';
        $database_server_version = $wpdb->get_var('SELECT VERSION() as version');
        $database_client_version = $wpdb->db_version();
        $database_username = DB_USER;
        $database_host = DB_HOST;
        $database_name = DB_NAME;
        $table_prefix = $wpdb->prefix;
        $database_charset = $wpdb->charset;
        $database_collation = $wpdb->collate;
        $max_allowed_packet_size = $wpdb->get_var("SHOW VARIABLES LIKE 'max_allowed_packet'");
        $max_connections_number = $wpdb->get_var("SHOW VARIABLES LIKE 'max_connections'");

        $system_info .= '<tr>
<td>' . esc_html__('Extension', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($database_extension) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Server Version', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html($database_server_version) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Client Version', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html($database_client_version) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Database Username', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($database_username) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Database Host', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-yellow">' . esc_html($database_host) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Database Name', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600 common-badge-table info-name-blue">' . esc_html($database_name) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Table Prefix', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($table_prefix) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Database Charset', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($database_charset) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Database Collation', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($database_collation) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Max Allowed Packet Size', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($max_allowed_packet_size) . '</td>
</tr>';

        $system_info .= '<tr>
<td>' . esc_html__('Max Connections Number', 'gsheetconnector-for-jetform') . '</td>
<td class="fw-600">' . esc_html($max_connections_number) . '</td>
</tr>';

        $system_info .= '</table>';
        $system_info .= '</div>';
        // WordPress constants.
        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-wrcons-info-button" class="info-button">'
            . esc_html__('WordPress Constants', 'gsheetconnector-for-jetform') .
            '<span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="wrcons-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';
        $system_info .= '<table>';

        $system_info .= '<tr><td>ABSPATH</td><td class="fw-600">' . esc_html(get_home_path()) . '</td></tr>';

        $system_info .= '<tr><td>WP_HOME</td><td class="fw-600 common-badge-table info-name-blue">' . esc_url(home_url()) . '</td></tr>';

        $system_info .= '<tr><td>WP_SITEURL</td><td class="fw-600">' . esc_url(site_url()) . '</td></tr>';

        $system_info .= '<tr><td>WP_CONTENT_DIR</td><td class="fw-600">' . esc_html(plugin_dir_path(GSHFJF_JETFORM_CONNECTOR_ROOT . '/..')) . '</td></tr>';

        $system_info .= '<tr><td>WP_PLUGIN_DIR</td><td class="fw-600">' . esc_html(plugin_dir_path(GSHFJF_JETFORM_CONNECTOR_ROOT)) . '</td></tr>';

        $system_info .= '<tr><td>WP_MEMORY_LIMIT</td><td class="fw-600">' . esc_html(WP_MEMORY_LIMIT) . '</td></tr>';

        $system_info .= '<tr><td>WP_MAX_MEMORY_LIMIT</td><td class="fw-600">' . esc_html(WP_MAX_MEMORY_LIMIT) . '</td></tr>';

        $system_info .= '<tr><td>WP_DEBUG</td><td class="fw-600">' .
            esc_html((defined('WP_DEBUG') && WP_DEBUG) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>WP_DEBUG_DISPLAY</td><td class="fw-600">' .
            esc_html((defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>SCRIPT_DEBUG</td><td class="fw-600">' .
            esc_html((defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>WP_CACHE</td><td class="fw-600">' .
            esc_html((defined('WP_CACHE') && WP_CACHE) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>CONCATENATE_SCRIPTS</td><td class="fw-600">' .
            esc_html((defined('CONCATENATE_SCRIPTS') && CONCATENATE_SCRIPTS) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>COMPRESS_SCRIPTS</td><td class="fw-600">' .
            esc_html((defined('COMPRESS_SCRIPTS') && COMPRESS_SCRIPTS) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>COMPRESS_CSS</td><td class="fw-600">' .
            esc_html((defined('COMPRESS_CSS') && COMPRESS_CSS) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        /* Proper Environment Type (WordPress way) */
        $environment_type = function_exists('wp_get_environment_type')
            ? wp_get_environment_type()
            : 'production';

        $system_info .= '<tr><td>WP_ENVIRONMENT_TYPE</td><td class="fw-600">' .
            esc_html($environment_type) .
            '</td></tr>';

        $system_info .= '<tr><td>WP_DEVELOPMENT_MODE</td><td class="fw-600">' .
            esc_html((defined('WP_DEVELOPMENT_MODE') && WP_DEVELOPMENT_MODE) ? __('Yes', 'gsheetconnector-for-jetform') : __('No', 'gsheetconnector-for-jetform')) .
            '</td></tr>';

        $system_info .= '<tr><td>DB_CHARSET</td><td class="fw-600">' . esc_html(DB_CHARSET) . '</td></tr>';

        $system_info .= '<tr><td>DB_COLLATE</td><td class="fw-600">' . esc_html(DB_COLLATE) . '</td></tr>';

        $system_info .= '</table>';
        $system_info .= '</div>';

        /* ===============================
        Filesystem Permission
        ================================= */

        $system_info .= '<div class="mb-20 mt-20">
    <button id="show-ftps-info-button" class="info-button">'
            . esc_html__('Filesystem Permission', 'gsheetconnector-for-jetform') .
            ' <span class="dashicons dashicons-arrow-down"></span>
    </button>
</div>';

        $system_info .= '<div id="ftps-info-container" class="info-content shadow-box pt-20 pb-20 pl-30 pr-30" style="display:none;">';

        $system_info .= '<p class="text-dark"><b>' .
            esc_html__(
                'Shows whether WordPress is able to write to the directories it needs access to.',
                'gsheetconnector-for-jetform'
            ) .
            '</b></p>';

        $system_info .= '<table>';

        global $wp_filesystem;

        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }

        /* Safer uploads directory */
        $upload_dir = wp_get_upload_dir();
        $uploads_path = isset($upload_dir['basedir']) ? $upload_dir['basedir'] : '';

        $paths = array(
            __('The main WordPress directory', 'gsheetconnector-for-jetform') => get_home_path(),
            __('The wp-content directory', 'gsheetconnector-for-jetform')     => WP_CONTENT_DIR,
            __('The uploads directory', 'gsheetconnector-for-jetform')        => $uploads_path,
            __('The plugins directory', 'gsheetconnector-for-jetform')        => plugin_dir_path(GSHFJF_JETFORM_CONNECTOR_ROOT),
            __('The themes directory', 'gsheetconnector-for-jetform')         => get_theme_root(),
        );

        foreach ($paths as $label => $path) {

            $writable = (
                isset($wp_filesystem) &&
                $wp_filesystem->exists($path) &&
                $wp_filesystem->is_writable($path)
            );

            $system_info .= '<tr>
        <td>' . esc_html($label) . '</td>
        <td>' . esc_html($path) . '</td>
        <td class="fw-600">' .
                esc_html(
                    $writable
                        ? __('Writable', 'gsheetconnector-for-jetform')
                        : __('Not Writable', 'gsheetconnector-for-jetform')
                ) .
                '</td>
    </tr>';
        }

        $system_info .= '</table>';
        $system_info .= '</div>';

        return $system_info;
    }

    /**
     * Display the last 100 lines from the WordPress debug.log file in a textarea.
     */

    public function gshfjf_display_error_log()
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $debug_log_file = WP_CONTENT_DIR . '/debug.log';

        if (!file_exists($debug_log_file)) {
            echo '<p>Debug log file not found.</p>';
            return;
        }

        $log_lines = file($debug_log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

        // Reverse and limit to last 100
        $log_lines = array_slice(array_reverse($log_lines), 0, 100);

        echo '<div style="max-height:500px; overflow:auto;">';
        echo '<table class="widefat striped mt-30">';
        echo '<thead>
        <tr>
        <th>' . esc_html__('Date', 'gsheetconnector-for-jetform') . '</th>
        <th>' . esc_html__('Type', 'gsheetconnector-for-jetform') . '</th>
        <th>' . esc_html__('Message', 'gsheetconnector-for-jetform') . '</th>
        <th>' . esc_html__('File', 'gsheetconnector-for-jetform') . '</th>
        </tr>
        </thead>';
        echo '<tbody>';

        foreach ($log_lines as $line) {

            if (preg_match('/\[(.*?)\]\s(.*?):\s(.*)/', $line, $matches)) {

                $date    = str_replace(' UTC', '', $matches[1]);
                $type    = str_replace('PHP ', '', $matches[2]);
                $message = $matches[3];

                $file = '-';
                if (preg_match('/in (.*?) on line/', $message, $file_match)) {
                    $file = $file_match[1];
                }

                echo '<tr>';
                echo '<td>' . esc_html($date) . '</td>';
                echo '<td>' . esc_html($type) . '</td>';
                echo '<td>' . esc_html($message) . '</td>';
                echo '<td>' . esc_html($file) . '</td>';
                echo '</tr>';
            }
        }

        echo '</tbody>';
        echo '</table>';
        echo '</div>';
    }

    /**
     * AJAX function - clear log file for system status tab
     *
     * @since 1.0.0
     */

    public function gshfjf_clear_logs()
    {
        // nonce check
        check_ajax_referer('gshfjf-ajax-nonce', 'security');

        // Initialize the WP_Filesystem global
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
            WP_Filesystem();
        }

        // Define log path
        $debug_file = WP_CONTENT_DIR . '/debug.log';

        // If file exists and is writable, clear it; otherwise create an empty file
        if ($wp_filesystem->exists($debug_file)) {
            if ($wp_filesystem->is_writable($debug_file)) {
                $result = $wp_filesystem->put_contents($debug_file, '', FS_CHMOD_FILE);
            } else {
                wp_send_json_error('Debug log is not writable', 403);
            }
        } else {
            // Create the file if it doesn’t exist
            $result = $wp_filesystem->put_contents($debug_file, '', FS_CHMOD_FILE);
        }

        if (false === $result) {
            wp_send_json_error('Failed to clear debug log', 500);
        }

        wp_send_json_success();
    }
}
// Initialize the google sheet connector class
$gshfjf_init = new GSHFJF_JetForm_Connector_Init();
