<?php

namespace WooLentor;

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

/**
* Base
*/
final class Base {

    const MINIMUM_PHP_VERSION = '5.4';
    const MINIMUM_ELEMENTOR_VERSION = '3.0.0';

    /**
     * [$template_info]
     * @var array
     */
    public static $template_info = [];

    /**
     * [$_instance]
     * @var null
     */
    private static $_instance = null;

    /**
     * [instance] Initializes a singleton instance
     * @return [Base]
     */
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * [__construct] Class construcotr
     */
    private function __construct() {

        if ( ! function_exists('is_plugin_active') ){ include_once( ABSPATH . 'wp-admin/includes/plugin.php' ); }
        add_action( 'init', [ $this, 'i18n' ] );
        add_action( 'plugins_loaded', [ $this, 'init' ] );

        // Installer
        if( is_admin() ){
            require( WOOLENTOR_ADDONS_PL_PATH.'classes/class.installer.php' );
        }
        // WooLentor Template CPT Manager
        require( WOOLENTOR_ADDONS_PL_PATH. 'includes/admin/include/class.template-manager.php' );

        // Register Plugin Active Hook
        register_activation_hook( WOOLENTOR_ADDONS_PL_ROOT, [ $this, 'plugin_activate_hook' ] );
        if( empty( get_option('woolentor_version', '') ) ){
            $this->plugin_activate_hook();
        }

        // Register Plugin Deactive Hook
        register_deactivation_hook( WOOLENTOR_ADDONS_PL_ROOT, [ $this, 'plugin_deactivation_hook'] );

        // Support WooCommerce
        add_action( 'after_setup_theme', [ $this, 'after_setup_theme' ] );

        // Product View Count
        add_action( 'template_redirect', [ $this, 'track_user_viewed_products' ], 99 );

    }

    /**
     * [i18n] Load Text Domain
     * @return [void]
     */
    public function i18n() {
        load_plugin_textdomain( 'woolentor', false, dirname( plugin_basename( WOOLENTOR_ADDONS_PL_ROOT ) ) . '/languages/' );
    }

    /**
     * [init] Plugins Loaded Init Hook
     * @return [void]
     */
    public function init() {

        if( is_admin()){
            include_once( WOOLENTOR_ADDONS_PL_PATH.'includes/admin/include/class.notice.php' );
        }

        // Check for required PHP version
        if ( version_compare( PHP_VERSION, self::MINIMUM_PHP_VERSION, '<' ) ) {
            add_action( 'admin_notices', [ $this, 'admin_notice_minimum_php_version' ] );
            return;
        }

        // Check WooCommerce
        if ( !did_action( 'woocommerce_loaded' ) ) {
            add_action('admin_notices', [ $this, 'admin_notic_missing_woocommerce' ] );
            return;
        }

        // Plugins Setting Page
        add_filter('plugin_action_links_'.WOOLENTOR_PLUGIN_BASE, [ $this, 'plugins_setting_links' ] );
        add_filter( 'plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 4 );

        // Include File
        $this->include_files();

        // After Active Plugin then redirect to setting page
        $this->plugin_redirect_option_page();

        // Migration: Delete old transients and use file-based cache
        if( is_admin() && class_exists('\Woolentor_Template_Library_Manager') ){
            $this->migrate_template_cache();
        }

        // Admin Notices
        add_action( 'admin_head', [ $this, 'all_admin_notices' ] );

        // Elementor Preview Action
        if ( ! empty( $_REQUEST['action'] ) && 'elementor' === $_REQUEST['action'] && is_admin() ) {
            add_action( 'admin_action_elementor', [ $this, 'wc_fontend_includes' ], 5 );
        }

        // Manage Page Action
        \WooLentor_Page_Action::instance()->init();

    }

    /**
     * [admin_notic_missing_woocommerce] Admin Notice For missing WooCommerce
     * @return [void]
     */
    public function admin_notic_missing_woocommerce(){

        if( ! current_user_can( 'activate_plugins' ) ) {
            return;
        }
        $woocommerce = 'woocommerce/woocommerce.php';
        if( $this->is_plugins_install( $woocommerce ) ) {
            $button['url'] = wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . $woocommerce . '&amp;plugin_status=all&amp;paged=1&amp;s', 'activate-plugin_' . $woocommerce );
            $button['text'] = __( 'Activate WooCommerce', 'woolentor' );
            $message = sprintf( __( '%1$sShopLentor Addons for Elementor%2$s requires %1$s"WooCommerce"%2$s plugin to be active. Please activate WooCommerce to continue.', 'woolentor' ), '<strong>', '</strong>');
        }else{
            $button['url']  = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' );
            $button['text'] = __( 'Install WooCommerce', 'woolentor' );
            $message = sprintf( __( '%1$sShopLentor Addons for Elementor%2$s requires %1$s"WooCommerce"%2$s plugin to be installed and activated. Please install WooCommerce to continue.', 'woolentor' ), '<strong>', '</strong>' );
        }

        \WooLentor_Notices::add_notice(
			[
				'id'          => 'missing-woocommerce',
				'type'        => 'error',
                'button'      => $button,
				'message'     => $message,
				'is_show'     => true,
			]
		);
    }

