<?php
namespace Phox\import;

use Phox\import\demo\CasualPro_Demo;
use function Phox_Host\phox_host_core;

/**
 * Demo Import
 * This configuration file that will use one click import plugin
 * to show the demo in it
 *
 * @package Phox
 * @author WHMCSdes
 * @link https://whmcsdes.com
 */


if( !defined('ABSPATH') ) {
    exit;
}

Class Demo_Import {
    /**
     * Instance .
     *
     * @var Demo_Import
     */
    protected static $_instance = null;
    /**
     * @var false|mixed
     */
    private $select_imp;

    /**
     * Get demo Import instance .
     *
     * @return Demo_Import
     */
    public static function instance() {

        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }

        return self::$_instance;

    }

    public $demo ;

    /**
     * Current demo being imported
     *
     * @var array|null
     */
    private $current_demo = null;

    /**
     * Extracted demo files directory
     *
     * @var string|null
     */
    private $extracted_dir = null;

    public function __construct() {

        if( ! (is_admin() || ( defined('WP_CLI') && WP_CLI ) ) ){
            return false;
        }

        $this->select_imp = false;

        $this->demo = [

            new demo\Primary_Demo ,
            new demo\Modern_Demo  ,
            new demo\Super_Demo   ,
            new demo\Startup_Demo,
            new demo\Saas_Demo,
            new demo\WoHost_Demo,
            new demo\Classy_Demo,
            new demo\Shiny_Demo,
            new demo\Go_Demo,
            new demo\Fancy_Demo,
            new demo\Moon_Demo,
            new demo\RTL_Demo,
            new demo\Cheap_Demo,
            new demo\IPhox_Demo,
            new demo\PhoxUp_Demo,
            new demo\Games_Demo,
            new demo\Space_Demo,
            new demo\Neat_Demo,
            new demo\ClassyPro_Demo,
            new demo\Host_Demo,
            new demo\Galaxy_Demo,
            new demo\Express_Demo,
            new demo\Cloudy_Demo,
            new demo\Temple_Demo,
            new demo\Extreme_Demo,
            new demo\Edge_Demo,
            new demo\GoPro_Demo,
            new demo\SpacePro_Demo,
            new demo\Casual_Demo,
            new demo\SaasPro_Demo,
            new demo\Ocean_Demo,
            new demo\Monster_Demo,
            new demo\MonsterLight_Demo,
            new demo\FancyPro_Demo,
            new demo\Trendy_Demo,
            new demo\Cloudora_Demo,
            new demo\Natural_Demo,
            new demo\LiquidGlass_Demo,
            new CasualPro_Demo,
        ];

        //Fix [WARNING] Could not find the author for ... log warning messages when use wp cli
        if( defined('WP_CLI') && WP_CLI ){

            wp_set_current_user( 1 );

        }

        add_filter('ocdi/plugin_page_setup', array($this, 'plugin_page_setup'), 30 );
        add_filter('ocdi/import_files', array( $this, 'set_import_files' ),1 );
        add_action('ocdi/after_import', array($this, 'after_import'),10,1 );
        add_action('ocdi/before_content_import_execution', array($this, 'before_import'), 10, 3);
        add_action('ocdi/time_for_one_ajax_call', array($this, 'change_time_of_single_ajax_call') );
        add_action('ocdi/after_content_import_execution', [$this, 'get_info_about_import'],10,4);
        add_filter('ocdi/before_widgets_import_data', [$this, 'widgets_import'], 10, 4);
        add_filter('ocdi/register_plugins', [$this, 'register_plugins']);
        add_filter('ocdi/pre_download_import_files', array($this, 'download_and_extract_demo_zip'));
        add_action('ocdi/after_all_import_execution', array($this, 'cleanup_demo_files'), 20, 3);
    }

    public function plugin_page_setup($page){

        //show in theme menu
        $page['menu_title']		= 'Demo Import';
        $page['capability']		= 'edit_theme_options';
        $page['menu_slug']		= 'wdes-demo-import';

        return $page;

    }

    public function after_import($selected_import){
        $locations = get_theme_mod('nav_menu_locations');
        $menus = wp_get_nav_menus();

        if( $menus ) {
            foreach ($menus as $menu ) {

                if( $menu->name == 'Menu 1' || $menu->name == 'startup' || $menu->name == 'wohost-main' || $menu->name == 'classy-main' ) {
                    $locations['main-menu'] = $menu->term_id;
                }

                if( $menu->name == 'startup-top' || $menu->name == 'host-header' || $menu->name == 'wohost-top' || $menu->name == 'classy-top' ) {
                    $locations['header-secondary'] = $menu->term_id;
                }

                if( $menu->name == 'startup-foot' || $menu->name == 'host-footer' || $menu->name == 'wohost-foot' || $menu->name == 'classy-foot' ) {
                    $locations['footer'] = $menu->term_id;
                }

            }

            set_theme_mod('nav_menu_locations', $locations);

            if(is_rtl()){

                $front_page_id = $this->get_page_by_title('الرئيسية');
                $blog_page_id  = $this->get_page_by_title('المدونة');

            }else{
                $front_page_id = $this->get_page_by_title('Home');
                $blog_page_id  = $this->get_page_by_title('Blog');
            }


            update_option('show_on_front', 'page');

            if( is_object($front_page_id) ){
                update_option('page_on_front', $front_page_id->ID);
            }

            if(is_object($blog_page_id)){
                update_option('page_for_posts', $blog_page_id->ID);
            }

            do_action( sprintf( 'wdes/demo-import/%s/after-import', $selected_import['demo_id'] ), $selected_import );


        }

        $conditions = ['condition_header', 'condition_footer', 'condition_popup'];

        for( $index = 0; $index < count($conditions); $index++ ){

            $condition_id = $selected_import[ $conditions[ $index ] ] ?? false;

            if( ! is_bool( $condition_id )  ) {

                $this->add_conditions($condition_id);

            }

        }


    }

    public function set_import_files(){

        return apply_filters( 'wdes/demo-import/files', [], $this );

    }

    public function before_import( $selected_import_files, $import_files, $selected_index ) {

        $demo = is_array( $import_files ) && isset( $import_files[ $selected_index ] ) ? $import_files[ $selected_index ] : false;
        if ( ! is_array( $demo ) || empty( $demo['demo_id'] ) ) {
            return;
        }

    }

    /**
     * Get info about import
     *
     * set information about import file to use in widget_import function
     *
     * @param $selected_import_files
     * @param $import_files
     * @param $selected_index
     */
    public function get_info_about_import($selected_import_files, $import_files, $selected_index){
        $demo = is_array( $import_files ) && isset( $import_files[ $selected_index ] ) ? $import_files[ $selected_index ] : false;

        $this->select_imp = $demo;
    }

    /**
     * Before Widget Import
     * check all links in widget and replace it
     * it work with all demos
     *
     * @since 1.5.7
     * @param $import_files
     * @return mixed
     */
    public function widgets_import($import_files){
        $import_files = apply_filters( sprintf( 'wdes/demo-import/%s/before_widgets_import_data', $this->select_imp['demo_id'] ), $import_files );
        return $import_files;
    }



    /**
     * Change Time Of Single Ajax Call
     * it increase time to 180 second to solve the problem with low server
     *
     * @since 1.4.4
     * @return int
     */
    public function change_time_of_single_ajax_call() {

        return 180;

    }

    /**
     * register the require plugins
     * this plugins if not install the one click import must tell use to must install it to can use the demo
     *
     * @since 1.7.4
     * @return array
     */
    public function register_plugins(){

        $demo_id = isset($_GET['import']) ? $_GET['import'] : false;

        $require_plugins = [
            [
                'name'        => esc_html__( 'Phox Host', 'phox' ),
                'description' => esc_html__( 'The Core Plugin for Phox', 'phox' ),
                'slug'        => 'phox-host',
                'required'    => true,
                'preselected' => true,
                'source'      => WDES_INC_DIR . '/core/admin/tgm/plugins/phox-host.zip'
            ],[
                'name'        => esc_html__( 'Elementor', 'phox' ),
                'description' => esc_html__( 'The Elementor Website Builder has it all: drag and drop page builder, pixel perfect design, mobile responsive editing, and more. Get started now!', 'phox' ),
                'slug'        => 'elementor',
                'required'    => true,
                'preselected' => true,
            ],
            [
                'name'        => esc_html__( 'Contact Form 7', 'phox' ),
                'description' => esc_html__( 'Just another contact form plugin. Simple but flexible.', 'phox' ),
                'slug'        => 'contact-form-7',
                'required'    => true,
                'preselected' => true,
            ],

        ];

        if($demo_id == '3' || $demo_id == '5'){

            $args = [
                'user-agent'  => 'WordPress/'. get_bloginfo('version') .'; '.network_site_url(),
                'timeout'     => 30,
            ];

            $response = wp_remote_get( 'https://whmcsdes.com/phoxplugin/plugins.php?version='.WDES_THEME_VERSION, $args );

            if( is_wp_error( $response ) ){
                return $response ;
            }

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

            if( is_array( $slider_plugins ) ){
                $slider_plugins[0]['description'] = esc_html__( 'Slider Revolution - Premium responsive slider.', 'phox' );

                $slider_plugins[0]['preselected'] = true;

                $require_plugins[] = $slider_plugins[0];
            }

        }

        return $require_plugins;

    }

    public function add_conditions(int $post_id){

        if( function_exists( 'Phox_Host\phox_host_core' ) ){

            phox_host_core()->theme_builder_condition->update_post_conditions($post_id);

        }

    }

    public function get_page_by_title($title)
    {

        $page_query = new \WP_Query(
            [
                'post_type' => 'page',
                'title'     => $title,
            ]
        );

        return $page_query->post;
    }

    /**
     * Download and Extract Demo ZIP File
     *
     * Downloads a single ZIP file containing all demo files (XML, WIE, JSON)
     * and extracts them to the uploads directory
     *
     * This runs via the ocdi/pre_download_import_files filter, which passes
     * the selected demo configuration right before OCDI starts downloading files
     *
     * @since 2.5.0
     * @param array $selected_import Selected demo import configuration
     * @return array Modified import configuration with local file paths
     */
    public function download_and_extract_demo_zip($selected_import) {

        if (empty($selected_import) || !is_array($selected_import)) {
            return $selected_import;
        }

        // Skip if no zip URL is provided
        if (empty($selected_import['import_zip_url'])) {
            return $selected_import;
        }

        $demo_id = $selected_import['demo_id'] ?? 'unknown';

        // Create upload directory for this demo
        $upload_dir = wp_upload_dir();
        $phox_import_dir = trailingslashit($upload_dir['basedir']) . 'phox-demo-import';
        $demo_dir = $phox_import_dir . '/' . $demo_id;

        // Remove existing phox-demo-import folder if it exists (clean start)
        if (file_exists($phox_import_dir)) {
            WP_Filesystem();
            global $wp_filesystem;
            $wp_filesystem->delete($phox_import_dir, true);
            error_log('Phox Demo Import: Removed existing phox-demo-import folder for clean start');
        }

        // Create directory
        wp_mkdir_p($demo_dir);

        // Download ZIP file
        $zip_file = $demo_dir . '/demo.zip';
        $response = wp_remote_get($selected_import['import_zip_url'], [
            'timeout' => 300, // 5 minutes timeout for large files
            'stream' => true,
            'filename' => $zip_file
        ]);

        if (is_wp_error($response)) {
            error_log('Phox Demo Import: Failed to download ZIP for ' . $demo_id . ' - ' . $response->get_error_message());
            return $selected_import;
        }

        // Verify the file was downloaded
        if (!file_exists($zip_file)) {
            error_log('Phox Demo Import: ZIP file not found after download for ' . $demo_id);
            return $selected_import;
        }

        // Extract ZIP file
        WP_Filesystem();
        global $wp_filesystem;

        $unzip_result = unzip_file($zip_file, $demo_dir);

        if (is_wp_error($unzip_result)) {
            error_log('Phox Demo Import: Failed to extract ZIP for ' . $demo_id . ' - ' . $unzip_result->get_error_message());
            @unlink($zip_file);
            return $selected_import;
        }

        // Update demo configuration to use local files (not remote URLs)
        $selected_import['local_import_file'] = $demo_dir . '/content.xml';
        $selected_import['local_import_widget_file'] = $demo_dir . '/widget.wie';
        $selected_import['import_theme_options_file'] = $demo_dir . '/theme-options.json';

        return $selected_import;
    }

    /**
     * Cleanup Demo Files
     *
     * Removes the entire phox-demo-import folder after import completes
     *
     * @since 2.5.0
     * @param array $selected_import Selected import configuration with file paths
     * @param array $import_files All import files
     * @param int|string $predefined_demo Predefined demo index
     * @return void
     */
    public function cleanup_demo_files($selected_import, $import_files, $predefined_demo) {

        // Extract phox-demo-import directory from the content file path
        // $selected_import['content'] = '/path/to/uploads/phox-demo-import/primary-demo/content.xml'
        // We need to get: '/path/to/uploads/phox-demo-import'

        $phox_import_dir = null;

        if (!empty($selected_import['content'])) {
            // Get parent directory of demo folder (phox-demo-import)
            $demo_dir = dirname($selected_import['content']);
            $phox_import_dir = dirname($demo_dir);
        } elseif (!empty($selected_import['widgets'])) {
            // Fallback to widgets file path
            $demo_dir = dirname($selected_import['widgets']);
            $phox_import_dir = dirname($demo_dir);
        }

        if (empty($phox_import_dir) || !file_exists($phox_import_dir)) {
            error_log('Phox Demo Import: Unable to determine phox-demo-import directory for cleanup');
            return;
        }

        // Verify we're deleting the correct folder (safety check)
        if (basename($phox_import_dir) !== 'phox-demo-import') {
            error_log('Phox Demo Import: Safety check failed - not deleting ' . $phox_import_dir);
            return;
        }

        // Initialize WordPress filesystem
        WP_Filesystem();
        global $wp_filesystem;

        // Delete the entire phox-demo-import directory (includes all demos, ZIPs, and extracted files)
        $deleted = $wp_filesystem->delete($phox_import_dir, true);

        if ($deleted) {
            error_log('Phox Demo Import: Cleaned up phox-demo-import folder from ' . $phox_import_dir);
        } else {
            error_log('Phox Demo Import: Failed to clean up phox-demo-import folder from ' . $phox_import_dir);
        }
    }

    /**
     * Get Local Theme Options File Path
     *
     * Returns the path to the extracted theme options JSON file
     * Used by Demo classes to load theme options
     *
     * @since 2.5.0
     * @param string $demo_id Demo identifier
     * @return string|false File path or false if not found
     */
    public function get_theme_options_file_path($demo_id) {

        $upload_dir = wp_upload_dir();
        $file_path = trailingslashit($upload_dir['basedir']) . 'phox-demo-import/' . $demo_id . '/theme-options.json';

        if (file_exists($file_path)) {
            return $file_path;
        }

        return false;
    }

}
