<?php

/**
 * Unlockafe Addons 
 *
 * @package Unlockafe_addons
 * @subpackage Unlockafe_addons\Classes
 */

namespace Unlockafe_addons\Classes;

use Elementor\Plugin;
use Error;

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

class Widget_manager {

	const UNLOCKAFE_ACTIVE_WIDGETS = '_unlockafe_active_widgets';

	public $registered_widgets = array();

	public function __construct( $registered_widgets ) {
		$this->registered_widgets = $registered_widgets;
	}

	public function unlockafe_elementor_after_save( $post_id, $editor_data ) {
		$active_widgets = $this->unlockafe_active_widgets( $editor_data );
		$this->save_active_widgets( $post_id, $active_widgets );
	}

	public function unlockafe_active_widgets( $editor_data ) {
		$active_widgets = [];

		Plugin::$instance->db->iterate_data( $editor_data, function ($element) use (&$active_widgets) {

			//get widget type
			if ( ! empty( $element['widgetType'] ) ) {
				$widget_type = $element['widgetType'];
			} else {
				$widget_type = $element['elType'];
			}

			if ( ! empty( $widget_type ) && strpos( $widget_type, 'unlockafe-' ) !== false ) {
				$active_widgets[ $widget_type ] = $widget_type;
			}
		} );

		// error_log( print_r($active_widgets, true));
		return $active_widgets;
	}

	public function save_active_widgets( $post_id, $active_widgets ) {

		if ( \defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return $post_id;
		}
		$document = is_object( Plugin::$instance->documents ) ? Plugin::$instance->documents->get( $post_id ) : [];


		if ( ! in_array( get_post_status( $post_id ), [ 'publish', 'private' ] ) || ( ! is_object( $document ) && ! $document->is_built_with_elementor() ) ) {
			return false;
		}

		// one more condition left ( Check widgets )

		try {
			// add all the active widgets to db
			update_post_meta( $post_id, self::UNLOCKAFE_ACTIVE_WIDGETS, $active_widgets );

			// remove existing assets
			$this->remove_assets( $post_id );

			// create file if ! exist
			$this->create_dir();

			// build the scripts
			$this->build_assets( $post_id, $active_widgets );
			return true;

		} catch (\Exception $e) {
			return false;
		}
	}

	/**
	 * remove_assets
	 * Removing existing assets
	 * 
	 * @param int $post_id
	 * @return void
	 */
	public function remove_assets( int $post_id = null ) {
		foreach ( [ 'css', 'js' ] as $ext ) {

			// build file path
			$file_id = ( $post_id != null ) ? '-' . $post_id : '';
			$file    = UNLOCKAFE_WP_ASSETS_PATH . 'unlockafe' . $file_id . '.' . $ext;

			// check and delete
			if ( file_exists( $file ) ) {
				wp_delete_file( $file );
			}
		}
	}

	public function build_assets( $post_id, $active_widgets ) {
		// build css
		$this->get_script( $post_id, $active_widgets, 'css' );
		// build js
		$this->get_script( $post_id, $active_widgets, 'js' );
	}

	public function get_script( $post_id, $active_widgets, $ext ) {
		$file_id   = ( $post_id != '' && $post_id !== null ) ? '-' . $post_id : '';
		$main_file = UNLOCKAFE_WP_ASSETS_PATH . UNLOCKAFE_init()::PREFIX . $file_id . '.' . $ext;

		// get all the scriont ${ext}
		$output = '';
		$paths  = [];

		// loop throw the active widgets

		if ( $post_id != null ) {
			foreach ( $active_widgets as $w ) {
				if ( isset( $this->registered_widgets['widgets'][ $w ][ $ext ] ) ) {
					// collect all the path
					if ( is_array( $this->registered_widgets['widgets'][ $w ][ $ext ] ) ) {
						foreach ( $this->registered_widgets['widgets'][ $w ][ $ext ] as $path ) {

							if( $path['context'] == 'lib'){
								continue;
							}

							// append the file to $path array
							$paths[] = $path['file'];
						}
					}
				}
			}
		} else {

			foreach ( $this->registered_widgets['widgets'] as $w ) {
				if ( isset( $w[ $ext ] ) && is_array( $w[ $ext ] ) ) {

					foreach ( $w[ $ext ] as $path ) {
						// append the file to $path array
						if( $path['context'] == 'lib' && isset($path['handle']) ){
							if( $ext == 'css' ){
								wp_enqueue_style( 
									$path['handle'],
									$path['file'],
									[],
									UNLOCKAFE_VERSION,
									'all'
								);
							}
							if( $ext == 'js' ){
								$dependencies = isset($path['deps']) ? $path['deps'] : [];
								wp_enqueue_script( 
									$path['handle'],
									$path['file'],
									$dependencies,
									UNLOCKAFE_VERSION,
									true
								);
							}
							
						}else{
							$paths[] = $path['file'];
						}
						
						
					}
				}
			}
		}

		// Initialize the WP_Filesystem
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once( ABSPATH . 'wp-admin/includes/file.php' );
		}
		global $wp_filesystem;
		WP_Filesystem();
		