    /**
     * [admin_notice_minimum_php_version] Admin Notice For Required PHP Version
     * @return [void]
     */
    public function admin_notice_minimum_php_version() {
        if ( isset( $_GET['activate'] ) ) unset( $_GET['activate'] );
        $message = sprintf(
            /* translators: 1: Plugin name 2: PHP 3: Required PHP version */
            esc_html__( '"%1$s" requires "%2$s" version %3$s or greater.', 'woolentor' ),
            '<strong>' . esc_html__( 'ShopLentor', 'woolentor' ) . '</strong>',
            '<strong>' . esc_html__( 'PHP', 'woolentor' ) . '</strong>',
             self::MINIMUM_PHP_VERSION
        );

        \WooLentor_Notices::add_notice(
			[
				'id'          => 'phpcompatibility',
				'type'        => 'warning',
				'message'     => $message,
			]
		);
    }

    /**
     * Admin Notices
     *
     * @return void
     */
    public function all_admin_notices(){

        // Rating notice
        $this->admin_rating_notice();

        // Promo Banner
        $this->admin_promo_notice();

    }

    /**
     * Rating Notice
     *
     * @return void
     */
    public function admin_rating_notice(){
        $logo_url = esc_url(WOOLENTOROPT_ASSETS.'/images/logo.png');

        $message = '<div class="hastech-review-notice-wrap">
                    <div class="hastech-rating-notice-logo">
                        <img src="' . $logo_url . '" alt="'.esc_attr__('ShopLentor','woolentor').'" style="max-width:85px"/>
                    </div>
                    <div class="hastech-review-notice-content">
                        <h3>'.esc_html__('Hi there! Thanks a lot for choosing ShopLentor to build an outstanding WooCommerce store.','woolentor').'</h3>
                        <p>'.esc_html__('It would be greatly appreciated if you consider giving us a review in WordPress. These reviews help us improve the plugin further and make it easier for other users to decide when exploring ShopLentor!','woolentor').'</p>
                        <div class="hastech-review-notice-action">
                            <a href="https://wordpress.org/support/plugin/woolentor-addons/reviews/?filter=5#new-post" class="hastech-review-notice button-primary" target="_blank">'.esc_html__('Ok, you deserve it!','woolentor').'</a>
                            <span class="dashicons dashicons-calendar"></span>
                            <a href="#" class="hastech-notice-close woolentor-review-notice">'.esc_html__('Maybe Later','woolentor').'</a>
                            <span class="dashicons dashicons-smiley"></span>
                            <a href="#" data-already-did="yes" class="hastech-notice-close woolentor-review-notice">'.esc_html__('I already did','woolentor').'</a>
                        </div>
                    </div>
                </div>';

        \WooLentor_Notices::set_notice(
            [
                'id'          => 'wlrating-notice',
                'type'        => 'info',
                'dismissible' => true,
                'message_type' => 'html',
                'message'     => $message,
                'display_after' => ( 2 * WEEK_IN_SECONDS ),
                'expire_time' => MONTH_IN_SECONDS,
                'close_by'    => 'transient'
            ]
        );
    }

    /**
     * Migrate template cache from transient to file-based cache
     * One-time migration
     *
     * @return void
     */
    public function migrate_template_cache(){
        $migrated = get_option( 'woolentor_cache_migrated_v2', false );

        if ( ! $migrated ) {
            // Delete old transients
            \Woolentor_Template_Library_Manager::migrate_from_transient();

            // Mark as migrated
            update_option( 'woolentor_cache_migrated_v2', true );
        }
    }

    /**
     * Get template info (lazy load)
     *
     * @return array
     */
    public static function get_template_info(){
        if( empty( self::$template_info ) && class_exists('\Woolentor_Template_Library_Manager') ){
            self::$template_info = \Woolentor_Template_Library_Manager::instance()->get_templates_info();
        }
        return self::$template_info;
    }

