<?php

/**
 * Enqueue class for the Custom Product Badge for WooCommerce plugin.
 * * @package Custom Product Badge For WooCommerce
 */

namespace CPBW\Backend;

use CPBW\App\Badge;
use CPBW\Libs\Assets;


class Enqueue {

    /**
	* Script handle for custom-product-badge-for-woocommerce.
	*/
	const SCRIPT_HANDLE = 'cpbw-dashboard';

    /**
	* Development script path for custom-product-badge-for-woocommerce.
	*/
	const DEV_SCRIPT = 'backend/views/src/main.jsx';

    /**
	* Localize Object name for custom-product-badge-for-woocommerce.
	*/
	const LOCALIZE_OBJ_NAME = 'CPBW';

    public function __construct() {
        add_action('admin_enqueue_scripts', [$this, 'admin_script']);
    }

    /**
     * Enqueue styles and scripts on the admin dashboard.
     *
     * @param string $page The current admin page.
     * @return void
     */
    public function admin_script($page) {
        // Global Admin Assets (Load on all admin pages if needed)
        wp_enqueue_style('cpbw-admin-css', CPBW_ASSETS . '/src/styles/cpbw-admin-global.css', [], CPBW_VERSION);

        wp_enqueue_script('cpbw-notice-script', CPBW_ASSETS . '/src/js/plugin-notice.js', ['jquery'], CPBW_VERSION, true);
        wp_localize_script('cpbw-notice-script', 'CPBW_NOTICE', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('cpbw_dismiss_notice'),
        ]);

        // Plugin Specific Assets (Only load on the plugin settings page)
        if ($page !== 'toplevel_page_cpbw') {
            return;
        }

        // wp_enqueue_style('cpbw-common-style', CPBW_ASSETS . '/src/styles/cpbw-common-style.css', [], CPBW_VERSION);
        
        if (function_exists('wp_enqueue_media')) {
            wp_enqueue_media();
        }

        //script for menu page
        wp_enqueue_script('cpbw-admin-menu', CPBW_ASSETS . '/src/js/cpbw-admin-menu.js', [], CPBW_VERSION, true);

        Assets\enqueue_asset(
			CPBW_DIR_PATH . 'assets/build',
			self::DEV_SCRIPT,
			$this->get_config()
		);
		wp_localize_script( self::SCRIPT_HANDLE, self::LOCALIZE_OBJ_NAME, $this->get_data() );
    }

    /**
	* Get the script configuration.
	*
	* @return array The script configuration.
	*/
    public function get_config() {
        return array(
            'dependencies' => array( 'react', 'react-dom' ),
            'handle'       => self::SCRIPT_HANDLE,
            'in-footer'    => true,
        );
	}

    /**
	* Get data for script localization.
	*
	* @return array The localized script data.
	*/
	public function get_data() {
		return array(
			'rest_nonce'        => wp_create_nonce( 'wp_rest' ),
            'rest_url'          => rest_url('cpbw/v1'),
            'badge_image_file'  => CPBW_URL,
            'is_pro'            => is_plugin_active( 'custom-product-badge-for-woocommerce-pro/custom-product-badge-for-woocommerce-pro.php' ) ? true : false,
            'is_license_active' => Badge::is_license_active(),
		);
	}
}