<?php
class FLEXIMP_Template_Importer
{

    public $text_domain;
    public function init()
    {
        $this->includes();

        add_action('wp_ajax_fleximp_verify_license', array($this, 'fleximp_verify_license'));
        add_action('wp_ajax_fleximp_deactivate_license', array($this, 'fleximp_deactivate_license'));
        add_action('admin_menu', array($this, 'fleximp_add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'fleximp_enqueue_admin_assets'));
        add_action('wp_enqueue_scripts', array($this, 'fleximp_enqueue_frontend_assets'));
        add_action('wp_ajax_fleximp_install_elementor', array($this, 'fleximp_install_elementor_ajax'));
        add_action('wp_ajax_fleximp_import_demo_content', array($this, 'fleximp_import_demo_content'));
        add_action('wp_ajax_fleximp_install_single_plugin', array($this, 'fleximp_install_single_plugin'));
        add_action('wp_ajax_fleximp_get_required_plugins', array($this, 'fleximp_get_required_plugins'));
        add_action('wp_ajax_fleximp_import_inner_pages_data', array($this, 'fleximp_import_inner_pages_data'));
        add_action('admin_head', array($this, 'fleximp_hide_admin_notices'));
        add_action('wp_ajax_fleximp_install_plugin', array($this, 'fleximp_install_plugin'));
        add_action('wp_ajax_fleximp_get_plugin_statuses', array($this, 'fleximp_get_plugin_statuses'));
        add_action('wp_ajax_render_fleximp_dashboard_content', [$this, 'render_fleximp_dashboard_content']);
        add_action('wp_ajax_fleximp_checked_install_plugin', [$this, 'fleximp_checked_install_plugin']);
        add_action('wp_ajax_fleximp_set_text_domain', array($this, 'fleximp_set_text_domain'));
        $is_premium_user = get_option('fleximp_is_premium', false);
        $this->text_domain = get_option('fleximp_current_text_domain');
        add_action('wp_ajax_fleximp_uninstall_template', [$this, 'fleximp_uninstall_template']);
        add_action('wp_ajax_fleximp_install_activate_theme', [$this, 'fleximp_install_activate_theme']);
    }

    public function fleximp_set_text_domain()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Unauthorized');
        }

        $is_premium = defined('FLEXIMP_PREMIUM_THEME') && FLEXIMP_PREMIUM_THEME === true;

        if (!$is_premium) {
            $template_php = isset($_POST['template_php'])
                ? esc_url_raw($_POST['template_php'])
                : '';

            if (!empty($template_php)) {
                $this->fleximp_handle_template_php_redirect($template_php);
            }
        }

        $text_domain = sanitize_text_field($_POST['text_domain'] ?? '');
        $template_mobile_image = isset($_POST['template_mobile_image']) ? esc_url_raw($_POST['template_mobile_image']) : '';
        $template_title = isset($_POST['template_title']) ? sanitize_text_field($_POST['template_title']) : '';

        if ($text_domain) {
            update_option('fleximp_current_text_domain', $text_domain);
            if (!empty($template_mobile_image)) {
                update_option('fleximp_current_template_mobile_image', $template_mobile_image);
            }
            if (!empty($template_title)) {
                update_option('fleximp_current_template_title', $template_title);
            }
            wp_send_json_success('Text domain saved');
        } else {
            wp_send_json_error('Text domain is empty');
        }
    }


    private function includes()
    {
        require_once FLEXIMP_PLUGIN_FILE . 'includes/fleximp-license-functions.php';
    }

