<?php
/**
* 
* @package tx
* @author theme-x
* @link https://theme-x.org/
* ======================================================================
*   Demo Data Import 
* ======================================================================
*/

// Demo instruction
if ( ! function_exists( 'tx_plugin_intro_text' ) ) :
  function tx_plugin_intro_text() {
  
    $default_text = '<div class="tx-demo-instructon">';
    $default_text .= '<h3 style="color:#e84d3e;">&#8594; Important Instruction:</h3>';
    $default_text .= '<p>&#9957; Best if used on new WordPress install.</p>';
    $default_text .= '<p>&#9957; If you plan to import more than one demo then please clear the existing demo before import the new demo. You can use the "WP Reset" plugin to reset everything.</p>';
    $default_text .= '<p>&#9957; If the import process gets stuck, please reload the page and click the "Continue & Import" button again.</p>';
    $default_text .= '<p>&#9957; Before start importing demo data please check your server resources to meet our server minimum requirements below.</p>';
    $default_text .= '<h3>System Requirements</h3>';

    // system requirements
    ob_start();
    tx_Welcome_Screen::tx_system_requirements();
    $requirements_output = ob_get_clean();
    $default_text .= $requirements_output;
    $default_text .= '</div>';

    return $default_text;
  }
endif;
add_filter( 'ocdi/plugin_intro_text', 'tx_plugin_intro_text' );

// Demo admin menu
function tx_plugin_page_setup( $default_settings ) {
    $default_settings['page_title']  = esc_html__( 'Avas Demo Data Import' , 'avas' );
    $default_settings['menu_title']  = esc_html__( 'Import Demo Data' , 'avas' );
 
    return $default_settings;
}
add_filter( 'ocdi/plugin_page_setup', 'tx_plugin_page_setup' );

// Demo menu setup
function tx_demo_menu_setup() {
  
          //Set Menu
          $top_menu = get_term_by( 'name', 'Top Menu', 'nav_menu' );
          $main_menu = get_term_by( 'name', 'Main Menu', 'nav_menu' );
          $footer_menu = get_term_by( 'name', 'Footer Menu', 'nav_menu' );
          $left_menu = get_term_by( 'name', 'Left Menu', 'nav_menu' );
          $right_menu = get_term_by( 'name', 'Right Menu', 'nav_menu' );
          $side_menu = get_term_by( 'name', 'Side Menu', 'nav_menu' );
          $mobile_menu = get_term_by( 'name', 'Mobile Menu', 'nav_menu' );
          $locations = array();
          if ( $top_menu )     $locations['top_menu']     = $top_menu->term_id;
          if ( $main_menu )    $locations['main_menu']    = $main_menu->term_id;
          if ( $footer_menu )  $locations['footer_menu']  = $footer_menu->term_id;
          if ( $left_menu )    $locations['left_menu']    = $left_menu->term_id;
          if ( $right_menu )   $locations['right_menu']   = $right_menu->term_id;
          if ( $side_menu )    $locations['side_menu']    = $side_menu->term_id;
          if ( $mobile_menu )  $locations['mobile_menu']  = $mobile_menu->term_id;

          set_theme_mod( 'nav_menu_locations', $locations );
        
        wp_delete_post( 1, true ); // delete Hello world post 

}
add_action('tx_demo_menu_setup', 'tx_demo_menu_setup');

// LearnPress Settings
add_action('tx_learnpress_settings', 'tx_learnpress_settings');
function tx_learnpress_settings() {
  $lp_pages = array(
    'learn_press_courses_page_id' => 'Courses',
    'learn_press_profile_page_id' => 'Profile',
    'learn_press_checkout_page_id'  => 'Checkout',
    'learn_press_become_a_teacher_page_id'  => 'Become A Teacher',
    'learn_press_term_conditions_page_id' => 'Term Conditions',
  );
  foreach( $lp_pages as $lp_page_name => $lp_page_title ) {
    $lp_page = get_page_by_title( $lp_page_title );
      if( isset( $lp_page->ID ) && $lp_page->ID ) {
        update_option($lp_page_name, $lp_page->ID);
      }
  }
  flush_rewrite_rules();
}

