<?php

namespace GemBoards;

use GemBoards\Settings\Base;
use GemBoards\Utils\Helper;
use StoreEngine\Frontend\FloatingCart;

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

class Assets {

	public static function init() {
		$self = new self();
		add_action( 'wp_enqueue_scripts', [ $self, 'frontend_scripts' ], 999 );
		add_action( 'admin_enqueue_scripts', [ $self, 'enqueue_admin_assets' ] );
	}

	public function frontend_scripts() {
		$route = get_query_var( 'gemboards_app_route' );
		if ( empty( $route ) && ! Helper::get_settings( 'load_on_entire_site', false ) ) {
			return;
		}

		$this->remove_other_assets();
		if ( class_exists( FloatingCart::class ) ) {
			remove_action( 'wp_footer', [ FloatingCart::init(), 'display_cart_button' ] );
		}

		if ( ! did_action( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}

		// phpcs:disable WordPress.WP.EnqueuedResourceParameters.MissingVersion
		wp_enqueue_style(
			'gemboards-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:enable

		wp_enqueue_style( 'gemboards-app-style', GEMBOARDS_ASSETS_URI . 'build/app.css', array( 'wp-components' ), filemtime( GEMBOARDS_ASSETS_DIR_PATH . 'build/app.css' ) );

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

		wp_enqueue_script(
			'gemboards-app-scripts',
			GEMBOARDS_ASSETS_URI . sprintf( 'build/app.%s.js', GEMBOARDS_VERSION ),
			$dependencies['dependencies'],
			$dependencies['version'],
			true
		);
		wp_localize_script( 'gemboards-app-scripts', 'GemBoardsGlobal', $this->get_scripts_data() );
		wp_set_script_translations( 'gemboards-app-scripts', 'gemboards', GEMBOARDS_ROOT_DIR_PATH . 'languages' );
	}

	public function get_scripts_data(): array {
		global $gemboards_settings;

		$settings_defaults = Base::get_settings_default_data();
		$permissions       = (array) $gemboards_settings->permissions;
		$object_permissions = array_map( function ( $role ) use ( $permissions ) {
			$filtered_permissions = array_filter( $permissions, fn( $permission ) => $permission->{$role->get_role()} );

			return array_merge( $role->get_data(), [
				'permissions' => array_keys( $filtered_permissions ),
			] );
		}, Helper::get_user_roles( get_current_user_id() ) );

		return apply_filters( 'gemboards/frontend_scripts_data', [
			'nonce'                 => wp_create_nonce( 'wp_rest' ),
			'gemboards_nonce'       => wp_create_nonce( 'gemboards_nonce' ),
			'rest_url'              => esc_url_raw( rest_url() ),
			'namespace'             => GEMBOARDS_PLUGIN_SLUG . '/v1/',
			'plugin_root_url'       => GEMBOARDS_PLUGIN_ROOT_URI,
			'plugin_root_path'      => GEMBOARDS_ROOT_DIR_PATH,
			'ajax_url'              => esc_url( admin_url( 'admin-ajax.php' ) ),
			'admin_url'             => admin_url(),
			'site_url'              => site_url(),
			'route_path'            => wp_parse_url( admin_url(), PHP_URL_PATH ),
			'current_user_id'       => get_current_user_id(),
			'is_rtl'                => is_rtl(),
			'is_admin'              => is_admin(),
			'title'                 => $gemboards_settings->title ?? $settings_defaults['title'],
			'path'                  => $gemboards_settings->path ?? $settings_defaults['path'],
			'logo'                  => $gemboards_settings->logo ?? $settings_defaults['logo'],
			'logo_url'              => ! empty( $gemboards_settings->logo ) ? wp_get_attachment_image_url( $gemboards_settings->logo, 'full' ) : str_replace( rtrim( site_url(), '/' ), '', plugins_url( '/assets/images/logo.svg', GEMBOARDS_PLUGIN_FILE ) ),
			'notification_position' => $gemboards_settings->notification_position ?? $settings_defaults['notification_position'],
			'is_pro'                => Helper::has_pro(),
			'current_user_can'      => [
				'manage_options'   => current_user_can( 'manage_options' ),
				'manage_gemboards' => current_user_can( 'manage_gemboards' ),
				'app_route'        => [
					'route'      => get_query_var( 'gemboards_app_route' ),
					'board_id'   => get_query_var( 'board_id' ),
					'project_id' => get_query_var( 'project_id' ),
					'sprint_id'  => get_query_var( 'sprint_id' ),
					'team_id'    => get_query_var( 'team_id' ),
				],
			],
			'object_permissions'    => $object_permissions,
		] );
	}

	public function enqueue_admin_assets() {
		$screen = get_current_screen();
		if ( 'toplevel_page_gemboards-settings' !== $screen->id ) {
			return;
		}

		if ( ! did_action( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}

		wp_enqueue_style( 'gemboards-app-style', GEMBOARDS_ASSETS_URI . 'build/admin.css', array(), filemtime( GEMBOARDS_ASSETS_DIR_PATH . 'build/admin.css' ) );

		wp_enqueue_style( 'gemboards-settings-style', GEMBOARDS_ASSETS_URI . 'build/admin.css', array( 'wp-components' ), filemtime( GEMBOARDS_ASSETS_DIR_PATH . 'build/admin.css' ) );

		$dependencies = include GEMBOARDS_ASSETS_DIR_PATH . sprintf( 'build/admin.%s.asset.php', GEMBOARDS_VERSION );

		wp_enqueue_script(
			'gemboards-settings-scripts',
			GEMBOARDS_ASSETS_URI . sprintf( 'build/admin.%s.js', GEMBOARDS_VERSION ),
			$dependencies['dependencies'],
			$dependencies['version'],
			true
		);

		wp_set_script_translations( 'gemboards-settings-scripts', 'gemboards', GEMBOARDS_ROOT_DIR_PATH . 'languages' );
		wp_localize_script(
			'gemboards-settings-scripts',
			'GemBoardsGlobal',
			apply_filters('gemboards/admin_scripts_data', $this->get_scripts_data())
		);
	}

	public function remove_other_assets() {
		global $wp_scripts, $wp_styles;
		// Remove plugin scripts
		if ( ! empty( $wp_scripts->queue ) ) {
			foreach ( $wp_scripts->queue as $handle ) {
				wp_dequeue_script( $handle );
				wp_deregister_script( $handle );
			}
		}

		// Remove plugin styles
		if ( ! empty( $wp_styles->queue ) ) {
			foreach ( $wp_styles->queue as $handle ) {
				wp_dequeue_style( $handle );
				wp_deregister_style( $handle );
			}
		}
	}
}
