<?php

/**
 * Unlockafe Addons 
 *
 * @package Unlockafe_addons
 */

namespace Unlockafe_addons\Classes;

use Unlockafe_addons\Admin\Admin;
use Unlockafe_addons\Admin\Text_Generator_Settings;
use Unlockafe_addons\Classes\Assets_loader;
use Unlockafe_addons\API\Widgets_API;
use Unlockafe_addons\API\Text_Generator_API;
use Unlockafe_addons\API\AI_Chatbot_API;
use Unlockafe_addons\API\Database_API;
use Unlockafe_addons\Editor\Text_Generator_Module;
use Unlockafe_addons\Traits\Utils;
use Unlockafe_addons\Widgets\Advance_Mega_Menu;
use Unlockafe_addons\Classes\Table_Reservation_Handler;
use Elementor\Plugin as Elementor_Plugin;

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

class Unlockafe_addons {
	use Utils;
	/**
	 *
	 * $instance property for instance
	 */
	private static $instance = null;

	/**
	 *
	 * Registerd widgets in cofig
	 */
	protected $registered_widgets;

	/**
	 *
	 * Storing/create all the instance
	 */
	public $get_instance = [];


	/**
	 *
	 * @return \Instance
	 * @since  1.0.0
	 */
	public static function getInstance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}
	/**
	 * Constructor of plugin class
	 *
	 * @since 3.0.0
	 */
	private function __construct() {

		// Suppress Elementor warnings for pro-free-trial-popup module
		// This is a known Elementor issue that doesn't affect functionality
		if (defined('WP_DEBUG') && WP_DEBUG && defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY) {
			// Only suppress if debug is enabled to avoid hiding real errors
			$error_handler = function($errno, $errstr, $errfile, $errline) {
				// Suppress only the specific Elementor pro-free-trial-popup warnings
				if (strpos($errfile, 'elementor/modules/pro-free-trial-popup') !== false && 
				    (strpos($errstr, 'Undefined array key') !== false || 
				     strpos($errstr, 'Trying to access array offset') !== false)) {
					return true; // Suppress this warning
				}
				return false; // Let other errors through
			};
			set_error_handler($error_handler, E_WARNING);
		}

		//admin page
		Admin::getInstance();
		// Initialize Text Generator Settings
		Text_Generator_Settings::getInstance();
		
		$widgets                  = require_once UNLOCKAFE_INCLUDE_PATH . 'Widgets/init.php';
		$this->registered_widgets = apply_filters( 'unlockafe_addons/widgets', $widgets );
		$this->unlockafe_load_instance();
		add_action('admin_enqueue_scripts', [ $this, 'admin_scripts' ]);
		$this->register_hooks();
	}

	/**
	 *
	 * Registering Hooks for UNLOCKAFE
	 *
	 * @since  1.0.0
	 */
	public function register_hooks() {

		if ( defined( 'ELEMENTOR_VERSION' ) ) {
			if ( version_compare( ELEMENTOR_VERSION, '3.5.0', '>=' ) ) {
				add_action( 'elementor/widgets/register', array( $this, 'register_widgets' ) );
			} else {
				add_action( 'elementor/widgets/widgets_registered', array( $this, 'register_widgets' ) );
			}
		}

		//loading assets
		$this->assets_loader();

		// Regenerate per-post CSS/JS bundles on plugin version bump so widget updates apply without re-saving each page.
		add_action( 'init', [ $this, 'maybe_regenerate_assets_on_upgrade' ], 5 );

		/// pro
		add_filter( 'elementor/editor/localize_settings', [ $this, 'unlockafe_promote_pro_elements' ] );

		// Register Header/Footer template post types.
		add_action( 'init', [ $this, 'register_template_post_types' ] );

		// Table Reservation widget AJAX
		Table_Reservation_Handler::init();

		// Register category
		add_action( 'elementor/elements/categories_registered', [ $this, 'add_custom_widget_categories' ] );

		add_action( 'wp_body_open', [ $this, 'render_global_header' ], 5 );
		add_action( 'wp_footer', [ $this, 'render_global_footer' ], 5 );

		add_filter( 'body_class', [ $this, 'add_header_footer_body_class' ], 10, 1 );
		add_action( 'wp_head', [ $this, 'hide_theme_header_when_custom_header_active' ], 100 );

		add_action( 'add_meta_boxes', [ $this, 'register_header_footer_meta_boxes' ] );
		add_action( 'save_post', [ $this, 'save_header_footer_meta' ] );

		// Unlock Advance Mega Menu – nav menu settings (Appearance → Menus)
		add_action( 'init', [ $this, 'init_mega_menu_nav_settings' ], 20 );

		// Advance Mega Menu: default Z-Index 15 (after common controls are merged so value shows in panel).
		add_action( 'elementor/element/after_register_controls', [ $this, 'advance_mega_menu_default_z_index' ], 10, 1 );
		add_action( 'wp_ajax_unlockafe_get_dummy_mega_menu', [ Advance_Mega_Menu::class, 'ajax_get_dummy_mega_menu' ] );

		//add link
		add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'add_action_links' );

		// register RestAPI
		add_action( 'rest_api_init', [ $this->get_instance['widget_api'], 'register_routes' ] );
		add_action( 'rest_api_init', [ $this->get_instance['database_api'], 'register_routes' ] );

		/// remove promotions
		add_filter( 'unlockafe_addon/promotions', function ($value) {
			return [];
		} );
	}

	/**
	 * On plugin version bump, regenerate per-post asset bundles for all posts that use Unlockafe widgets
	 * so that CSS/JS updates (e.g. Advance Mega Menu) apply without requiring users to re-save each page.
	 *
	 * @since 1.0.0
	 */
	public function maybe_regenerate_assets_on_upgrade() {
		if ( ! defined( 'UNLOCKAFE_VERSION' ) ) {
			return;
		}
		$option = 'unlockafe_assets_db_version';
		if ( get_option( $option ) === UNLOCKAFE_VERSION ) {
			return;
		}
		$loader = $this->get_instance['assets_loader'] ?? null;
		if ( ! $loader || ! isset( $loader->Widget_manager ) ) {
			return;
		}
		$loader->Widget_manager->regenerate_assets_on_upgrade();
		update_option( $option, UNLOCKAFE_VERSION );
	}

	/**
	 *
	 * Creating instance for all the dependency class
	 *
	 * @since  1.0.0
	 */
	public function unlockafe_load_instance() {
		$this->get_instance['assets_loader'] = new Assets_loader( $this->registered_widgets );
		$this->get_instance['widget_api']    = new Widgets_API( $this->registered_widgets );
		$this->get_instance['text_generator_api'] = Text_Generator_API::getInstance();
		$this->get_instance['text_generator_module'] = Text_Generator_Module::getInstance();
		$this->get_instance['database_api'] = Database_API::getInstance();
	}

	/**
	 *
	 * Registering cusotm a widget
	 *
	 * @since  1.0.0
	 */
	public function register_widgets( $widgets_manager ) {
		// Get DB option
		$get_widgets = is_array( get_option( '_unlockafe_addons_opstions' ) ) ? get_option( '_unlockafe_addons_opstions', true ) : [];
		// Merge config and DB
		$widgets = $this->unlockafe_combine_widgets( $this->registered_widgets['widgets'], array_combine( array_column( $get_widgets, 'id' ), $get_widgets ) );
		foreach ( $widgets as $key => $widget ) {
			if ( isset( $widget['class'] ) && $widget['status'] == true && class_exists( $widget['class'] ) ) {
				$widgets_manager->register( new $widget['class']() );
			}
		}
	}
	/**
	 * `plugin_type` returning Plugin type
	 * 
	 * @return string
	 */
	public static function plugin_type() {
		return apply_filters( 'unlockafe_addon/plugin_type', 'lite' );
	}

	/**
	 * Loading pluign assets
	 */
	public function assets_loader() {

		add_action( 'wp_enqueue_scripts', [ $this->get_instance['assets_loader'], 'load_public_scripts' ] );
		add_action( 'admin_enqueue_scripts', [ $this->get_instance['assets_loader'], 'unlockafe_load_admin_scripts' ] );
	}

	/**
	 * Register custom post types used for Header and Footer templates.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public function register_template_post_types() {
		$common_args = [
			'public'              => false,
			'show_ui'             => true,
			'show_in_menu'        => true,
			'exclude_from_search' => true,
			'publicly_queryable'  => true,
			'rewrite'             => false,
			'show_in_rest'        => true,
			'supports'            => [ 'title', 'editor', 'thumbnail', 'revisions', 'elementor' ],
		];

		$header_labels = [
			'name'               => __( 'Headers', 'unlock-addons-for-elementor' ),
			'singular_name'      => __( 'Header', 'unlock-addons-for-elementor' ),
			'add_new'            => __( 'Add New Header', 'unlock-addons-for-elementor' ),
			'add_new_item'       => __( 'Add New Header', 'unlock-addons-for-elementor' ),
			'edit_item'          => __( 'Edit Header', 'unlock-addons-for-elementor' ),
			'new_item'           => __( 'New Header', 'unlock-addons-for-elementor' ),
			'view_item'          => __( 'View Header', 'unlock-addons-for-elementor' ),
			'search_items'       => __( 'Search Headers', 'unlock-addons-for-elementor' ),
			'not_found'          => __( 'No headers found', 'unlock-addons-for-elementor' ),
			'not_found_in_trash' => __( 'No headers found in Trash', 'unlock-addons-for-elementor' ),
			'menu_name'          => __( 'Header', 'unlock-addons-for-elementor' ),
		];

		register_post_type(
			'wpr-header',
			wp_parse_args(
				[
					'labels'    => $header_labels,
					'menu_icon' => 'dashicons-editor-table',
					'menu_position' => 35,
				],
				$common_args
			)
		);

		$footer_labels = [
			'name'               => __( 'Footers', 'unlock-addons-for-elementor' ),
			'singular_name'      => __( 'Footer', 'unlock-addons-for-elementor' ),
			'add_new'            => __( 'Add New Footer', 'unlock-addons-for-elementor' ),
			'add_new_item'       => __( 'Add New Footer', 'unlock-addons-for-elementor' ),
			'edit_item'          => __( 'Edit Footer', 'unlock-addons-for-elementor' ),
			'new_item'           => __( 'New Footer', 'unlock-addons-for-elementor' ),
			'view_item'          => __( 'View Footer', 'unlock-addons-for-elementor' ),
			'search_items'       => __( 'Search Footers', 'unlock-addons-for-elementor' ),
			'not_found'          => __( 'No footers found', 'unlock-addons-for-elementor' ),
			'not_found_in_trash' => __( 'No footers found in Trash', 'unlock-addons-for-elementor' ),
			'menu_name'          => __( 'Footer', 'unlock-addons-for-elementor' ),
		];

		register_post_type(
			'wpr-footer',
			wp_parse_args(
				[
					'labels'    => $footer_labels,
					'menu_icon' => 'dashicons-editor-kitchensink',
					'menu_position' => 36,
				],
				$common_args
			)
		);
	}

	/**
	 * Add custom widget categories
	 */
	public function add_custom_widget_categories( $elements_manager ) {
		$elements_manager->add_category(
			'unlockafe-addons',
			[ 
				'title' => __( 'Unlock Addons', 'unlock-addons-for-elementor' ),
				'icon' => 'fa fa-plug',
			]
		);
		$elements_manager->add_category(
			'unlock-addons-pro',
			[ 
				'title' => __( 'Unlock Addons Pro', 'unlock-addons-for-elementor' ),
				'icon' => 'fa fa-plug',
			]
		);
		$elements_manager->add_category(
			'unlockafe-restaurant',
			[
				'title' => __( 'Restaurant', 'unlock-addons-for-elementor' ),
				'icon'  => 'eicon-archive',
			]
		);
	}
	public function unlockafe_promote_pro_elements( $config ) {

		$pro_widgets = [];

		if ( isset( $config['promotionWidgets'] ) ) {
			$pro_widgets = $config['promotionWidgets'];
		}


		$add_pro_widget = apply_filters( 'unlockafe_addon/promotions', [ 
			[ 
				'name' => 'unlockafe-team-carousel',
				'title' => __( 'Team Carousel', 'unlock-addons-for-elementor' ),
				'icon' => 'eicon-slider-push',
				'categories' => '["unlock-addons-pro"]'
			],
			[ 
				'name' => 'unlockafe-blog-carousel',
				'title' => __( 'Blog Carousel', 'unlock-addons-for-elementor' ),
				'icon' => 'eicon-posts-carousel',
				'categories' => '["unlock-addons-pro"]'
			],
		] );

		$config['promotionWidgets'] = array_merge( $pro_widgets, $add_pro_widget );

		return $config;
	}

	/**
	 * Enqueue scripts and styles for admin
	 */
	public function admin_scripts()
	{
		if (isset($_GET['page']) && strpos($_GET['page'], 'unlock-addons') !== false) {
			// Enqueue WordPress core scripts needed for React
			wp_enqueue_script('wp-element');
			wp_enqueue_script('wp-components');
			wp_enqueue_script('wp-api-fetch');

			wp_enqueue_style(
				'unlockafe-admin',
				UNLOCKAFE_ADDONS_URL . 'assets/build/index.css',
				[],
				filemtime(UNLOCKAFE_ADDONS_PATH . 'assets/build/index.css')
			);

			wp_enqueue_script(
				'unlockafe-admin',
				UNLOCKAFE_ADDONS_URL . 'assets/build/index.js',
				['wp-element', 'wp-components', 'wp-api-fetch'],
				filemtime(UNLOCKAFE_ADDONS_PATH . 'assets/build/index.js'),
				true
			);

			// Localize script with nonce and other data for REST API
			wp_localize_script('unlockafe-admin', 'unlockAddonsData', [
				'ajaxUrl' => admin_url('admin-ajax.php'),
				'nonce' => wp_create_nonce('wp_rest'),
				'restUrl' => esc_url_raw(rest_url()),
				'adminUrl' => admin_url()
			]);
		}
	}

	protected function get_active_template_id( $type = 'header' ) {
		$option_key = $type === 'footer' ? 'unlockafe_default_footer' : 'unlockafe_default_header';
		$meta_key   = $type === 'footer' ? '_unlockafe_footer_template' : '_unlockafe_header_template';

		if ( is_singular() ) {
			$post_id = get_queried_object_id();
			$meta_id = absint( get_post_meta( $post_id, $meta_key, true ) );
			if ( $meta_id ) {
				return $meta_id;
			}
		}

		$id = absint( get_option( $option_key, 0 ) );
		return $id ? $id : 0;
	}

	protected function render_elementor_template( $template_id ) {
		if ( ! $template_id || ! class_exists( '\Elementor\Plugin' ) ) {
			return '';
		}

		return Elementor_Plugin::instance()->frontend->get_builder_content_for_display( $template_id );
	}

	public function render_global_header() {
		if ( is_admin() || is_singular( [ 'wpr-header', 'wpr-footer' ] ) ) {
			return;
		}

		$header_id = $this->get_active_template_id( 'header' );
		if ( ! $header_id ) {
			return;
		}

		echo '<div class="unlockafe-global-header">';
		echo $this->render_elementor_template( $header_id );
		echo '</div>';
	}

	public function render_global_footer() {
		if ( is_admin() || is_singular( [ 'wpr-header', 'wpr-footer' ] ) ) {
			return;
		}

		$footer_id = $this->get_active_template_id( 'footer' );
		if ( ! $footer_id ) {
			return;
		}

		echo '<div class="unlockafe-global-footer">';
		echo $this->render_elementor_template( $footer_id );
		echo '</div>';
	}

	/**
	 * Add body class when custom header or footer from plugin is active (so theme header can be hidden via CSS).
	 *
	 * @param array $classes Existing body classes.
	 * @return array
	 */
	public function add_header_footer_body_class( $classes ) {
		if ( is_admin() || is_singular( [ 'wpr-header', 'wpr-footer' ] ) ) {
			return $classes;
		}
		if ( $this->get_active_template_id( 'header' ) ) {
			$classes[] = 'unlockafe-global-header-active';
		}
		if ( $this->get_active_template_id( 'footer' ) ) {
			$classes[] = 'unlockafe-global-footer-active';
		}
		return $classes;
	}

	/**
	 * When a header is set from Header & Footer settings, hide the theme's default header to avoid duplicate headers.
	 */
	public function hide_theme_header_when_custom_header_active() {
		if ( is_admin() || is_singular( [ 'wpr-header', 'wpr-footer' ] ) ) {
			return;
		}
		if ( ! $this->get_active_template_id( 'header' ) ) {
			return;
		}

		$selectors = apply_filters( 'unlockafe_addons/hide_theme_header_selectors', [
			'.site-header-main-section-left',
			'.site-header-section',
			'.site-header-main',
			'.site-header',
			'#site-header',
			'header#masthead',
			'.fusion-header-wrapper',
			'#fusion-header',
			'header'
		] );

		$selector_list = implode( ', ', array_map( function ( $s ) {
			return 'body.unlockafe-global-header-active ' . trim( $s );
		}, $selectors ) );

		echo '<style id="unlockafe-hide-theme-header">';
		echo $selector_list . ' { display: none !important; }';
		echo '</style>';
	}

	/**
	 * Set default Z-Index to 15 for Advance Mega Menu widget (runs after Elementor merges common controls).
	 *
	 * @param \Elementor\Controls_Stack $element
	 */
	public function advance_mega_menu_default_z_index( $element ) {
		if ( $element->get_name() !== 'unlockafe-advance-mega-menu' ) {
			return;
		}
		// Responsive Z-Index: set defaults so the value shows in the panel (desktop_default fixes empty display).
		$element->update_control( '_z_index', [
			'default'          => 15,
			'desktop_default'  => 15,
			'tablet_default'   => 15,
			'mobile_default'   => 15,
			'frontend_available' => true,
		] );
	}

	/**
	 * Load Advance Mega Menu nav settings (Appearance → Menus: declare menu as mega, choose template).
	 */
	public function init_mega_menu_nav_settings() {
		require_once UNLOCKAFE_INCLUDE_PATH . 'Classes/Mega_Menu_Nav_Settings.php';
		new Mega_Menu_Nav_Settings();
	}

	public function register_header_footer_meta_boxes() {
		$post_types = apply_filters( 'unlockafe_addons/header_footer_meta_post_types', [ 'page' ] );
		foreach ( $post_types as $post_type ) {
			add_meta_box(
				'unlockafe-header-footer-meta',
				__( 'Header & Footer', 'unlock-addons-for-elementor' ),
				[ $this, 'render_header_footer_meta_box' ],
				$post_type,
				'side',
				'default'
			);
		}
	}

	public function render_header_footer_meta_box( $post ) {
		wp_nonce_field( 'unlockafe_save_header_footer_meta', 'unlockafe_header_footer_meta_nonce' );

		$selected_header = get_post_meta( $post->ID, '_unlockafe_header_template', true );
		$selected_footer = get_post_meta( $post->ID, '_unlockafe_footer_template', true );

		$headers = get_posts( [
			'post_type'      => 'wpr-header',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'title',
			'order'          => 'ASC',
		] );

		$footers = get_posts( [
			'post_type'      => 'wpr-footer',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'title',
			'order'          => 'ASC',
		] );
		?>
		<p>
			<label for="unlockafe_post_header"><?php esc_html_e( 'Header Template', 'unlock-addons-for-elementor' ); ?></label>
			<select name="unlockafe_post_header" id="unlockafe_post_header" class="widefat">
				<option value=""><?php esc_html_e( 'Default (Global)', 'unlock-addons-for-elementor' ); ?></option>
				<?php foreach ( $headers as $header ) : ?>
					<option value="<?php echo esc_attr( $header->ID ); ?>" <?php selected( $selected_header, $header->ID ); ?>>
						<?php echo esc_html( $header->post_title ); ?>
					</option>
				<?php endforeach; ?>
			</select>
		</p>
		<p>
			<label for="unlockafe_post_footer"><?php esc_html_e( 'Footer Template', 'unlock-addons-for-elementor' ); ?></label>
			<select name="unlockafe_post_footer" id="unlockafe_post_footer" class="widefat">
				<option value=""><?php esc_html_e( 'Default (Global)', 'unlock-addons-for-elementor' ); ?></option>
				<?php foreach ( $footers as $footer ) : ?>
					<option value="<?php echo esc_attr( $footer->ID ); ?>" <?php selected( $selected_footer, $footer->ID ); ?>>
						<?php echo esc_html( $footer->post_title ); ?>
					</option>
				<?php endforeach; ?>
			</select>
		</p>
		<?php
	}

	public function save_header_footer_meta( $post_id ) {
		if ( ! isset( $_POST['unlockafe_header_footer_meta_nonce'] ) || ! wp_verify_nonce( $_POST['unlockafe_header_footer_meta_nonce'], 'unlockafe_save_header_footer_meta' ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( isset( $_POST['unlockafe_post_header'] ) ) {
			$header = absint( $_POST['unlockafe_post_header'] );
			if ( $header ) {
				update_post_meta( $post_id, '_unlockafe_header_template', $header );
			} else {
				delete_post_meta( $post_id, '_unlockafe_header_template' );
			}
		}

		if ( isset( $_POST['unlockafe_post_footer'] ) ) {
			$footer = absint( $_POST['unlockafe_post_footer'] );
			if ( $footer ) {
				update_post_meta( $post_id, '_unlockafe_footer_template', $footer );
			} else {
				delete_post_meta( $post_id, '_unlockafe_footer_template' );
			}
		}
	}
}