    public function fleximp_enqueue_frontend_assets()
    {
        if (!is_admin()) {
            wp_enqueue_script('fleximp-service-tabs-scripts', FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/front-script.js', array('jquery'), FLEXIMP_VER, true);
        }
    }

    public function fleximp_add_admin_menu()
    {
        add_menu_page(
            'Elementor Template Importer',
            'Flex Importer',
            'manage_options',
            'fleximp-template-importer',
            array($this, 'fleximp_display_dashboard_page'),
            'dashicons-download',
            20
        );

        add_submenu_page(
            'fleximp-template-importer',
            'License Key',
            'License Key',
            'manage_options',
            'fleximp-license-key',
            array($this, 'fleximp_display_license_page')
        );
    }


    public function fleximp_hide_admin_notices()
    {
        $screen = get_current_screen();
        if ($screen->id === 'toplevel_page_fleximp-template-importer') {
            remove_all_actions('admin_notices');
            remove_all_actions('all_admin_notices');
        }
    }

    function fleximp_display_license_page()
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Sorry, you are not allowed to access this page.', 'flex-import'));
        }
        ?>
        <div class="license-key-wrap">
            <form id="fleximp-license-key-form" action="<?php echo esc_url(admin_url('admin.php?page=')); ?>" method="POST">
                <div class="license-key-input-wrap">
                    <label><?php esc_html_e('Enter Your Plugin License Key:', 'flex-import'); ?></label>
                    <div class="license-key-input">
                        <input type="text" name="fleximp_is_premium" required placeholder="License Key"
                            value="<?php echo esc_attr(get_fleximp_key()); ?>" />
                    </div>
                    <button class="button" name="key-activation" value="<?php esc_html_e('Activate', 'flex-import'); ?>"
                        type="submit">Activate</button>
                    <button class="button deactivate-domain" value="<?php esc_html_e('Deactivate', 'flex-import'); ?>"
                        type="button">Deactivate</button>
                    <?php if (get_fleximp_suspension_status() == 'false' && get_fleximp_validation_status() !== 'false') { ?>
                        <br><small id="license">License Key Activated Successfully</small>
                    <?php } ?>
                </div>
            </form>
        </div>
        <div class="fleximp-server-info" style="margin-top: 30px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd;">
            <h3><?php esc_html_e('Recommended Server Settings for Importing Demo Content', 'flex-import'); ?></h3>
            <ul>
                <li><strong>PHP Time Limit:</strong> <?php echo esc_html(ini_get('max_execution_time')); ?> (Recommended:
                    5000)</li>
                <li><strong>PHP Memory Limit:</strong> <?php echo esc_html(ini_get('memory_limit')); ?> (Recommended: 9512M or
                    more)</li>
                <li><strong>Max Input Vars:</strong> <?php echo esc_html(ini_get('max_input_vars')); ?> (Recommended: 6000)
                </li>
                <li><strong>Max Upload Size:</strong> <?php echo esc_html(size_format(wp_max_upload_size())); ?>
                    (Recommended: 200MB or more)</li>
            </ul>
            <p style="color: #d63638;"><strong>Note:</strong>
                <?php esc_html_e('Contact your hosting provider to increase these values if needed for successful demo content import.', 'flex-import'); ?>
            </p>
        </div>

        <?php // } ?>

