<?php
namespace ZenCommunity;

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

use ZenCommunity\Classes\RoleManager;
use ZenCommunity\Database\Models\{
	Profile,
	Group
};
use Throwable;
use stdClass;
class Assets {

	public static function init() {
		$self = new self();
		add_action( 'wp_enqueue_scripts', [ $self, 'frontend_scripts' ] );
		add_action( 'admin_enqueue_scripts', [ $self, 'enqueue_admin_assets' ] );
		add_filter( 'zencommunity/assets/script_data', [ self::CLASS, 'add_socket_data' ] );
		if(!is_admin()){
			add_action( 'wp_print_styles', [ self::CLASS, 'remove_theme_styles' ] , 1 );
			add_action( 'wp_print_scripts', [ self::CLASS, 'remove_theme_scripts' ] , 1 );
		}
		add_action( 'wp_head', [ self::CLASS, 'add_theme_mode_css' ] , 1 );
	}
	
	public static function is_enqueueable( string $src ) : bool {
		$whilists = apply_filters( 
			'zencommunity/enqueueable/plugins',
			[
				'zencommunity',
				'zencommunity-pro',
				'zencommunity-live-chat',
			]
		);

		$plugin_dir = plugins_url();
		foreach( $whilists as $plugin ) {
			if ( strpos( $src, "{$plugin_dir}/{$plugin}" ) === 0 ) 
				return true;
		}
		return false;
	}
	public static function remove_theme_scripts() : void {
        global $zencommunity_settings;
        $load_on_entire_site = (bool) Helper::get_setting( 'load_on_entire_site', false ); // $zencommunity_settings->load_on_entire_site ?? false;
		
		if ( ! $load_on_entire_site && get_query_var( ZENCOMMUNITY_APP_ROUTE_QUERY_VAR ) !== 'community' ) {
			return;
		}

		global $wp_scripts;

		$theme_uris = [
			get_stylesheet_directory_uri(), // child theme
			get_template_directory_uri(),   // parent theme
		];
		
		foreach ( $wp_scripts->queue ?? [] as $handle ) {
			$script = wp_scripts()->registered[ $handle ] ?? null;

			if ( $script && isset( $script->src ) ) {
				foreach ( $theme_uris as $theme_uri ) {
					if ( 
						strpos( $script->src, $theme_uri ) === 0  ||
						! static::is_enqueueable( $script->src )
					) {
						// var_dump( 'Dequeued theme script: ' . $handle );
						wp_dequeue_script( $handle );
						wp_deregister_script( $handle );
						break;
					}
				}
			}
		}
	}

	public static function remove_theme_styles() : void {
        global $zencommunity_settings;
        $load_on_entire_site = (bool) Helper::get_setting( 'load_on_entire_site', false ); //$zencommunity_settings->load_on_entire_site ?? false;
		if ( ! $load_on_entire_site && get_query_var( ZENCOMMUNITY_APP_ROUTE_QUERY_VAR ) !== 'community' ) {
			return;
		}

		global $wp_styles;

		$theme_uris = [
			get_stylesheet_directory_uri(),
			get_template_directory_uri(),
		];

		foreach ( $wp_styles->queue as $handle ) {
			$style = wp_styles()->registered[ $handle ] ?? null;

			if ( $style && isset( $style->src ) ) {
				foreach ( $theme_uris as $theme_uri ) {
					if ( 
						strpos( $style->src, $theme_uri ) === 0 ||
						! static::is_enqueueable( $style->src )
					) {
						// var_dump( 'Dequeuing: ' . $handle );
						wp_dequeue_style( $handle );
						wp_deregister_style( $handle );
						break;
					}
				}
			}
		}
	}

	public static function add_socket_data( array $data ) : array {
        try {
			$roles = RoleManager::get_global_roles_by_user_id( get_current_user_id() );
			foreach ( $roles as $role => [ 'capabilities' => $capabilities ] ) {
				foreach ( $capabilities as $capability => [ 'disabled' => $disabled ] ) {
					$data['global_roles'][$role][$capability] = ! $disabled;
				}
			}
        }
        catch ( Throwable $e ) {}

		return $data;
	}
	
	public static function get_theme_mode_css( ?stdClass $settings) : array {
        if ( ! isset( $settings->theme ) )
            $settings->theme = new stdClass;

        if ( ! isset( $settings->theme->light ) )
            $settings->theme->light = new stdClass;

        if ( ! isset( $settings->theme->dark ) )
            $settings->theme->dark = new stdClass;

		$uid = get_current_user_id();
		$theme_mode = $uid ? get_user_meta(
				$uid,
				'zenc_theme_mode',
				true
			) : null;
		$theme_mode = in_array( $theme_mode, [ 'dark', 'light' ] ) ? $theme_mode : 'light';

		return [
			'theme_mode' => $theme_mode,
			'dark' => wp_parse_args(
				$settings->theme->dark ?? [],
				zencommunity_default_theme_settings()['theme']['dark']
			),
			'light' => wp_parse_args(
				$settings->theme->light ?? [],
				zencommunity_default_theme_settings()['theme']['light']
			)
		]; 
	}