    /**
     * [admin_promo_notice]
     * @return [void] Promo banner admin notice
     */
    public function admin_promo_notice(){

        if( is_plugin_active('woolentor-addons-pro/woolentor_addons_pro.php') ){
            return;
        }

        // Lazy load template info
        $template_info = self::get_template_info();

        if( !isset( $template_info['notices'] ) || !is_array( $template_info['notices'] ) ){
            return;
        }

        if( isset( $template_info['notices'][0]['status'] ) ){
            if( $template_info['notices'][0]['status'] == 0 ){
                return;
            }
        }else{
            return;
        }

        // Fetch data
        $bannerLink = $template_info['notices'][0]['bannerlink'] ? $template_info['notices'][0]['bannerlink'] : '#';
        $bannerTitle = $template_info['notices'][0]['title'] ? $template_info['notices'][0]['title'] : esc_html__('Promo Banner','woolentor');
        $bannerDescription = $template_info['notices'][0]['description'] ? $template_info['notices'][0]['description'] : '';
        $bannerImage = $template_info['notices'][0]['bannerimage'] ? '<img src="'.esc_url($template_info['notices'][0]['bannerimage']).'" alt="'.esc_attr($bannerTitle).'"/>' : '';

        $banner['image'] = $bannerImage;
        $banner['url'] = $bannerLink;
        \WooLentor_Notices::set_notice(
            [
                'id'          => 'wlpromo-banner',
                'type'        => 'info',
                'dismissible' => true,
                'message'     => $bannerDescription,
                'banner'      => $banner,
                'close_by'    => 'user',
                'priority'    => 2
            ]
        );

    }

   /**
    * [is_plugins_install] Check Plugin is Installed or not
    * @param  [string] $pl_file_path plugin file path
    * @return boolean  true|false
    */
    public function is_plugins_install( $pl_file_path = NULL ){
        $installed_plugins_list = get_plugins();
        return isset( $installed_plugins_list[$pl_file_path] );
    }

   /**
    * [plugins_setting_links]
    * @param  [array] $links default plugin action link
    * @return [array] plugin action link
    */
    public function plugins_setting_links( $links ) {
        $settings_link = '<a href="'.admin_url('admin.php?page=woolentor').'">'.esc_html__( 'Settings', 'woolentor' ).'</a>'; 
        array_unshift( $links, $settings_link );
        if( !is_plugin_active('woolentor-addons-pro/woolentor_addons_pro.php') ){
            $links['woolentorgo_pro'] = sprintf('<a href="https://woolentor.com/pricing/?utm_source=admin&utm_medium=gopro&utm_campaign=free" target="_blank" style="color: #39b54a; font-weight: bold;">' . esc_html__('Go Pro','woolentor') . '</a>');
        }
        return $links; 
    }

    /**
     * [plugin_row_meta] Plugin row meta
     * @return [links] plugin action link
     */
    public function plugin_row_meta( $links, $file, $data, $status ) {
        if ( $file === WOOLENTOR_PLUGIN_BASE ) {
            $new_links = array(
                'docs'          => '<a href="https://woolentor.com/documentation/wl/" target="_blank"><span class="dashicons dashicons-search"></span>' . esc_html__( 'Documentation', 'woolentor' ) . '</a>',
                'facebookgroup' => '<a href="https://www.facebook.com/groups/woolentor" target="_blank"><span class="dashicons dashicons-facebook" style="font-size:14px;line-height:1.3"></span>' . esc_html__( 'Facebook Group', 'woolentor' ) . '</a>',
                'rateus'        => '<a href="https://wordpress.org/support/plugin/woolentor-addons/reviews/?filter=5#new-post" target="_blank"><span class="dashicons dashicons-star-filled" style="font-size:14px;line-height:1.3"></span>' . esc_html__( 'Rate the plugin', 'woolentor' ) . '</a>',
            );
            $links = array_merge( $links, $new_links );
        }
        return $links;
    }

   /**
    * [plugin_activate_hook] Plugin Activation hook callable
    * @return [void]
    */
    public function plugin_activate_hook() {
        if( class_exists('\WooLentor\Installer') ){
            \WooLentor\Installer::instance();
        }
    }

    /**
     * [plugin_deactivation_hook] Plugin Deactivation hook callable
     * @return [void]
     */
    public function plugin_deactivation_hook() {
        delete_metadata( 'user', 0, 'hastech-notice-id-wlagency-bundle-promo-banner', null, true );
        update_option( 'woolentor_plugin_permalinks_flushed', 'no' );
    }

    /**
     * [plugin_redirect_option_page] After Active the plugin then redirect to option page
     * @return [void]
     */
    public function plugin_redirect_option_page() {
        if ( get_option( 'woolentor_do_activation_redirect', FALSE ) ) {
            delete_option('woolentor_do_activation_redirect');
            if( !isset( $_GET['activate-multi'] ) ){
                if ( ! get_option( 'woolentor_setup_wizard_completed', false ) ) {
                    wp_redirect( admin_url( 'admin.php?page=woolentor#/setup-wizard' ) );
                } else {
                    wp_redirect( admin_url( 'admin.php?page=woolentor' ) );
                }
                exit;
            }
        }
    }


