<?php

namespace WarrantyCart\Admin;

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

/**
 * Admin Assets Class
 */
class Assets {

	/**
	 * Constructor
	 */
	public function __construct() {
		add_action( 'init', array( $this, 'register_scripts_styles' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts_styles' ) );
	}

	/**
	 * Register admin scripts and styles.
	 *
	 * @param string $hook Current admin page hook.
	 *
	 * @return void
	 */
	public function register_scripts_styles( string $hook ): void {
		$admin_asset_file = sprintf( '%s/build/admin.asset.php', WARRANTY_CART_PATH );
		if ( ! file_exists( $admin_asset_file ) ) {
			return;
		}

		$admin_asset = require $admin_asset_file;

		/**
		 * Filter admin asset dependencies
		 *
		 * @param array $dependencies Asset dependencies.
		 */
		$admin_asset_deps = apply_filters(
			'warranty_cart_admin_asset_dependencies',
			array_merge( $admin_asset['dependencies'], array( 'jquery' ) )
		);

		$admin_asset_version = $admin_asset['version'] ?? WARRANTY_CART_VERSION;

		/**
		 * Filter admin script handle
		 *
		 * @param string $handle Script handle.
		 */
		$admin_script_handle = apply_filters( 'warranty_cart_admin_script_handle', 'warranty-admin' );

		wp_register_script(
			$admin_script_handle,
			WARRANTY_CART_URL . 'build/admin.js',
			$admin_asset_deps,
			$admin_asset_version,
			true
		);

		/**
		 * Filter admin style handle
		 *
		 * @param string $handle Style handle.
		 */
		$admin_style_handle = apply_filters( 'warranty_cart_admin_style_handle', 'warranty-admin' );

		wp_register_style(
			$admin_style_handle,
			WARRANTY_CART_URL . 'build/style-admin.css',
			array(),
			$admin_asset_version
		);

		// Enqueue admin product meta box styles
		wp_register_style(
			"$admin_style_handle-meta",
			WARRANTY_CART_URL . 'assets/css/warranty-admin.css',
			array(),
			WARRANTY_CART_VERSION
		);

		wp_set_script_translations( 'warranty-admin', 'warranty-cart' );

		/**
		 * Action after enqueuing admin assets
		 *
		 * @param string $hook Current admin page hook.
		 */
		do_action( 'warranty_cart_after_register_admin_assets', $hook );
	}

	/**
	 * Enqueue admin scripts
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts_styles( string $hook ): void {
		/**
		 * Filter whether to enqueue admin assets
		 *
		 * @param bool   $enqueue Whether to enqueue assets.
		 * @param string $hook    Current admin page hook.
		 */
		$enqueue_assets = apply_filters( 'warranty_cart_enqueue_admin_assets', true, $hook );

		if ( ! $enqueue_assets ) {
			return;
		}

		// Enqueue scripts for warranty admin page
		if ( 'toplevel_page_warranty-cart' === $hook ) {
			/*
			 * The media library, for the plan image picker.
			 *
			 * `wp.media` is not loaded on an admin page by default — it is a
			 * sizeable bundle of backbone views and templates, so WordPress
			 * makes each screen ask. Without this the picker's `wp.media` is
			 * undefined and the button does nothing at all.
			 *
			 * Called before the app's own script so the global exists by the
			 * time React mounts.
			 */
			wp_enqueue_media();

			/**
			 * Filter admin script handle
			 *
			 * @param string $handle Script handle.
			 */
			$admin_script_handle = apply_filters( 'warranty_cart_admin_script_handle', 'warranty-admin' );

			wp_enqueue_script( $admin_script_handle );

			/**
			 * Filter admin style handle
			 *
			 * @param string $handle Style handle.
			 */
			$admin_style_handle = apply_filters( 'warranty_cart_admin_style_handle', 'warranty-admin' );

			wp_enqueue_style( $admin_style_handle );

			// Enqueue admin product meta box styles
			wp_enqueue_style( "$admin_style_handle-meta" );

			wp_set_script_translations( 'warranty-admin', 'warranty-cart' );

			/**
			 * Action after enqueuing admin assets
			 *
			 * @param string $hook Current admin page hook.
			 */
			do_action( 'warranty_cart_after_enqueue_admin_assets', $hook );
		}

		// Enqueue scripts for product edit page
		if ( 'post.php' === $hook || 'post-new.php' === $hook ) {
			global $post;
			if ( isset( $post ) && 'product' === $post->post_type ) {
				wp_add_inline_script(
					'jquery',
					"
					jQuery(document).ready(function($) {
						$('#warranty_cart_product_status').on('change', function() {
							if ($(this).is(':checked')) {
								$('.warranty-fields').show();
								// Re-initialize select2 when fields are shown
								$('#associated_warranty').trigger('wc-enhanced-select-init');
							} else {
								$('.warranty-fields').hide();
							}
						});

						$('#warranty_cart_product_type').on('change', function() {
							var productType = $(this).val();
							if ('additional_service' === productType) {
								$('.show_if_additional_service').show();
							} else {
								$('.show_if_additional_service').hide();
							}
							// Coverage rules belong to main warranties: a service
							// attaches to a warranty, not to a product.
							$('.warranty_cart_main_only').toggle('main_warranty' === productType);
							// Re-initialize select2 when field is shown
							$('#associated_warranty').trigger('wc-enhanced-select-init');
						}).trigger('change');

						// Nothing about price applies to cover that is given away.
						function warrantyCartPriceFields() {
							var included = $('#warranty_cart_included').is(':checked');

							$('.warranty_cart_sold_field').toggle(!included);

							$('.warranty_cart_percentage_field').toggle(
								!included && 'percentage' === $('#warranty_cart_pricing_mode').val()
							);
						}

						$('#warranty_cart_included').on('change', warrantyCartPriceFields);

						// The percentage fields mean nothing under a fixed price.
						$('#warranty_cart_pricing_mode').on('change', warrantyCartPriceFields);

						warrantyCartPriceFields();

						// Only the picker the chosen scope actually uses. Showing
						// both means two empty fields and no clue which one counts.
						$('#warranty_cart_applies_to').on('change', function() {
							var scope = $(this).val();
							$('.warranty_cart_applies_categories_field').toggle('categories' === scope);
							$('.warranty_cart_applies_products_field').toggle('products' === scope);
						}).trigger('change');
					});
					"
				);
			}
		}
	}
}