	public static function add_theme_mode_css() : void {
		global $zencommunity_settings;
		$load_on_entire_site = (bool) Helper::get_setting( 'load_on_entire_site', false );
		if ( false === $load_on_entire_site  && 'community' !== get_query_var( ZENCOMMUNITY_APP_ROUTE_QUERY_VAR )  ) { 
			return;
		}

		$theme_settings = static::get_theme_mode_css( $zencommunity_settings );
		$curr_theme_fields = $theme_settings[$theme_settings['theme_mode']];
		
		// Map old variable names to new ones
		$variable_mapping = [
			'content_body_color' => 'body_background',
			'content_background_color' => 'background',
			'text_color' => 'font_color',
		];
		
		// Rename the keys before processing
		foreach ( $variable_mapping as $old_key => $new_key ) {
			if ( isset( $curr_theme_fields[ $old_key ] ) ) {
				$curr_theme_fields[ $new_key ] = $curr_theme_fields[ $old_key ];
				unset( $curr_theme_fields[ $old_key ] );
			}
		}
		
		array_walk(
			$curr_theme_fields,
			function( string &$val, string $key, string $prefix ) : void {
				$val = "\t\t" . $prefix . str_replace( '_', '-', $key ) . ': ' . $val . ';';
			},
			'--zencom-'
		);
		
		echo "<style>\n" . 
			"\t:root {\n".
				implode( "\n", $curr_theme_fields ) . "\n" .
			"\t}\n" . 
			"</style>\n";
	}