    /**
     * [after_setup_theme] WooCommerce Support
     * @return [void] 
     */
    public function after_setup_theme() {
        if( function_exists('woolentor_get_option') ){
            if( woolentor_get_option( 'enablecustomlayout', 'woolentor_woo_template_tabs', 'on' ) == 'on' ){
                if( !current_theme_supports('woocommerce') ) {
                    add_theme_support('woocommerce');
                    add_theme_support('wc-product-gallery-zoom');
                    add_theme_support('wc-product-gallery-lightbox');
                    add_theme_support('wc-product-gallery-slider');
                }
            }
        }
    }

    /**
     * Manage Product Viewed products
     *
     * @return void
     */

     public function track_user_viewed_products(){

        global $post;
    
        if ( is_null( $post ) || $post->post_type != 'product' || !is_product() ) {
            return;
        }
    
        $products_list = woolentor_get_track_user_data();
        $user_id       = get_current_user_id();
        $cookie_name   = woolentor_get_cookie_name( 'viewed_products_list' );
    
        $product_id = get_the_id();
    
        // Initialize products_list as array if it's not already
        if (!is_array($products_list)) {
            $products_list = [];
        }
    
        // Check current product exists in the list and remove it
        if ( ( $key = array_search( $product_id, $products_list ) ) !== false ) {
            unset( $products_list[$key] );
        }
    
        $timestamp = time();
        $products_list[$timestamp] = $product_id;
    
        // MEMORY FIX: Limit the size of the products list to prevent memory exhaustion
        $max_products_limit = apply_filters( 'woolentor_max_viewed_products', 100 ); // Default limit: 100 products
        
        if ( count( $products_list ) > $max_products_limit ) {
            // Sort by timestamp (keys) and keep only the most recent products
            ksort( $products_list );
            $products_list = array_slice( $products_list, -$max_products_limit, null, true );
        }
    
        // Set cookie or save user meta
        $cookie_duration = 5;
        $cookie_duration = time() + (86400 * $cookie_duration);
    
        if ( $user_id ) {
            update_user_meta( $user_id, $cookie_name, $products_list );
        } else {
            setcookie( $cookie_name, serialize( $products_list ), $cookie_duration, COOKIEPATH, COOKIE_DOMAIN, false, true );
        }
    
        // Set View Count
        woolentor_set_views_count( $product_id, 'product' );
    
    }

   /**
    * [wc_fontend_includes] Load WC Files in Editor Mode
    * @return [void]
    */
    public function wc_fontend_includes() {
        \WC()->frontend_includes();
        if ( is_null( \WC()->cart ) ) {
            global $woocommerce;
            $session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );
            $woocommerce->session = new $session_class();
            $woocommerce->session->init();

            $woocommerce->cart     = new \WC_Cart();
            $woocommerce->customer = new \WC_Customer( get_current_user_id(), true );
        }
    }

    /**
     * [include_files] Required File
     * @return [void]
     */
    public function include_files(){

        require_once( WOOLENTOR_ADDONS_PL_PATH.'includes/helper-function.php' );
        woolentor_include_all(WOOLENTOR_ADDONS_PL_PATH.'includes/traits');
        require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.assest_management.php' );
        require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.widgets_control.php' );
        require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.default_data.php' );
        require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.icon_list.php' );
        require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.multi_language.php' );
        require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.ajax_actions.php' );

        // Admin Setting file
        if( is_admin() ){
            require_once( WOOLENTOR_ADDONS_PL_PATH.'includes/custom-metabox.php' );
            require_once( WOOLENTOR_ADDONS_PL_PATH.'includes/admin/admin-init.php' );
        }

        // Vue Dashboard
        require_once( WOOLENTOR_ADDONS_PL_PATH .'includes/admin-panel/settings-panel.php');

        // Builder File
        if( woolentor_get_option( 'enablecustomlayout', 'woolentor_woo_template_tabs', 'on' ) == 'on' ){

            require_once( WOOLENTOR_ADDONS_PL_PATH.'includes/manage_wc_template.php' );
            require_once( WOOLENTOR_ADDONS_PL_PATH.'includes/archive_product_render.php' );           
            require_once( WOOLENTOR_ADDONS_PL_PATH.'includes/class.product_video_gallery.php' );
            require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.product_query.php' );
            require_once( WOOLENTOR_ADDONS_PL_PATH.'classes/class.third_party.php' );
        }

        // Product Query Manager
        require_once( WOOLENTOR_ADDONS_PL_PATH . 'classes/class.woocommerce_query_manager.php' );

        // Page Action
        require_once( WOOLENTOR_ADDONS_PL_PATH. 'classes/class.page_action.php' );

        // Modules Manager
        require_once( WOOLENTOR_ADDONS_PL_PATH. 'includes/modules/class.module-manager.php' );


    }
    

}

/**
 * Initializes the main plugin
 *
 * @return Base
 */
function woolentor() {
    return Base::instance();
}