// WooCommerce Settings
add_action('tx_woocommerce_settings', 'tx_woocommerce_settings');
function tx_woocommerce_settings() {
      $woopages = array(
        'woocommerce_shop_page_id'      => 'Shop',
        'woocommerce_cart_page_id'     => 'Shopping Cart',
        'woocommerce_checkout_page_id'   => 'Checkout',
        'woocommerce_myaccount_page_id'  => 'My Account'
      );
      foreach( $woopages as $woo_page_name => $woo_page_title ) {
        $woopage = get_page_by_title( $woo_page_title );
        if( isset( $woopage->ID ) && $woopage->ID ) {
          update_option($woo_page_name, $woopage->ID);
        }
      }

      if( class_exists('WC_Admin_Notices') ) {
        WC_Admin_Notices::remove_notice('install');
      }
      delete_transient( '_wc_activation_redirect' );
      
      
      flush_rewrite_rules();
}

// Update WooCommerce Lookup Table
add_action('tx_update_woocommerce_lookup_table', 'tx_update_woocommerce_lookup_table');
function tx_update_woocommerce_lookup_table() {
      if( function_exists('wc_update_product_lookup_tables_is_running') && function_exists('wc_update_product_lookup_tables') ){
        if( !wc_update_product_lookup_tables_is_running() ){
          if( !defined('WP_CLI') ){
            define('WP_CLI', true);
          }
          wc_update_product_lookup_tables();
        }
      }
}

function tx_rev_slider_import( $slider_urls = [] ) {
    if ( ! class_exists( 'RevSlider' ) || empty( $slider_urls ) ) {
        return;
    }

    foreach ( $slider_urls as $slider_url ) {
        // Download the slider zip file to a temp location
        $tmp = download_url( $slider_url );

        if ( is_wp_error( $tmp ) ) {
            error_log('Failed to download slider: ' . $slider_url);
            continue;
        }

        // Import slider using RevSlider class
        try {
            $slider = new RevSlider();
            $slider->importSliderFromPost( true, true, $tmp );
        } catch (Exception $e) {
            error_log('Slider import error: ' . $e->getMessage());
        }

        // Remove temp file
        @unlink( $tmp );
    }
}

// Theme Builder import
function tx_theme_builder_import($tb_url) {
  $encode_options = file_get_contents($tb_url);
  $options = json_decode($encode_options, true);      
            
  foreach ($options as $key => $value) {
    update_option($key, $value);  
  } 

  return $tb_url;

}

// Set frontpage
function tx_get_page_by_title( $page_title, $output = OBJECT ) {
    $args  = array(
        'title'     => $page_title,
        'post_type' => 'page',
    );
    $query = new WP_Query( $args );
    $pages = $query->posts;

    if ( empty( $pages ) ) {
        return null;
    }

    return get_post( $pages[0], $output );
}

/**
 * Set Elementor Active Default Kit
 */
if ( ! function_exists( 'tx_set_elementor_active_kit' ) ) :
  function tx_set_elementor_active_kit() {
      global $wpdb;

      // Find the Default Kit ID
      $default_kit_id = $wpdb->get_var(
          "SELECT ID FROM {$wpdb->posts} WHERE post_type = 'elementor_library' AND post_name = 'default-kit-2'"
      );

      if ( ! $default_kit_id ) {
          wp_die( 'Default Kit not found.' );
      }

      // Update the active kit option in the database
      update_option( 'elementor_active_kit', $default_kit_id );
     
  }
endif;


// Run after demo import to regenerate Elementor CSS/data and clear common caches.
function tx_after_demo_import_clear_elementor_cache() {

    // Only run in admin where import runs
    if ( ! is_admin() ) {
        return;
    }

    // Wait until Elementor has loaded
    if ( did_action( 'elementor/loaded' ) ) {
        // Regenerate Elementor CSS and clear its files/data cache
        try {
            \Elementor\Plugin::instance()->files_manager->clear_cache();
        } catch ( Throwable $e ) {
            error_log( 'Elementor clear_cache error: ' . $e->getMessage() );
        }
    }

    // Clear WP object cache / transient cache
    if ( function_exists( 'wp_cache_flush' ) ) {
        wp_cache_flush();
    }

    // Try to clear popular caching plugins (safe-guarded)
    if ( function_exists( 'rocket_clean_domain' ) ) {
        // WP Rocket
        rocket_clean_domain();
    }
    if ( function_exists( 'w3tc_flush_all' ) ) {
        // W3 Total Cache
        w3tc_flush_all();
    }
    if ( function_exists( 'litespeed_purge_all' ) ) {
        // LiteSpeed Cache
        litespeed_purge_all();
    }
    if ( function_exists( 'wp_cache_clear_cache' ) ) {
        // WP Super Cache variant
        wp_cache_clear_cache();
    }

}



