<?php

use Carbon_Fields\Container;
use Carbon_Fields\Field;

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://gleap.io
 * @since      1.0.0
 *
 * @package    Gleap
 * @subpackage Gleap/admin
 */
class Gleap_Admin
{

    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $plugin_name The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string $version The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @param string $plugin_name The name of this plugin.
     * @param string $version The version of this plugin.
     * @since    1.0.0
     */
    public function __construct($plugin_name, $version)
    {

        $this->plugin_name = $plugin_name;
        $this->version = $version;

        $this->load_dependencies();
    }

    /**
     * Load the required dependencies for the Admin facing functionality.
     *
     * Include the following files that make up the plugin:
     *
     * - Carbon
     *
     *
     * @since    1.0.0
     * @access   private
     */
    private function load_dependencies()
    {

        /**
         * The class responsible for orchestrating the actions and filters of the
         * core plugin.
         */
        //require_once plugin_dir_path( dirname( __FILE__ ) ) .  'admin/class-gleap-settings.php';

    }

    /**
     * Migrate old role settings to new separate frontend/admin role settings.
     * This ensures backward compatibility when updating from older plugin versions.
     * Uses proper Carbon Fields methods as per documentation.
     *
     * @since    1.0.0
     * @access   private
     */
    private function migrate_old_role_settings()
    {
        // Check if Carbon Fields functions are available
        if (!function_exists('carbon_get_theme_option') || !function_exists('carbon_set_theme_option')) {
            return;
        }

        // Check if migration has already been performed
        $migration_done = get_option('gleap_role_migration_done', false);
        if ($migration_done) {
            return;
        }

        // Get old role settings from database directly since these fields are no longer registered
        // Carbon Fields can't retrieve values for fields that aren't in the current schema
        $old_roles_only = get_option('_gleap_selected_roles_only', null);
        $old_selected_roles_raw = get_option('_gleap_selected_roles|||0|value', null);
        
        // Convert the selected roles to array format
        $old_selected_roles = null;
        if ($old_selected_roles_raw !== null && $old_selected_roles_raw !== '') {
            $old_selected_roles = array($old_selected_roles_raw);
        }

        // Only log if we found something to migrate
        if ($old_roles_only !== null && $old_roles_only !== '') {
            error_log('Gleap Migration: Found old database values - roles_only=' . var_export($old_roles_only, true) . ', selected_roles_raw=' . var_export($old_selected_roles_raw, true));
        }

        // Check if we got the expected data types and values
        $has_valid_roles_only = ($old_roles_only === 'yes');
        $has_valid_selected_roles = !empty($old_selected_roles);

        // Only migrate if old settings exist and have meaningful values
        if ($has_valid_roles_only) {
            // Convert to boolean (Carbon Fields stores checkbox as 'yes'/'no' or boolean)
            $roles_only_bool = true; // We know it's enabled if we got here
            
            // Ensure selected roles is an array
            if (!is_array($old_selected_roles)) {
                $old_selected_roles = $old_selected_roles ? array($old_selected_roles) : array();
            }
            
            // Migrate to new frontend settings using direct database insertion (Carbon Fields format)
            // Since carbon_set_theme_option might not work during field registration, 
            // we'll set the values directly in the database using Carbon Fields format
            
            // Frontend roles only checkbox
            update_option('_gleap_frontend_selected_roles_only', $roles_only_bool ? 'yes' : 'no');
            
            // Frontend selected roles multiselect
            if (!empty($old_selected_roles)) {
                // For multiselect fields, Carbon Fields stores each value with |||index|value format
                foreach ($old_selected_roles as $index => $role) {
                    update_option('_gleap_frontend_selected_roles|||' . $index . '|value', $role);
                }
            }

            // Admin roles only checkbox  
            update_option('_gleap_admin_selected_roles_only', $roles_only_bool ? 'yes' : 'no');
            
            // Admin selected roles multiselect
            if (!empty($old_selected_roles)) {
                // For multiselect fields, Carbon Fields stores each value with |||index|value format
                foreach ($old_selected_roles as $index => $role) {
                    update_option('_gleap_admin_selected_roles|||' . $index . '|value', $role);
                }
            }

            // Mark migration as completed
            update_option('gleap_role_migration_done', true);
            
            // Log successful migration
            error_log('Gleap Migration: Successfully migrated role settings to separate frontend/admin controls');
        }
    }

    /**
     * Handle migration only when on Gleap settings page
     * This prevents migration from running on every request
     *
     * @since    1.0.0
     */
    public function handle_migration_on_settings_page() {
        // Only run on Gleap settings page in admin
        if (is_admin() && isset($_GET['page']) && $_GET['page'] === 'crb_carbon_fields_container_gleap.php') {
            // Add a delay to ensure Carbon Fields is fully loaded
            add_action('admin_head', array($this, 'run_migration_when_ready'));
        }
    }