		if ( $ext == 'js' ) {
			$output .= '(function($){"use strict";';
		}
		
		// Concat all the assets by reading files directly instead of using slow HTTP requests
		foreach ( $paths as $file_url ) {
			$file_path = str_replace( UNLOCKAFE_ADDONS_URL, UNLOCKAFE_ADDONS_PATH, $file_url );
			if ( $wp_filesystem->exists( $file_path ) ) {
				$content = $wp_filesystem->get_contents( $file_path );
				if ( $content ) {
					// Remove existing wrapper if present (multiple patterns)
					$content = preg_replace('/^;\s*\(function\s*\(\$\)\s*\{[\'"]use strict[\'"];?/i', '', $content);
					$content = preg_replace('/^\(function\s*\(\$\)\s*\{[\'"]use strict[\'"];?/i', '', $content);
					$content = preg_replace('/\}\(jQuery\)\)\s*;?\s*$/i', '', $content);
					$content = preg_replace('/\}\(jQuery\)\s*;?\s*$/i', '', $content);
					// Trim and add content
					$content = trim($content);
					if ( !empty($content) ) {
						// Remove trailing semicolon if exists to avoid double semicolons
						$content = rtrim($content, ';');
						// Ensure content ends properly
						if ( !empty($content) ) {
							$output .= $content . ';';
						}
					}
				}
			}
		}

		if ( $ext == 'js' ) {
			$output .= '})(jQuery);';
		}