	public function frontend_scripts() {
		global $zencommunity_settings;
        $load_on_entire_site = (bool) Helper::get_setting( 'load_on_entire_site', false );
		if ( false === $load_on_entire_site  && 'community' !== get_query_var( ZENCOMMUNITY_APP_ROUTE_QUERY_VAR )  ) { 
			return;
		}
		if ( ! did_action( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}

		wp_enqueue_style( 'zencommunity-app-style', ZENCOMMUNITY_ASSETS_URI . 'build/app.css', array(), filemtime( ZENCOMMUNITY_ASSETS_DIR_PATH . 'build/app.css' ), 'all' );

		$dependencies = include ZENCOMMUNITY_ASSETS_DIR_PATH . sprintf( 'build/app.%s.asset.php', ZENCOMMUNITY_VERSION );

		wp_enqueue_script(
            'zencommunity-app-scripts',
            ZENCOMMUNITY_ASSETS_URI . sprintf( 'build/app.%s.js', ZENCOMMUNITY_VERSION ),
            $dependencies['dependencies'],
            $dependencies['version'],
            true
        );
		
		wp_localize_script( 'zencommunity-app-scripts', 'ZencommunityGlobal', static::localized_data() );
		
		// Enqueue Google Font
		wp_enqueue_style(
			'zencommunity-web-font',
			'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap',
			[],
			null // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
		);
		wp_set_script_translations( 'zencommunity-app-scripts', 'zencommunity', ZENCOMMUNITY_ROOT_DIR_PATH . 'i18n/languages' );
	}

	public static function localized_data( ?string $type = null) : ?array {
		global $zencommunity_settings;
		return apply_filters(
			'zencommunity/assets' . ( empty( $type ) ? '' : '/' . $type ) . '/script_data',
			[
				//  Security
				'timestamps'         => time(),
				'is_configured'      => ! empty( get_option( ZENCOMMUNITY_SETTINGS_NAME ) ),
				'is_permalink_plain' => empty( get_option( 'permalink_structure' ) ),
				'nonce'              => wp_create_nonce( 'wp_rest' ),
				'community_nonce'    => wp_create_nonce( 'zencommunity_nonce' ),

				//  URLs & Paths
				'rest_url'           => esc_url_raw( rest_url() ),
				'ajaxurl'            => admin_url( 'admin-ajax.php' ),
				'site_url'           => site_url(),
				'plugin_root_url'    => plugins_url( '', ZENCOMMUNITY_PLUGIN_FILE ),
				'plugin_root_path'   => plugin_dir_path( ZENCOMMUNITY_PLUGIN_FILE ),
				'current_permalink'  => get_permalink(),
				'is_plain_permalink' => ! get_option( 'permalink_structure' ),
				'active_addons'      => array_values( ( new Classes\Addon\Manager() )->get_activated() ),

				//  REST API
				'namespace'          => 'zencommunity/v1',
				'route_path'         => '/',
				'is_pro_active'      => is_plugin_active( 'zencommunity-pro/zencommunity-pro.php' ),

				//  Current User
				'is_logged_in'        => is_user_logged_in(),
				'current_logged_user' => Profile::current(),
				'current_user_can'    => [
					'manage_options'     => current_user_can( 'manage_options' ),
				],
				// 'groups' 		  => Group::get_categories_with_its_groups( get_current_user_id() ),

				//  Settings from plugin
				'community_path'           => $zencommunity_settings->path ?? null,
				'community_visibility'     => $zencommunity_settings->community_visibility ?? null,
				'allow_member_registration'=> $zencommunity_settings->allow_member_registration ?? null,
				'site_logo'=> $zencommunity_settings->site_logo ?? null,
				'notification_position'=> $zencommunity_settings->notification_position ?? null,
				'theme_settings' => static::get_theme_mode_css( $zencommunity_settings ),
				'permitted_social_sites_for_link_sharing' => $zencommunity_settings->permitted_social_sites_for_link_sharing ?? [
                    'facebook',
                    'x',
                    'instagram',
                    'linkedin',
                    'email',
				],
				'pass_reset_url' => site_url( '/wp-login.php?action=lostpassword' ),
					
				'is_feed_title_required'=> $zencommunity_settings->feed->is_title_required ?? false,
				'feed_default_sort_by'=> $zencommunity_settings->feed->default_sort_by ?? 'created_at',
			]
		);
	}

	public function enqueue_admin_assets() : void {
		wp_enqueue_style(
			'zencommunity-admin-menu-style', ZENCOMMUNITY_ASSETS_URI . 'css/admin.menu.css',
			[],
			'1.0.0'
		);
		
		$screen = get_current_screen();
		if ($screen->id === 'toplevel_page_zencommunity-settings') {
			
			if ( ! did_action( 'wp_enqueue_media' ) ) {
				wp_enqueue_media();
			}

			wp_enqueue_style( 'zencommunity-app-style', ZENCOMMUNITY_ASSETS_URI . 'build/app.css', array(), filemtime( ZENCOMMUNITY_ASSETS_DIR_PATH . 'build/app.css' ), 'all' );

			wp_enqueue_style( 'zencommunity-settings-style', ZENCOMMUNITY_ASSETS_URI . 'build/settings.css', array( 'wp-components' ), filemtime( ZENCOMMUNITY_ASSETS_DIR_PATH . 'build/settings.css' ), 'all' );

			$dependencies = include ZENCOMMUNITY_ASSETS_DIR_PATH . sprintf( 'build/settings.%s.asset.php', ZENCOMMUNITY_VERSION );

			wp_enqueue_script(
				'zencommunity-settings-scripts',
				ZENCOMMUNITY_ASSETS_URI . sprintf( 'build/settings.%s.js', ZENCOMMUNITY_VERSION ),
				$dependencies['dependencies'],
				$dependencies['version'],
				true
			);

			wp_set_script_translations( 'zencommunity-settings-scripts', 'zencommunity', ZENCOMMUNITY_ROOT_DIR_PATH . 'i18n/languages' );

			// wp_localize_script( 'zencommunity-settings-scripts', 'zencommunitySettings', [
			// 	'root'  => esc_url_raw(rest_url()),
			// 	'nonce' => wp_create_nonce('wp_rest'),
			// ] );
			wp_localize_script( 'zencommunity-settings-scripts', 'ZencommunityGlobal', apply_filters(
			'zencommunity/assets/script_data',
				[
					//  Security
					'timestamps'         => time(),
					'is_configured'      => ! empty( get_option( ZENCOMMUNITY_SETTINGS_NAME ) ),
					'is_permalink_plain' => empty( get_option( 'permalink_structure' ) ),
					'nonce'              => wp_create_nonce( 'wp_rest' ),
					'community_nonce'    => wp_create_nonce( 'zencommunity_nonce' ),

					//  URLs & Paths
					'rest_url'           => esc_url_raw( rest_url() ),
					'ajaxurl'            => admin_url( 'admin-ajax.php' ),
					'site_url'           => site_url(),
					'plugin_root_url'    => plugins_url( '', ZENCOMMUNITY_PLUGIN_FILE ),
					'plugin_root_path'   => plugin_dir_path( ZENCOMMUNITY_PLUGIN_FILE ),
					'current_permalink'  => get_permalink(),
					'is_plain_permalink' => ! get_option( 'permalink_structure' ),
					// 'active_addons'      => array_values( ( new Classes\Addon\Manager() )->get_activated() ), // no need

					//  REST API
					'namespace'          => 'zencommunity/v1',
					'route_path'         => '/',
					'is_pro_active'      => is_plugin_active( 'zencommunity-pro/zencommunity-pro.php' ),

					//  Current User
					'current_logged_user' => Profile::current(),
					'current_user_can'    => [
						'manage_options'     => current_user_can( 'manage_options' ),
					],
					// 'groups' 		  => Group::get_categories_with_its_groups( get_current_user_id() ),  // no need

					//  Settings from plugin
					'community_path'           => $zencommunity_settings->path ?? null,
					'community_visibility'     => $zencommunity_settings->community_visibility ?? null,
					'allow_member_registration'=> $zencommunity_settings->allow_member_registration ?? null,
					'site_logo'=> $zencommunity_settings->site_logo ?? null,
					'notification_position'=> $zencommunity_settings->notification_position ?? null,
					// license
					'license_page_url' => admin_url('options-general.php?page=zencommunity-pro'),
					
					'is_feed_title_required'=> $zencommunity_settings->feed->is_title_required ?? false,
					'feed_default_sort_by'=> $zencommunity_settings->feed->default_sort_by ?? 'created_at',
				]
			) );
		}
	}
}