<?php
/**
 * Ajax Class for Shop Explorer
 *
 * @package ShopExplorer\Ajax
 */

namespace SHOPEXPLORER\Inc\Ajax;

use ShopExplorer\Ajax\SHOPEX_AjaxHandler;

/**
 * Ajax Class
 */
class SHOPEX_Ajax {

	/**
	 * Ajax Handler instance
	 *
	 * @var SHOPEX_AjaxHandler
	 */
	private $ajax_handler;

	/**
	 * Initialize Ajax functionality
	 */
	public function __construct() {
		$this->init();
	}

	/**
	 * Initialize Ajax handlers
	 */
	private function init() {
		// Load the Ajax handler
		require_once SHOPEX_PATH . 'inc/Ajax/AjaxHandler.php';

		// Initialize the handler
		$this->ajax_handler = new SHOPEX_AjaxHandler();

		// Add nonce generation for frontend
		add_action( 'wp_enqueue_scripts', [ $this, 'localize_ajax_data' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'localize_ajax_data' ] );
	}

	/**
	 * Localize Ajax data for frontend use
	 */
	public function localize_ajax_data() {
		// Only localize if our scripts are enqueued
		if ( wp_script_is( 'shop-explorer-admin', 'enqueued' ) || wp_script_is( 'shop-explorer-admin', 'registered' ) ) {
			wp_localize_script( 'shop-explorer-admin', 'shopExplorerAjax', [
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonces' => [
					'upload_image' => wp_create_nonce( 'shopex_upload_image' ),
					'media_nonce' => wp_create_nonce( 'shopex_media_nonce' ),
					'create_category' => wp_create_nonce( 'shopex_create_category' ),
					'create_tag' => wp_create_nonce( 'shopex_create_tag' ),
					'create_brand' => wp_create_nonce( 'shopex_create_brand' ),
				],
			] );
		}
	}

	/**
	 * Get Ajax handler instance
	 *
	 * @return SHOPEX_AjaxHandler
	 */
	public function get_handler() {
		return $this->ajax_handler;
	}
}