		// put all the styles
		$wp_filesystem->put_contents( $main_file, $output, FS_CHMOD_FILE );
	}

	public function singuler_file( $file_name ) {

		// return if empty
		if ( empty( $file_name ) )
			return;

		// retrive the post ID
		$post_id = preg_replace( '/[^0-9]/', '', $file_name );

		$active_widgets = get_post_meta( $post_id, self::UNLOCKAFE_ACTIVE_WIDGETS, true );

		if ( ! empty( $active_widgets ) ) {
			// enqueu styles
			$style_handle = UNLOCKAFE_init()::PREFIX . '-' . $post_id;
			$js_handle    = UNLOCKAFE_init()::PREFIX . '-' . $post_id;

			// load css
			wp_enqueue_style(
				$style_handle,
				UNLOCKAFE_WP_ASSETS_URI . $style_handle . '.css',
				[ UNLOCKAFE_init()::PREFIX . '-public' ],
				get_post_modified_time(),
				'all'
			);

			// load js
			wp_enqueue_script(
				$js_handle,
				UNLOCKAFE_WP_ASSETS_URI . $js_handle . '.js',
				['jquery', 'elementor-frontend'],
				get_post_modified_time(),
				true
			);

		}

		return $file_name;
	}

	/**
	 * Summary of add_elementor_assets
	 * 
	 * This method is responsible for enqueue and bundle css
	 * of Elementor
	 * 
	 * @return void
	 */
	public function add_elementor_assets() {

		if ( Plugin::instance()->editor->is_edit_mode() || Plugin::instance()->preview->is_preview_mode() ) {

			$this->build_elementor_assets();

			// styles
			wp_enqueue_style(
				UNLOCKAFE_init()::PREFIX,
				UNLOCKAFE_WP_ASSETS_URI . UNLOCKAFE_init()::PREFIX . '.css',
				[],
				UNLOCKAFE_VERSION
			);

			// scripts
			wp_enqueue_script(
				UNLOCKAFE_init()::PREFIX,
				UNLOCKAFE_WP_ASSETS_URI . UNLOCKAFE_init()::PREFIX . '.js',
				[ 'jquery' ],
				UNLOCKAFE_VERSION,
				true
			);
		}
	}


	public function build_elementor_assets() {
		// removing old assets
		$this->remove_assets();

		// check and create dir
		$this->create_dir();

		// build assets (pass null to include all widgets)
		$this->build_assets( null, null );
	}

	/**
	 * Regenerate per-post CSS/JS bundles for all posts that use Unlockafe widgets.
	 * Call this on plugin upgrade so updated widget CSS/JS is applied without requiring users to re-save each page.
	 *
	 * @return int Number of posts whose assets were regenerated.
	 */
	public function regenerate_assets_on_upgrade() {
		$post_ids = get_posts( [
			'post_type'      => 'any',
			'post_status'    => [ 'publish', 'private', 'draft' ],
			'posts_per_page' => -1,
			'fields'         => 'ids',
			'meta_key'       => self::UNLOCKAFE_ACTIVE_WIDGETS,
			'meta_compare'   => 'EXISTS',
		] );
		if ( empty( $post_ids ) ) {
			return 0;
		}
		$this->create_dir();
		$count = 0;
		foreach ( $post_ids as $post_id ) {
			$active_widgets = get_post_meta( $post_id, self::UNLOCKAFE_ACTIVE_WIDGETS, true );
			if ( ! is_array( $active_widgets ) || empty( $active_widgets ) ) {
				continue;
			}
			$this->remove_assets( (int) $post_id );
			$this->build_assets( (int) $post_id, $active_widgets );
			$count++;
		}
		return $count;
	}

	/**  
	 * create_dir to create Folder
	 * in specific directory
	 * 
	 * @return void
	 */
	public function create_dir() {
		if ( ! file_exists( UNLOCKAFE_WP_ASSETS_PATH ) ) {
			wp_mkdir_p( UNLOCKAFE_WP_ASSETS_PATH );
		}
	}

	public function unlockafe_editor_styles() {
		wp_enqueue_style( UNLOCKAFE_init()::PREFIX . '-editor', UNLOCKAFE_ASSETS . 'editor.css', [], UNLOCKAFE_VERSION );
		
		// Add inline CSS with absolute URL for logo to ensure it works everywhere
		$logo_url = UNLOCKAFE_ASSETS . 'images/unlockafe-editor.svg';
		$inline_css = "
		/* Set CSS variable with absolute URL */
		:root {
			--unlockafe-icon-url: url('{$logo_url}');
		}
		
		/* Addon logo in search results - direct wrapper ::before (no :has()), absolute URL */
		.elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe']::before,
		.elementor-panel-search-results .elementor-element-wrapper[data-widget*='unlockafe']::before {
			content: \"\" !important;
			width: 35px !important;
			height: 35px !important;
			position: absolute !important;
			top: 8px !important;
			left: 5px !important;
			background: url('{$logo_url}') no-repeat center center / contain !important;
			display: block !important;
		}
		.elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'],
		.elementor-panel-search-results .elementor-element-wrapper[data-widget*='unlockafe'] {
			position: relative !important;
			padding-left: 45px !important;
		}
		.elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element::before,
		.elementor-panel-search-results .elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element::before {
			content: none !important;
			display: none !important;
		}
		#elementor-panel-elements .elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe']::before,
		.elementor-panel-elements-wrapper .elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe']::before {
			content: \"\" !important;
			width: 35px !important;
			height: 35px !important;
			position: absolute !important;
			top: 8px !important;
			left: 5px !important;
			background: url('{$logo_url}') no-repeat center center / contain !important;
			display: block !important;
		}
		#elementor-panel-elements .elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element::before,
		.elementor-panel-elements-wrapper .elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element::before {
			content: none !important;
			display: none !important;
		}
		#elementor-panel-elements .elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'],
		.elementor-panel-elements-wrapper .elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'] {
			position: relative !important;
			padding-left: 45px !important;
		}
		
		/* Universal: addon logo for ANY unlockafe widget in panel that is NOT in category (absolute URL) */
		#elementor-panel-elements [data-widget*='unlockafe']:not(#elementor-panel-category-unlockafe-addons [data-widget*='unlockafe'])::before {
			content: \"\" !important;
			width: 35px !important;
			height: 35px !important;
			position: absolute !important;
			top: 8px !important;
			left: 5px !important;
			background: url('{$logo_url}') no-repeat center center / contain !important;
			display: block !important;
		}
		#elementor-panel-elements [data-widget*='unlockafe']:not(#elementor-panel-category-unlockafe-addons [data-widget*='unlockafe']) {
			position: relative !important;
			padding-left: 45px !important;
		}
		
		/* Replace background-image for ALL unlockafe widget icons - Most comprehensive approach */
		.elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon'],
		.elementor-element-wrapper[data-widget*='unlockafe'] [class^='eicon-'],
		.elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element-icon,
		.elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon'],
		.elementor-element-wrapper[data-widget*='unlockafe'] i[class^='eicon-'],
		.elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element-icon-wrapper [class*='eicon'],
		.elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element-icon-wrapper i,
		.elementor-panel-element-wrapper[data-widget*='unlockafe'] [class*='eicon'],
		.elementor-panel-element-wrapper[data-widget*='unlockafe'] i[class*='eicon'],
		[data-widget*='unlockafe'] [class*='eicon'],
		[data-widget*='unlockafe'] [class^='eicon-'],
		[data-widget*='unlockafe'] .elementor-element-icon,
		[data-widget*='unlockafe'] i[class*='eicon'],
		.elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon'],
		.elementor-panel-elements-search-results .elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon'],
		.elementor-panel-elements-view .elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon'],
		.elementor-panel-elements-view .elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon'],
		#elementor-panel-elements .elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon'],
		#elementor-panel-elements .elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon'],
		.elementor-panel .elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon'],
		.elementor-panel .elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon'],
		.elementor-element-wrapper[data-widget*='unlockafe'] i,
		.elementor-element-wrapper[data-widget*='unlockafe-email-capture'] i,
		.elementor-element-wrapper[data-widget*='unlockafe-email-capture'] [class*='eicon'],
		.elementor-element-wrapper[data-widget*='unlockafe-email-capture'] .elementor-element-icon {
			background-image: url('{$logo_url}') !important;
			background-size: contain !important;
			background-repeat: no-repeat !important;
			background-position: center center !important;
			font-size: 0 !important;
			font-family: none !important;
			line-height: 0 !important;
			opacity: 1 !important;
			color: transparent !important;
			text-indent: -9999px !important;
			width: 28px !important;
			height: 28px !important;
			min-width: 28px !important;
			min-height: 28px !important;
			max-width: 28px !important;
			max-height: 28px !important;
			display: inline-block !important;
			visibility: visible !important;
			position: relative !important;
		}
		
		/* Hide original font icon content using ::before and ::after pseudo-elements */
		.elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon']::before,
		.elementor-element-wrapper[data-widget*='unlockafe'] [class*='eicon']::after,
		.elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon']::before,
		.elementor-element-wrapper[data-widget*='unlockafe'] i[class*='eicon']::after,
		.elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element-icon::before,
		.elementor-element-wrapper[data-widget*='unlockafe'] .elementor-element-icon::after,
		[data-widget*='unlockafe'] [class*='eicon']::before,
		[data-widget*='unlockafe'] [class*='eicon']::after,
		[data-widget*='unlockafe'] i[class*='eicon']::before,
		[data-widget*='unlockafe'] i[class*='eicon']::after {
			display: none !important;
			content: '' !important;
			visibility: hidden !important;
			opacity: 0 !important;
			width: 0 !important;
			height: 0 !important;
			font-size: 0 !important;
		}

		/* Advance Mega Menu: when a menu row is expanded, hide main Add Menu button so only Add Category / Add Submenu show */
		.elementor-control-menu_items .elementor-repeater-fields-wrapper:has(.elementor-repeater-row.elementor-active) + .elementor-button-wrapper,
		.elementor-control-menu_items .elementor-repeater-fields-wrapper:has(li.elementor-repeater-row--open) + .elementor-button-wrapper {
			display: none !important;
		}
		";
		wp_add_inline_style( UNLOCKAFE_init()::PREFIX . '-editor', $inline_css );
	}

	public function load_plugin_dependency(){
		
		//

	}
}