        <?php if (get_fleximp_suspension_status() == 'false' && get_fleximp_validation_status() !== 'false') { ?>
            <div class="fleximp-elems-next" style="display:none;">

            </div>
        <?php } ?>
    <?php

    }
    // end

    public function fleximp_deactivate_license()
    {
        delete_option('fleximp_plugin_license_key');
        delete_option('fleximp_plugin_license_validation_status');
        wp_send_json_success(['message' => 'License deactivated successfully.']);
    }

    function fleximp_install_plugin_handler()
    {
        check_ajax_referer('fleximp_quick_setup_nonce', 'security');

        if (!current_user_can('install_plugins')) {
            wp_send_json_error(['message' => 'You do not have permission to install plugins.']);
        }

        $template = sanitize_text_field($_POST['template']);
        $plugins = $_POST['plugins'];

        if (empty($template) || empty($plugins)) {
            wp_send_json_error(['message' => 'Template or plugins data missing.']);
        }

        wp_send_json_success(['message' => 'Plugins installed successfully.']);
    }

    public function fleximp_get_plugin_statuses()
    {

        check_ajax_referer('fleximp_quick_setup_nonce', 'security');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'Unauthorized'], 403);
            return;
        }

        $plugins = isset($_POST['plugins']) ? json_decode(stripslashes($_POST['plugins']), true) : [];

        if (empty($plugins)) {
            wp_send_json_error(['message' => 'No plugins provided'], 400);
            return;
        }

        // Retrieve statuses
        $installed_plugins = get_plugins();
        $active_plugins = get_option('active_plugins', []);
        $response = [];

        foreach ($plugins as $plugin) {
            $slug = $plugin['slug'] ?? '';
            $main_file = $plugin['main_file'] ?? '';

            if (!$slug || !$main_file)
                continue;

            $plugin_path = "{$slug}/{$main_file}";
            $response[$slug] = in_array($plugin_path, $active_plugins) ? 'Activated' : (isset($installed_plugins[$plugin_path]) ? 'Installed' : 'Not Installed');
        }

        wp_send_json_success($response);
    }
    //end

    //import inner pages data
    public function fleximp_import_inner_pages_data()
    {
        ob_start();

        // Permission check
        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to import demo content.', 'flex-import'));
        }

        if (defined('FLEXIMP_PREMIUM_THEME') && FLEXIMP_PREMIUM_THEME === true) {

            $active_theme = wp_get_theme();
            $active_theme_textdomain = $active_theme->get('TextDomain');
            $setup_widgets_function = str_replace('-', '_', $active_theme_textdomain) . '_setup_widgets';

            if (class_exists('Flex_Import_Content_Whizzie') && method_exists('Flex_Import_Content_Whizzie', $setup_widgets_function)) {
                try {
                    $result = Flex_Import_Content_Whizzie::$setup_widgets_function();

                    ob_clean();

                    if ($result !== false) {
                        wp_send_json_success(__('Inner pages data imported successfully!', 'flex-import'));
                    } else {
                        wp_send_json_error(__('Error occurred while importing inner pages data. Please check the logs.', 'flex-import'));
                    }
                } catch (Exception $e) {
                    ob_clean();
                    wp_send_json_error(
                        sprintf(__('An error occurred: %s', 'flex-import'), $e->getMessage())
                    );
                }
            } else {
                ob_clean();
                wp_send_json_error(__('The setup function for the theme could not be found.', 'flex-import'));
            }

            // wp_die();
            exit;
        }

        $content_path = isset($_POST['content_path']) ? sanitize_text_field($_POST['content_path']) : '';
        $text_domain = isset($_POST['text_domain']) ? sanitize_text_field($_POST['text_domain']) : '';
        $template_php = isset($_POST['template_php']) ? esc_url_raw($_POST['template_php']) : '';
        $template_css = isset($_POST['template_css']) ? esc_url_raw($_POST['template_css']) : '';
        $template_js = isset($_POST['template_js']) ? esc_url_raw($_POST['template_js']) : '';

        if (!empty($template_php)) {
            $this->fleximp_handle_template_php_redirect($template_php);
        }
        if (!empty($template_css)) {
            $this->fleximp_handle_template_css_redirect($template_css);
        }
        if (!empty($template_js)) {
            $this->fleximp_handle_template_js_redirect($template_js);
        }

        if (empty($content_path)) {
            wp_send_json_error(__('Content path is missing or invalid.', 'flex-import'));
        }

        // Fetch demo content
        $response = wp_remote_get($content_path);
        if (is_wp_error($response)) {
            wp_send_json_error(__('Error fetching demo content from the server.', 'flex-import'));
        }
        $content = wp_remote_retrieve_body($response);

        // Fetch and validate hash
        $hash_response = wp_remote_get($content_path . '.sha256');
        if (is_wp_error($hash_response)) {
            wp_send_json_error(__('Failed to fetch content hash from server.', 'flex-import'));
        }

        $expected_hash = trim(wp_remote_retrieve_body($hash_response));
        $actual_hash = hash('sha256', $content);

        if ($expected_hash !== $actual_hash) {
            wp_send_json_error(__('Hash mismatch — content may be tampered with.', 'flex-import'));
        }

        // Replace demo asset URLs
        $content = str_replace(
            'http://example.com/assets/images/',
            FLEXIMP_MAIN_URL . 'demo-content/' . $text_domain . '/assets/images/',
            $content
        );

        // Initialize filesystem
        if (!function_exists('WP_Filesystem')) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }

        global $wp_filesystem;
        WP_Filesystem();

        $upload_dir = wp_upload_dir();
        $temp_file = $upload_dir['basedir'] . '/temp-content-import.php';

        if (!$wp_filesystem->put_contents($temp_file, $content, FS_CHMOD_FILE)) {
            wp_send_json_error(__('Failed to save temporary file for demo content.', 'flex-import'));
        }

        try {
            include $temp_file;
        } catch (Exception $e) {
            wp_send_json_error(__('Error executing demo content.', 'flex-import'));
        }

        wp_delete_file($temp_file);

        ob_clean();
        wp_send_json_success(__('Demo content imported successfully!', 'flex-import'));
        wp_die();
    }


    // js
    public function fleximp_handle_template_js_redirect($template_js = '')
    {
        if (!empty($template_js)) {
            update_option('fleximp_dynamic_template_js', esc_url_raw($template_js));
        }
    }
    //end

    // php
    public function fleximp_handle_template_php_redirect($template_php = '')
    {
        if (!empty($template_php)) {
            update_option('fleximp_dynamic_template_php', esc_url_raw($template_php));
        }
    }
    //end

    // css
    public function fleximp_handle_template_css_redirect($template_css = '')
    {
        if (!empty($template_css)) {
            update_option('fleximp_dynamic_template_css', esc_url_raw($template_css));
        }
    }

    public function fleximp_get_required_plugins()
    {
        if (!current_user_can('install_plugins')) {
            wp_send_json_error(['message' => 'You do not have permission to install plugins.']);
        }

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

        $plugins_file = get_template_directory() . '/inc/plugins.json';

        if ($wp_filesystem->exists($plugins_file)) {
            $plugins_json = $wp_filesystem->get_contents($plugins_file);


            if (empty($plugins_json)) {
                wp_send_json_error(['message' => 'Plugins configuration file is empty.']);
            }

            $plugins = json_decode($plugins_json, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                wp_send_json_error(['message' => 'Invalid JSON format in plugins configuration file.']);
            }

            foreach ($plugins as $key => $plugin) {
                $main_file = !empty($plugin['main_file']) ? $plugin['main_file'] : $plugin['slug'] . '.php';
                $plugin_file = WP_PLUGIN_DIR . '/' . $plugin['slug'] . '/' . $main_file;
                $plugins[$key]['status'] = file_exists($plugin_file) && is_plugin_active($plugin_file) ? 'installed' : 'required';
            }

            wp_send_json_success($plugins);
        } else {
            wp_send_json_error(['message' => 'Plugins configuration file not found.']);
        }
    }


    // from templates tab plugins
    public function fleximp_checked_install_plugin()
    {
        // check_ajax_referer('fleximp_quick_setup_nonce', 'security');

        if (!current_user_can('install_plugins')) {
            wp_send_json_error(['message' => 'You do not have permission to install plugins.']);
        }

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

        $plugin_slug = sanitize_text_field($_POST['plugin_slug']);
        $plugin_name = sanitize_text_field($_POST['plugin_name']);
        $plugin_main_file = sanitize_text_field($_POST['plugin_main_file']);

        if (empty($plugin_slug) || empty($plugin_name) || empty($plugin_main_file)) {
            wp_send_json_error(['message' => 'Plugin details are missing.']);
        }

        $plugin_file = WP_PLUGIN_DIR . '/' . $plugin_slug . '/' . $plugin_main_file;

        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        $upgrader = new Plugin_Upgrader();

        // Install the plugin if it's not already installed
        if (!file_exists($plugin_file)) {
            $plugin_url = 'https://downloads.wordpress.org/plugin/' . $plugin_slug . '.latest-stable.zip';
            $install_result = $upgrader->install($plugin_url);

            if (is_wp_error($install_result)) {
                wp_send_json_error(['message' => 'Installation error: ' . $install_result->get_error_message()]);
            }

            if (file_exists($plugin_file)) {
                $activation = activate_plugin($plugin_slug . '/' . $plugin_main_file);
                if (is_wp_error($activation)) {
                    wp_send_json_error(['message' => 'Activation error: ' . $activation->get_error_message()]);
                }
                wp_send_json_success(['message' => 'Plugin installed and activated successfully.']);
            } else {
                wp_send_json_error(['message' => 'Plugin installation failed.']);
            }
        } else {
            // Activate if already installed but not active
            if (!is_plugin_active($plugin_file)) {
                $activation = activate_plugin($plugin_slug . '/' . $plugin_main_file);
                if (is_wp_error($activation)) {
                    wp_send_json_error(['message' => 'Activation error: ' . $activation->get_error_message()]);
                }
            }
            wp_send_json_success(['message' => 'Plugin is already installed and activated.']);
        }
    }

    public function fleximp_install_plugin()
    {
        // check_ajax_referer('fleximp_quick_setup_nonce', 'security');

        if (!current_user_can('install_plugins')) {
            wp_send_json_error(['message' => 'You do not have permission to install plugins.']);
        }

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

        $plugin_slug = sanitize_text_field($_POST['plugin_slug']);
        $plugin_name = sanitize_text_field($_POST['plugin_name']);
        $plugin_main_file = sanitize_text_field($_POST['plugin_main_file']);

        if (empty($plugin_slug) || empty($plugin_name) || empty($plugin_main_file)) {
            wp_send_json_error(['message' => 'Plugin details are missing.']);
        }

        $plugin_file = WP_PLUGIN_DIR . '/' . $plugin_slug . '/' . $plugin_main_file;

        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        $upgrader = new Plugin_Upgrader();

        if (!file_exists($plugin_file)) {
            $plugin_url = 'https://downloads.wordpress.org/plugin/' . $plugin_slug . '.latest-stable.zip';
            $install_result = $upgrader->install($plugin_url);

            if (is_wp_error($install_result)) {
                wp_send_json_error(['message' => 'Installation error: ' . $install_result->get_error_message()]);
            }

            if (file_exists($plugin_file)) {
                $activation = activate_plugin($plugin_slug . '/' . $plugin_main_file);
                if (is_wp_error($activation)) {
                    wp_send_json_error(['message' => 'Activation error: ' . $activation->get_error_message()]);
                }
                wp_send_json_success(['message' => 'Plugin installed and activated successfully.']);
            } else {
                wp_send_json_error(['message' => 'Plugin installation failed.']);
            }
        } else {
            // Activate if already installed but not active
            if (!is_plugin_active($plugin_file)) {
                $activation = activate_plugin($plugin_slug . '/' . $plugin_main_file);
                if (is_wp_error($activation)) {
                    wp_send_json_error(['message' => 'Activation error: ' . $activation->get_error_message()]);
                }
            }
            wp_send_json_success(['message' => 'Plugin is already installed and activated.']);
        }
    }

    public function fleximp_install_activate_theme()
    {
        check_ajax_referer('fleximp_nonce', 'security');

        if (!current_user_can('switch_themes')) {
            wp_send_json_error(['message' => 'You do not have permission to install or activate themes.']);
        }

        $theme_slug = sanitize_key($_POST['theme_slug'] ?? '');

        if (empty($theme_slug)) {
            wp_send_json_error(['message' => 'Theme slug is missing.']);
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
        require_once ABSPATH . 'wp-admin/includes/theme.php';

        WP_Filesystem();

        $installed_themes = wp_get_themes();

        if (!isset($installed_themes[$theme_slug])) {
            $theme_zip_url  = 'https://downloads.wordpress.org/theme/' . $theme_slug . '.latest-stable.zip';
            $skin           = new WP_Ajax_Upgrader_Skin();
            $upgrader       = new Theme_Upgrader($skin);
            ob_start();
            $install_result = $upgrader->install($theme_zip_url);
            ob_get_clean();

            if (is_wp_error($install_result)) {
                wp_send_json_error(['message' => 'Theme installation failed: ' . $install_result->get_error_message()]);
            }

            if ($skin->get_errors()->has_errors()) {
                wp_send_json_error(['message' => 'Theme installation failed: ' . $skin->get_errors()->get_error_message()]);
            }

            if ($install_result !== true) {
                wp_send_json_error(['message' => 'Theme installation failed.']);
            }
        }

        switch_theme($theme_slug);

        $active = wp_get_theme();
        if ($active->get('TextDomain') !== $theme_slug && $active->get_stylesheet() !== $theme_slug) {
            wp_send_json_error(['message' => 'Theme installed but could not be activated.']);
        }

        wp_send_json_success(['message' => 'Theme installed and activated successfully.', 'theme_slug' => $theme_slug]);
    }

    //changes start from here for dashboard
    public function fleximp_display_dashboard_page()
    { ?>
        <div class="container-fluid flex-imp-nav-box" style="margin-top:30px;">
            <div class="row w-100">


                <div class="col-xl-12 col-sm-12 col-12 flex-container-1 align-self-center">
                    <div class="row flex-import-logo-box">
                        <div class="col-xl-1 col-lg-2 col-sm-2 col-4 pl-0 pr-0">
                            <div class="flex-dash-plugin-logo  ">
                                <img src="<?php echo esc_url(FLEXIMP_PLUGIN_DIR_FILE . 'assets/images/flex-logo.svg'); ?>"
                                    alt="<?php esc_attr_e('Plugin Logo', 'flex-import'); ?>" class="logo-img">
                            </div>
                        </div>

                        <div class="col-xl-9 col-lg-7 col-sm-7 col-12 p-sm-0 pt-sm-0 pt-3 align-self-center">
                            <div>
                                <ul class="nav nav-tabs mr-auto flex-nav-tab-links" role="tablist">
                                    <li class="nav-item flex-icons ">
                                        <a class="nav-link" data-toggle="tab" href="#dashboard">
                                            <?php esc_html_e('Dashboard', 'flex-import'); ?>
                                        </a>
                                    </li>
                                    <li class="nav-item flex-icons">
                                        <a class="nav-link active" data-toggle="tab" href="#free-templates">
                                            <?php esc_html_e('Free Templates', 'flex-import'); ?>
                                        </a>
                                    </li>
                                    <li class="nav-item flex-icons ">
                                        <a class="nav-link" data-toggle="tab" href="#templates">
                                            <?php esc_html_e('Pro Templates', 'flex-import'); ?>
                                        </a>
                                    </li>
                                    <li class="nav-item flex-icons">
                                        <a class="nav-link" data-toggle="tab" href="#plugins">
                                            <?php esc_html_e('Plugins', 'flex-import'); ?>
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </div>

                        <div
                            class="col-xl-2 col-lg-3 col-sm-3 text-right flex-demo-btns mt-sm-0 mt-3 mb-sm-0 mb-3 align-self-center">
                            <?php
                            $is_premium_user = get_option('fleximp_is_premium', false);
                            if (!$is_premium_user) {
                                ?>
                                <div class="ml-auto flex-demo-buttons">
                                    <a href="<?php echo htmlspecialchars(FLEXIMP_UPGRADE_PRO_URL, ENT_QUOTES, 'UTF-8'); ?>"
                                        class="btn flex-demo-btn flex-btn-space" target="_blank" rel="noopener">
                                        <img src="<?php echo esc_url(FLEXIMP_PLUGIN_DIR_FILE . 'assets/images/pro.png'); ?>"
                                            alt="<?php esc_attr_e('Plugin Logo', 'flex-import'); ?>" style="">
                                        <?php esc_html_e('Get Bundle', 'flex-import'); ?>
                                    </a>
                                </div>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Tab Content -->
        <div class="tab-content mt-3">
            <div id="dashboard" class="tab-pane fade">
                <?php include FLEXIMP_PLUGIN_FILE . '/templates/dashboard-content.php'; ?>
            </div>
            <div id="free-templates" class="tab-pane fade show active fleximp-template-main-box fleximp-free-template-main-box">
                <?php include FLEXIMP_PLUGIN_FILE . '/templates/free-templates-content.php'; ?>
            </div>
            <div id="templates" class="tab-pane fade fleximp-template-main-box">
                <?php include FLEXIMP_PLUGIN_FILE . '/templates/templates-content.php'; ?>
            </div>
            <div id="plugins" class="tab-pane fade fleximp-plugin-main-box">
                <?php include FLEXIMP_PLUGIN_FILE . '/templates/plugins-content.php'; ?>
            </div>
        </div>
    <?php }

    //changes end from here for bootstrap
    public function fleximp_enqueue_admin_assets()
    {
        wp_enqueue_style('fleximp-dashboard-banner', FLEXIMP_PLUGIN_DIR_FILE . 'assets/css/dashboard-banner.css', array(), FLEXIMP_VER);

        $screen = get_current_screen();
        if ($screen->id === 'toplevel_page_fleximp-template-importer') {
            wp_enqueue_style('fleximp-admin-styles', FLEXIMP_PLUGIN_DIR_FILE . 'assets/css/admin-style.css', array(), FLEXIMP_VER);
            wp_enqueue_style('bootstrap-css', FLEXIMP_PLUGIN_DIR_FILE . 'assets/lib/bootstrap.min.css', [], FLEXIMP_VER);
            wp_enqueue_script('bootstrap-js', FLEXIMP_PLUGIN_DIR_FILE . 'assets/lib/bootstrap.min.js', ['jquery'], FLEXIMP_VER, true);
            wp_enqueue_style('flex-swiper-css', FLEXIMP_PLUGIN_DIR_FILE . 'assets/lib/swiper-bundle.min.css', array(), FLEXIMP_VER);
            wp_enqueue_script('flex-swiper-js', FLEXIMP_PLUGIN_DIR_FILE . 'assets/lib/swiper-bundle.min.js', ['jquery'], FLEXIMP_VER, true);
            wp_enqueue_script('fleximp-admin-scripts', FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/admin-script.js', array('jquery'), FLEXIMP_VER, true);
            wp_enqueue_style('font-awesome', FLEXIMP_PLUGIN_DIR_FILE . 'assets/lib/all.min.css', [], FLEXIMP_VER);

            $is_premium_theme = defined('GET_PREMIUM_THEME');

            wp_localize_script('fleximp-admin-scripts', 'fleximp_admin_ajax_object', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'fleximp_nonce' => wp_create_nonce('fleximp_quick_setup_nonce'),
                'plugin_url' => plugins_url('', __FILE__),
                'is_premium_theme' => $is_premium_theme
            ));

            //for plugin
            wp_enqueue_script(
                'fleximp-plugin-js',
                FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/plugin-admin.js',
                array('jquery'),
                FLEXIMP_VER,
                true
            );

            wp_localize_script('fleximp-plugin-js', 'fleximp_ajax_object', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'fleximp_nonce' => wp_create_nonce('fleximp_quick_setup_nonce'),
                'plugin_url' => plugins_url('', __FILE__),
                'apiEndpoint' => FLEXIMP_PLUGIN_DIR_FILE . 'includes/flex-get-api.php',
            ));
            //end

            //for templates 
            wp_enqueue_script(
                'fleximp-template-js',
                FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/template-admin.js',
                array('jquery'),
                FLEXIMP_VER,
                true
            );

            $is_elementor_active = is_plugin_active('elementor/elementor.php');

            // Get active theme data
            $theme = wp_get_theme();
            $theme_author = $theme->get('Author');
            $theme_domain = $theme->get('TextDomain');

            // Detect free Flex theme via constant e.g. FLEX_BLOGGING_LIVE_DEMO
            $free_theme_constant = strtoupper( str_replace( [ '-', ' ' ], '_', $theme_domain ) ) . '_LIVE_DEMO';
            $is_free_flex_theme  = defined( $free_theme_constant );

            wp_localize_script('fleximp-template-js', 'fleximp_template_ajax_object', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'fleximp_nonce' => wp_create_nonce('fleximp_nonce'),
                'apiEndpoint' => FLEXIMP_PLUGIN_DIR_FILE . 'includes/flex-get-templates-api.php',
                'isPremiumUser' => get_option('fleximp_is_premium', false),
                'is_Bundle' => get_option('fleximp_is_bundle', false),
                'themes_redirect_page_url' => admin_url('theme-install.php?browse=popular'),
                'imported_template' => get_option('flex_template_is_imported', ''),
                'pro_image_url' => FLEXIMP_PLUGIN_DIR_FILE . 'assets/images/pro.png',
                'fleximp_dynamic_text_domain' => get_option('fleximp_current_text_domain'),
                'fleximp_current_text_domain' => wp_get_theme()->get('TextDomain'),
                'isElementorActive' => $is_elementor_active ? '1' : '0',
                'active_theme_author' => $theme_author,
                'is_free_flex_theme'  => $is_free_flex_theme,
                'installed_theme_slugs' => array_keys( wp_get_themes() ),
            ));
            //end

            //for free templates
            wp_enqueue_script(
                'fleximp-free-template-js',
                FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/free-template-admin.js',
                array('jquery', 'fleximp-template-js'),
                FLEXIMP_VER,
                true
            );
            //end

            //for dashboard
            wp_enqueue_script(
                'fleximp-dashposts-js',
                FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/dashboard-posts.js',
                array('jquery'),
                FLEXIMP_VER,
                true
            );

            wp_localize_script('fleximp-dashposts-js', 'fleximp_dashposts_ajax_object', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'fleximp_nonce' => wp_create_nonce('fleximp_nonce'),
                'apiEndpoint' => FLEXIMP_PLUGIN_DIR_FILE . 'includes/flex-dashboard-post-api.php',
            ));
        }
    }

    //for license key 

    public function fleximp_verify_license()
    {
        $license_key = sanitize_text_field($_POST['fleximp_license_key']);
        $endpoint = WPEI_SHOPIFY_LICENCE_ENDPOINT . 'verifyTheme';

        $body = json_encode([
            'theme_license_key' => $license_key,
            'site_url' => site_url(),
            'theme_text_domain' => wp_get_theme()->get('TextDomain'),
        ]);

        $response = wp_remote_post($endpoint, [
            'body' => $body,
            'headers' => ['Content-Type' => 'application/json']
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => 'Connection error.']);
            return;
        }

        $response_body = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($response_body['is_suspended']) && $response_body['is_suspended'] == 1) {
            wp_send_json_error(['message' => 'License is suspended.']);
            return;
        }

        if (isset($response_body['status']) && $response_body['status'] === true) {
            update_option('fleximp_plugin_license_key', $license_key);
            update_option('fleximp_plugin_license_validation_status', 'true');
            wp_send_json_success(['message' => 'License activated successfully!']);
        } else {
            $error_message = isset($response_body['message']) ? $response_body['message'] : 'License activation failed. Please try again.';
            wp_send_json_error(['message' => $error_message]);
        }
    }
    //end

    public function fleximp_import_demo_content()
    {

        if (!current_user_can('manage_options')) {
            wp_send_json_error(__('You do not have permission to import demo content.', 'flex-import'));
        }

        if (!is_plugin_active('elementor/elementor.php')) {
            wp_send_json_error(__('Elementor must be installed and activated before importing demo content.', 'flex-import'));
        }

        $text_domain = isset($_POST['text_domain']) ? sanitize_text_field($_POST['text_domain']) : 'flex-import';

        $import_success = $this->fleximp_elementor_importer_setup_pages();

        if ($import_success) {
            update_option('flex_template_is_imported', $text_domain);
            wp_send_json_success(__('imported successfully!', 'flex-import'));
        } else {
            wp_send_json_error(__('Error occurred during the import process.', 'flex-import'));
        }

        wp_die();
    }

    public function fleximp_elementor_importer_setup_pages()
    {
        $active_theme = wp_get_theme();
        $active_theme_textdomain = $active_theme->get('TextDomain');

        $pages_arr = [];
        $imported_pages = 0;

        $fallback_json_url = isset($_POST['json_path']) ? sanitize_text_field($_POST['json_path']) : FLEXIMP_MAIN_URL . '/themes-json/multipurpose-business/multipurpose-business.json';
        $fallback_content = $this->fetch_remote_content($fallback_json_url);

        if ($fallback_content) {
            $fallback_data = json_decode($fallback_content, true);
            if ($fallback_data) {
                foreach ($fallback_data as $page) {
                    $pages_arr[] = [
                        'title' => $page['name'],
                        'ishome' => ($page['type'] === 'home') ? 1 : 0,
                        'post_type' => $page['posttype'],
                        'source' => $page['source'],
                        'type' => $page['type']
                    ];
                }
            }
        }

        foreach ($pages_arr as $page) {
            $page_content_response = wp_remote_get($page['source']);

            if (is_wp_error($page_content_response) || wp_remote_retrieve_response_code($page_content_response) !== 200) {
                continue;
            }

            $page_content_arr = isset($page['content']) ? ['content' => $page['content']] : json_decode(wp_remote_retrieve_body($page_content_response), true);

            if ($page_content_arr === null || !isset($page_content_arr['content'])) {
                continue;
            }

            $post_data = [
                'post_title' => $page['title'],
                'post_type' => $page['post_type'],
                'post_status' => 'publish',
                'post_author' => get_current_user_id(),
                'post_content' => '',
            ];

            $post_id = wp_insert_post($post_data);

            if (is_wp_error($post_id)) {
                continue;
            }
            update_post_meta($post_id, '_elementor_data', wp_slash(wp_json_encode($page_content_arr['content'])));
            update_post_meta($post_id, '_elementor_edit_mode', 'builder');

            if ($page['post_type'] === 'elementskit_template') {

                update_post_meta($post_id, '_wp_page_template', 'elementor_canvas');
                $template_type = $page['type'] === 'header' ? 'header' : ($page['type'] === 'footer' ? 'footer' : 'general');
                update_post_meta($post_id, 'elementskit_template_activation', 'yes');
                update_post_meta($post_id, 'elementskit_template_type', $template_type);
                update_post_meta($post_id, 'elementskit_template_condition_a', 'entire_site');
            }

            update_post_meta($post_id, '_wp_page_template', 'elementor_header_footer');

            // Set homepage if applicable
            if ($page['ishome'] === 1) {
                update_option('page_on_front', $post_id);
                update_option('show_on_front', 'page');
            }

            $imported_pages++;
        }

        return $imported_pages > 0;
    }
    // end 

    private function get_free_themes_text_domain()
    {
        $api_url = WPEI_SHOPIFY_LICENCE_ENDPOINT . 'get_elemento_themes_array_records_datatable';
        $options = ['headers' => ['Content-Type' => 'application/json']];
        $response = wp_remote_get($api_url, $options);
        $wpei_free_text_domain = [];
        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) == 200) {
            $json = json_decode(wp_remote_retrieve_body($response), true);

            if (is_array($json)) {
                foreach ($json as $value) {
                    if (is_array($value)) {
                        foreach ($value as $values) {
                            if (is_array($values) && isset($values['theme_domain_array'])) {
                                $get_all_domains = $values['theme_domain_array'];
                                array_push($wpei_free_text_domain, $get_all_domains);
                            } elseif (is_object($values) && isset($values->theme_domain_array)) {
                                $get_all_domains = $values->theme_domain_array;
                                array_push($wpei_free_text_domain, $get_all_domains);
                            }
                        }
                    }
                }
            }
        }

        return $wpei_free_text_domain;
    }

    // Function to fetch theme data from API
    private function get_theme_data()
    {
        $endpoint = WPEI_SHOPIFY_LICENCE_ENDPOINT . 'get_elemento_themes_records';
        $options = ['headers' => ['Content-Type' => 'application/json']];
        $response = wp_remote_get($endpoint, $options);

        if (is_wp_error($response)) {
            return ['status' => 100, 'msg' => 'Something went wrong!', 'data' => []];
        } else {
            $response_body = wp_remote_retrieve_body($response);
            $response_data = json_decode($response_body);
            return ['status' => 200, 'msg' => 'Theme data retrieved', 'data' => $response_data->data];
        }
    }

    // Function to fetch remote content
    private function fetch_remote_content($url)
    {
        $response = wp_remote_get($url);
        if (is_wp_error($response)) {
            return false;
        }
        return wp_remote_retrieve_body($response);
    }


    //uninstall template
    public function fleximp_uninstall_template()
    {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => 'You do not have permission to uninstall.']);
        }

        $fleximp_current_text_domain = get_option('fleximp_current_text_domain', true);
        $fleximp_get_home = get_option('page_on_front', true);

        delete_option('flex_template_is_imported');
        delete_option('fleximp_current_text_domain');
        delete_option('fleximp_dynamic_template_php');
        delete_option('fleximp_dynamic_template_js');
        delete_option('fleximp_dynamic_template_css');
        delete_option('fleximp_current_template_mobile_image');
        delete_option('fleximp_current_template_title');

        wp_delete_post($fleximp_get_home, true);
        delete_option('page_on_front');

        // for hf
        $templates = get_posts([
            'post_type' => 'elementskit_template',
            'numberposts' => -1,
            'post_status' => 'any',
        ]);

        if (!empty($templates)) {
            foreach ($templates as $template) {
                wp_delete_post($template->ID, true);
            }
        }

        // for page
        $elementor_pages = get_posts([
            'post_type' => 'page',
            'numberposts' => -1,
            'post_status' => 'any',
            'meta_query' => [
                [
                    'key' => '_elementor_edit_mode',
                    'compare' => 'EXISTS',
                ],
            ],
        ]);

        if (!empty($elementor_pages)) {
            foreach ($elementor_pages as $page) {
                wp_delete_post($page->ID, true);
            }
        }


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

        global $wp_filesystem;
        WP_Filesystem();

        if (!empty($fleximp_current_text_domain)) {
            $upload_dir = wp_upload_dir();
            $temp_template = $upload_dir['basedir'] . '/' . $fleximp_current_text_domain . '.php';
            if (file_exists($temp_template)) {
                if (!$wp_filesystem->put_contents($temp_template, '', FS_CHMOD_FILE)) {
                    wp_send_json_error(['message' => 'Something went wrong!']);
                }
            }
        }


        wp_send_json_success(['message' => 'Plugins deactivated, content deleted successfully.']);
    }


}