    /**
     * Run migration when Carbon Fields is ready
     *
     * @since    1.0.0
     */
    public function run_migration_when_ready() {
        $this->migrate_old_role_settings();
    }

    /**
     * Reset migration flag - useful for development/testing
     * This method can be called to force re-migration of settings
     *
     * @since    1.0.0
     */
    public function reset_migration_flag() {
        delete_option('gleap_role_migration_done');
        error_log('Gleap Migration: Reset migration flag - next admin page visit will trigger migration');
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles()
    {

        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Gleap_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Gleap_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/gleap-admin.css', array(), $this->version, 'all');
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts()
    {
        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Gleap_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Gleap_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */

        wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/gleap-admin.js', array('jquery'), $this->version, false);

        // Check if Gleap should be activated in admin
        $gleap_activate_in_admin = carbon_get_theme_option('gleap_activate_in_admin');

        if ($gleap_activate_in_admin) {
            $gleap_token = carbon_get_theme_option('gleap_token');

            // Apply filter to allow modification of the gleap_token
            $gleap_token = apply_filters('gleap_modify_token', $gleap_token);

            if ($gleap_token) {
                $gleap_admin_selected_roles_only = carbon_get_theme_option('gleap_admin_selected_roles_only');
                if ($gleap_admin_selected_roles_only == true) {
                    $user_roles = wp_get_current_user()->roles;
                    $gleap_admin_selected_roles = carbon_get_theme_option('gleap_admin_selected_roles');

                    if (!array_intersect($user_roles, $gleap_admin_selected_roles)) {
                        // If the user's role is not in the selected roles, don't show Gleap
                        return;
                    }
                }

                $identify_script = "";
                if (is_user_logged_in()) {
                    $gleap_identity_token = carbon_get_theme_option('gleap_identity_token');

                    // Apply filter to allow modification of the gleap_identity_token
                    $gleap_identity_token = apply_filters('gleap_modify_identity_token', $gleap_identity_token);

                    $user_data = get_userdata(get_current_user_id());
                    $login = $user_data->user_login;
                    $signature = hash_hmac('sha256', $login, $gleap_identity_token);

                    // Prepare identify data
                    $identify_data = $this->prepare_gleap_identify_data();
                    $identify_json = json_encode($identify_data);

                    $identify_script = ',Gleap.identify("' . $login . '", ' . $identify_json . ', "' . $signature . '");';
                }

                $gleap_set_language = "";

                if (class_exists('SitePress')) {
                    $current_language = apply_filters('wpml_current_language', NULL);
                    $gleap_set_language = 'Gleap.setLanguage("' . $current_language . '"),';
                }

                wp_register_script('gleap-sdk-js', '',);
                wp_enqueue_script('gleap-sdk-js');
                wp_add_inline_script('gleap-sdk-js', '!function(Gleap,t,i){if(!(Gleap=window.Gleap=window.Gleap||[]).invoked){for(window.GleapActions=[],Gleap.invoked=!0,Gleap.methods=["identify","clearIdentity","attachCustomData","setCustomData","removeCustomData","clearCustomData","registerCustomAction","logEvent","sendSilentCrashReport","startFeedbackFlow","setAppBuildNumber","setAppVersionCode","preFillForm","setApiUrl","setFrameUrl","isOpened","open","close","on","setLanguage","setOfflineMode","initialize"],Gleap.f=function(e){return function(){var t=Array.prototype.slice.call(arguments);window.GleapActions.push({e:e,a:t})}},t=0;t<Gleap.methods.length;t++)Gleap[i=Gleap.methods[t]]=Gleap.f(i);Gleap.load=function(){var t=document.getElementsByTagName("head")[0],i=document.createElement("script");i.type="text/javascript",i.async=!0,i.src="https://sdk.gleap.io/latest/index.js",t.appendChild(i)},Gleap.load(),' . $gleap_set_language . 'Gleap.initialize("' . $gleap_token . '")' . $identify_script . 'Gleap.attachCustomData({
                    wp_version: "' . get_bloginfo('version') . '",
                    php_version: "' . phpversion() . '",
                    theme: "' . wp_get_theme()->get('Name') . '",
                    theme_version: "' . wp_get_theme()->get('Version') . '",
                    is_multisite: ' . (is_multisite() ? 'true' : 'false') . ',
                    active_plugins: ' . json_encode($this->get_active_plugins()) . ',
                    is_admin: true
                })}}();');
            }
        }
    }

    /**
     * Prepare the data for the Gleap.identify call.
     *
     * @since    1.0.0
     */
    private function prepare_gleap_identify_data()
    {
        if (!is_user_logged_in()) {
            return '';
        }

        $user_data = get_userdata(get_current_user_id());
        $login = $user_data->user_login;
        $uname = $user_data->user_firstname . ' ' . $user_data->user_lastname;
        $nickname = (strlen($user_data->nickname) > 1) ? $user_data->nickname : '';
        $name = (strlen($uname) > 1) ? $uname : $nickname;
        $email = $user_data->user_email;

        // Prepare the default data array.
        $data = array(
            'name' => $name,
            'email' => $email,
        );

        // Allow other plugins to add or modify data.
        $data = apply_filters('gleap_identify_data', $data);

        return $data;
    }

    public function setup_settings_ui()
    {
        // Migration is now handled separately in admin_init hook
        // Don't run migration here as this hook fires on every request

        // Get WordPress roles
        $wp_roles = wp_roles();
        $roles = array();
        foreach ($wp_roles->roles as $role => $details) {
            $roles[$role] = translate_user_role($details['name']);
        }


        $gleap_fields = array(
            Field::make('text', 'gleap_token', 'API key')->set_required(true)->set_help_text("Get your free API key within the <a href=\"https://app.gleap.io/\">Gleap Dashboard.</a>"),
            Field::make('text', 'gleap_identity_token', 'Identity verification secret')->set_attribute('type', 'password')->set_help_text("If you'd like to verify the identity of your users, copy the code from Project -> Settings -> Security to the field above."),
            Field::make('text', 'gleap_secret_api_token', 'Secret API token')->set_attribute('type', 'password')->set_help_text("If you'd like to use the Gleap Rest API to send events, copy the code from Project -> Settings -> Security to the field above."),
            Field::make('checkbox', 'gleap_activate_in_frontend', 'Activate Gleap widget in Frontend')
                ->set_default_value(true)
                ->set_help_text('Enable the Gleap widget in the frontend area.'),
            Field::make('checkbox', 'gleap_frontend_selected_roles_only', 'Enable Gleap frontend only for selected WP roles')
                ->set_default_value(false)
                ->set_help_text('Gleap widget will only be visible in frontend for users with the selected roles.')
                ->set_conditional_logic(array(
                    array(
                        'field' => 'gleap_activate_in_frontend',
                        'value' => true,
                        'compare' => '='
                    )
                )),
            Field::make('multiselect', 'gleap_frontend_selected_roles', 'Select roles for frontend')
                ->add_options($roles)
                ->set_conditional_logic(array(
                    array(
                        'field' => 'gleap_frontend_selected_roles_only',
                        'value' => true,
                        'compare' => '='
                    )
                )),
            Field::make('checkbox', 'gleap_activate_in_admin', 'Activate Gleap widget in WP Admin')
                ->set_default_value(false)
                ->set_help_text('Enable the Gleap widget in the WordPress admin area.'),
            Field::make('checkbox', 'gleap_admin_selected_roles_only', 'Enable Gleap admin only for selected WP roles')
                ->set_default_value(false)
                ->set_help_text('Gleap widget will only be visible in WP admin for users with the selected roles.')
                ->set_conditional_logic(array(
                    array(
                        'field' => 'gleap_activate_in_admin',
                        'value' => true,
                        'compare' => '='
                    )
                )),
            Field::make('multiselect', 'gleap_admin_selected_roles', 'Select roles for admin')
                ->add_options($roles)
                ->set_conditional_logic(array(
                    array(
                        'field' => 'gleap_admin_selected_roles_only',
                        'value' => true,
                        'compare' => '='
                    )
                ))
        );

        if (class_exists('SitePress')) {
            $gleap_fields[] = Field::make('checkbox', 'gleap_detect_wpml_lang', 'Detect language from wpml')
                ->set_default_value(false)
                ->set_help_text('Gleap widget will automatically detect the language from WPML. If this is not enabled, the language will be set to the user\'s browser language.');
        }

        Container::make('theme_options', __('Gleap'))
            ->set_page_parent('options-general.php')
            ->add_fields($gleap_fields);
    }

    public function crb_load()
    {
        \Carbon_Fields\Carbon_Fields::boot();
    }

    /**
     * Get a list of active plugins for Gleap custom data.
     *
     * @since    1.0.0
     * @return   array    Array of active plugins with their versions.
     */
    private function get_active_plugins()
    {
        if (!function_exists('get_plugins')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active_plugins = array();
        $all_plugins = get_plugins();
        $activated_plugins = get_option('active_plugins');

        foreach ($activated_plugins as $plugin) {
            if (isset($all_plugins[$plugin])) {
                $plugin_name = $all_plugins[$plugin]['Name'];
                $plugin_version = $all_plugins[$plugin]['Version'];
                $active_plugins[$plugin_name] = $plugin_version;
            }
        }

        return $active_plugins;
    }
}
