<?php
/** Assets
 *
 * @package BwWinnersGlobalSite
 */

namespace BwWinnersGlobalSite;

if ( ! class_exists( __NAMESPACE__ . '\Assets' ) ) {

	/**
	 * Register Assets
	 */
	class Assets {

		/**
		 * Adds hooks.
		 */
		public function __construct() {
			add_action( 'init', array( $this, 'register_assets' ) );
		}

		/**
		 * Registers styles and scripts.
		 */
		public function register_assets() {
			$asset_file = plugin_dir_path( PLUGIN_PATH ) . 'build/api-fetch/apiFetch.asset.php';

			if ( ! file_exists( $asset_file ) ) {
				error_log( 'Plugin assets not built: ' . $asset_file );
				return;
			}

			$script_settings = include $asset_file;

			// API Fetch. Similar to @wordpress/api-fetch but it accepts non-json data. Usefull with file uploads and formdata.

			wp_register_script(
				'bw-winners-api-fetch',
				plugins_url( 'build/api-fetch/apiFetch.js', PLUGIN_PATH ),
				$script_settings['dependencies'],
				$script_settings['version'],
				false
			);

			wp_localize_script(
				'bw-winners-api-fetch',
				'bwWinnersPlugins',
				array(
					'root'          => esc_url_raw( rest_url( API_NAMESPACE ) ),
					'nonce'         => wp_create_nonce( 'wp_rest' ),
					'nonceEndpoint' => admin_url( 'admin-ajax.php?action=rest-nonce' ),
				)
			);
		}
	}
}