/**
 * Get plugin configuration for each demo
 * Returns an array of required plugins for the given demo name
 */
function tx_get_demo_plugins( $demo_name ) {
    
    // Base plugins required for all demos
    $base_plugins = [
        [
            'name'     => esc_html__( 'Elementor', 'avas' ),
            'slug'     => 'elementor',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'Contact Form 7', 'avas' ),
            'slug'     => 'contact-form-7',
            'required' => true,
        ],
    ];

    // Elementor plugin only demo
    $elementor = [
        [
            'name'     => esc_html__( 'Elementor', 'avas' ),
            'slug'     => 'elementor',
            'required' => true,
        ]
    ];

    // Revolution Slider plugin
    $revslider = [
        'name'     => esc_html__( 'Slider Revolution', 'avas' ),
        'slug'     => 'revslider',
        'source'   => 'https://avas.live/revslider/revslider.zip',
        'required' => true,
    ];

    // Mailchimp plugin
    $mailchimp = [
        'name'     => esc_html__( 'MC4WP: Mailchimp for WordPress', 'avas' ),
        'slug'     => 'mailchimp-for-wp',
        'required' => true,
    ];



    // WooCommerce plugins
    $woocommerce_plugins = [
        [
            'name'     => esc_html__( 'Woocommerce', 'avas' ),
            'slug'     => 'woocommerce',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'WPC Smart Quick View for WooCommerce', 'avas' ),
            'slug'     => 'woo-smart-quick-view',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'WPC Smart Wishlist for WooCommerce', 'avas' ),
            'slug'     => 'woo-smart-wishlist',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'WPC Smart Compare for WooCommerce', 'avas' ),
            'slug'     => 'woo-smart-compare',
            'required' => true,
        ],
    ];

    // LearnPress plugins
    $learnpress_plugins = [
        [
            'name'     => esc_html__( 'LearnPress', 'avas' ),
            'slug'     => 'learnpress',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'LearnPress Course Review', 'avas' ),
            'slug'     => 'learnpress-course-review',
            'required' => true,
        ],
    ];

    // Events Calendar plugin
    $events_calendar = [
        'name'     => esc_html__( 'The Events Calendar', 'avas' ),
        'slug'     => 'the-events-calendar',
        'required' => true,
    ];

    // Give Donation plugin
    $give_donation = [
        'name'     => esc_html__( 'Give - Donation Plugin', 'avas' ),
        'slug'     => 'give',
        'required' => true,
    ];

    // bbPress plugin
    $bbpress = [
        'name'     => esc_html__( 'bbPress', 'avas' ),
        'slug'     => 'bbpress',
        'required' => true,
    ];

    // Estatik plugin
    $estatik = [
        'name'     => esc_html__( 'Estatik', 'avas' ),
        'slug'     => 'estatik',
        'required' => true,
    ];

    // Prime Slider plugin
    $prime_slider = [
        'name'     => esc_html__( 'Prime Slider', 'avas' ),
        'slug'     => 'bdthemes-prime-slider-lite',
        'required' => true,
    ];

    // Demo-specific plugin configurations
    $demo_plugins_map = [

        // Simple demos (base plugins only)
        'Agency Two'                    => $base_plugins,
        'Air Conditioning Services'     => $base_plugins,
        'Bicycle Repair'                => $base_plugins,
        'Business Advisor'              => $base_plugins,
        'Call Center'                   => $base_plugins,
        'Car Wash'                      => $base_plugins,
        'Coronavirus'                   => $base_plugins,
        'Creative Agency Two'           => $base_plugins,
        'Crypto News'                   => $base_plugins,
        'Design Agency'                 => $base_plugins,
        'Designer'                      => $base_plugins,
        'ICO Cryptocurrency'            => $base_plugins,
        'Magazine'                      => $base_plugins,
        'Movers'                        => $base_plugins,
        'News Dark'                     => $base_plugins,
        'Pinterest'                     => $base_plugins,
        'Resume'                        => $base_plugins,
        'Transportation & Logistics'    => $base_plugins,

        // Elementor demo only
        'Coffee Shop'                   => $elementor,

        // Demos with Mailchimp
        'AI Technology'                 => array_merge( $base_plugins, [ $mailchimp ] ),
        'Artificial Intelligence'       => array_merge( $base_plugins, [ $mailchimp ] ),
        'Business Consultant'           => array_merge( $base_plugins, [ $mailchimp ] ),
        'Business Optimization'         => array_merge( $base_plugins, [ $mailchimp ] ),
        'Construction Two'              => array_merge( $base_plugins, [ $mailchimp ] ),
        'Corporate Business'            => array_merge( $base_plugins, [ $mailchimp ] ),
        'Cyber Security Services'       => array_merge( $base_plugins, [ $mailchimp ] ),
        'Digital Agency Two'            => array_merge( $base_plugins, [ $mailchimp ] ),
        'Digital Marketing Agency'      => array_merge( $base_plugins, [ $mailchimp ] ),
        'ISP'                           => array_merge( $base_plugins, [ $mailchimp ] ),
        'IT Solutions'                  => array_merge( $base_plugins, [ $mailchimp ] ),
        'Pest Control'                  => array_merge( $base_plugins, [ $mailchimp ] ),
        'Portfolio'                     => array_merge( $base_plugins, [ $mailchimp ] ),
        'SaaS'                          => array_merge( $base_plugins, [ $mailchimp ] ),
        'Immigration Visa Consulting'   => array_merge( $base_plugins, [ $mailchimp ] ),

        // Demos with Revslider
        'Agency'                  => array_merge( $base_plugins, [ $revslider ] ),
        'App'                     => array_merge( $base_plugins, [ $revslider ] ),
        'Architecture'            => array_merge( $base_plugins, [ $revslider ] ),
        'Barber Shop'             => array_merge( $base_plugins, [ $revslider ] ),
        'Blog'                    => array_merge( $base_plugins, [ $revslider ] ),
        'Business'                => array_merge( $base_plugins, [ $revslider ] ),
        'Cleaning Services'       => array_merge( $base_plugins, [ $revslider ] ),
        'Construction'            => array_merge( $base_plugins, [ $revslider ] ),
        'Consultant'              => array_merge( $base_plugins, [ $revslider ] ),
        'Corporate'               => array_merge( $base_plugins, [ $revslider ] ),
        'Creative'                => array_merge( $base_plugins, [ $revslider ] ),
        'Dental Clinic'           => array_merge( $base_plugins, [ $revslider ] ),
        'Digital Agency'          => array_merge( $base_plugins, [ $revslider ] ),
        'Driving School'          => array_merge( $base_plugins, [ $revslider ] ),
        'Finance'                 => array_merge( $base_plugins, [ $revslider ] ),
        'Fitness'                 => array_merge( $base_plugins, [ $revslider ] ),
        'Gym'                     => array_merge( $base_plugins, [ $revslider ] ),
        'Handyman'                => array_merge( $base_plugins, [ $revslider ] ),
        'Hosting'                 => array_merge( $base_plugins, [ $revslider ] ),
        'Insurance'               => array_merge( $base_plugins, [ $revslider ] ),
        'Interior'                => array_merge( $base_plugins, [ $revslider ] ),
        'Kindergarten'            => array_merge( $base_plugins, [ $revslider ] ),
        'Lawyer'                  => array_merge( $base_plugins, [ $revslider ] ),
        'Mechanic'                => array_merge( $base_plugins, [ $revslider ] ),
        'Medical'                 => array_merge( $base_plugins, [ $revslider ] ),
        'News'                    => array_merge( $base_plugins, [ $revslider ] ),
        'Nice & Clean'            => array_merge( $base_plugins, [ $revslider ] ),
        'Photographer'            => array_merge( $base_plugins, [ $revslider ] ),
        'Product Landing Page'    => array_merge( $base_plugins, [ $revslider ] ),
        'Restaurant'              => array_merge( $base_plugins, [ $revslider ] ),
        'RTL'                     => array_merge( $base_plugins, [ $revslider ] ),
        'SEO'                     => array_merge( $base_plugins, [ $revslider ] ),
        'Spa'                     => array_merge( $base_plugins, [ $revslider ] ),
        'Startup'                 => array_merge( $base_plugins, [ $revslider ] ),
        'Travel'                  => array_merge( $base_plugins, [ $revslider ] ),
        'Website Builder'         => array_merge( $base_plugins, [ $revslider ] ),
        'Web Solutions'           => array_merge( $base_plugins, [ $revslider ] ),
        'Wedding'                 => array_merge( $base_plugins, [ $revslider ] ),

        // Demos with WooCommerce
        'Bakery'                  => array_merge( $base_plugins, $woocommerce_plugins, [ $revslider ] ),
        'Beauty Salon'            => array_merge( $base_plugins, $woocommerce_plugins, [ $mailchimp ] ),
        'Creative Agency'         => array_merge( $base_plugins, $woocommerce_plugins, [ $revslider ] ),
        'eBook'                   => array_merge( $base_plugins, $woocommerce_plugins, [ $revslider ] ),
        'Pet Care'                => array_merge( $base_plugins, [ $mailchimp ], $woocommerce_plugins ),
        'Printing Services'       => array_merge( $base_plugins, [ $mailchimp ], $woocommerce_plugins ),
        'Shop'                    => array_merge( $base_plugins, $woocommerce_plugins, [ $revslider ] ),

        // Demos with LearnPress
        'Education'               => array_merge( $base_plugins, $learnpress_plugins, [ $revslider ] ),
        'Education Two'           => array_merge( $base_plugins, $learnpress_plugins, [ $revslider ] ),

        // Demos with Events Calendar
        'Charity Two'             => array_merge( $base_plugins, [ $events_calendar, $mailchimp ] ),
        'Events'                  => array_merge( $base_plugins, [ $events_calendar, $revslider ] ),
        'Yoga'                    => array_merge( $base_plugins, [ $events_calendar, $revslider ] ),

        // Special demos
        'Charity'                 => array_merge( $base_plugins, [ $give_donation, $revslider ] ),
        'Forum'                   => array_merge( $base_plugins, [ $bbpress ] ),
        'Real Estate'             => array_merge( $base_plugins, [ $estatik, $revslider ] ),
        'Insurance Two'           => array_merge( $base_plugins, [ $mailchimp, $prime_slider ] ),
        'Technology'              => array_merge( $base_plugins, [ $mailchimp, $revslider ] ),
    ];

    // Return specific demo plugins or base plugins as default
    return isset( $demo_plugins_map[ $demo_name ] ) ? $demo_plugins_map[ $demo_name ] : $base_plugins;
}


/**
 * Demo plugin setup
 */
function tx_register_plugins( $plugins ) {
    // List of plugins used by all theme demos (default)
    $theme_plugins = [
        [
            'name'     => esc_html__( 'Elementor', 'avas' ),
            'slug'     => 'elementor',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'Contact Form 7', 'avas' ),
            'slug'     => 'contact-form-7',
            'required' => true,
        ],
        [
            'name'     => esc_html__( 'Slider Revolution', 'avas' ),
            'slug'     => 'revslider',
            'source'   => 'https://avas.live/revslider/revslider.zip',
            'required' => true,
        ],
    ];

    // Check if user is on the theme recommended plugins step and a demo was selected
    if ( isset( $_GET['step'] ) && $_GET['step'] === 'import' && isset( $_GET['import'] ) ) {
        
        // Get the demo index
        $demo_index = intval( $_GET['import'] );
        
        // Get all available demos
        $available_demos = apply_filters( 'ocdi/import_files', [] );
        
        // Check if the demo exists
        if ( isset( $available_demos[ $demo_index ] ) ) {
            $demo_name = $available_demos[ $demo_index ]['import_file_name'];
            
            // Get plugins for this specific demo
            $theme_plugins = tx_get_demo_plugins( $demo_name );
        }
    }

    return array_merge( $plugins, $theme_plugins );
}



add_filter( 'ocdi/register_plugins', 'tx_register_plugins' );

/* ---------------------------------------------------------
    EOF
------------------------------------------------------------ */