<?php

namespace Divi_Essential\Includes;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Main Divi Cache Clearer Class
 */
class DnxteCache_Clearer {

	/**
	 * Constructor
	 */
	public function __construct() {
		// Add admin bar menu
		add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_button' ), 100 );

		// Handle AJAX request
		add_action( 'wp_ajax_clear_divi_css_cache', array( $this, 'ajax_clear_divi_css_cache' ) );

		// Add admin notices
		add_action( 'admin_notices', array( $this, 'display_admin_notices' ) );

		// Add required scripts
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
	}

	/**
	 * Add button to admin bar
	 *
	 * @param WP_Admin_Bar $admin_bar WordPress Admin Bar object.
	 */
	public function add_admin_bar_button( $admin_bar ) {
		// Only show to users who can manage options
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Add the parent item
		$admin_bar->add_node(
			array(
				'id'    => 'divi-cache-clearer',
				'title' => '<span class="ab-icon dashicons dashicons-update"></span>' . esc_html__( 'Clear Divi Cache', 'divi-cache-clearer' ),
				'href'  => '#',
				'meta'  => array(
					'title'   => esc_attr__( 'Clear Divi CSS Cache', 'divi-cache-clearer' ),
					'class'   => 'divi-cache-clear-button',
					'onclick' => 'return false;',
				),
			)
		);
	}

	/**
	 * Enqueue admin scripts
	 */
	public function enqueue_admin_scripts() {
		// Only for users who can manage options
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Register and enqueue our script
		wp_register_script(
			'divi-cache-clearer',
			plugin_dir_url( __FILE__ ) . 'js/divi-cache-clearer.js',
			array( 'jquery' ),
			'1.0.0',
			true
		);

		// Localize the script with new data
		$localize_data = array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'clear_divi_css_cache_nonce' ),
		);
		wp_localize_script( 'divi-cache-clearer', 'DiviCacheClearer', $localize_data );

		// Enqueue the script
		wp_enqueue_script( 'divi-cache-clearer' );

		// Add custom styles for the admin bar button
		wp_add_inline_style(
			'admin-bar',
			'
            #wp-admin-bar-divi-cache-clearer .ab-icon {
                top: 2px;
            }
            #wp-admin-bar-divi-cache-clearer:hover .ab-icon {
                transform: rotate(180deg);
                transition: transform 0.5s ease;
            }
            #wp-admin-bar-divi-cache-clearer.clearing .ab-icon {
                animation: divi-cache-spin 1s infinite linear;
            }
            @keyframes divi-cache-spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        '
		);

		// Create the JS file directory if it doesn't exist
		if ( ! file_exists( plugin_dir_path( __FILE__ ) . 'js' ) ) {
			mkdir( plugin_dir_path( __FILE__ ) . 'js', 0755 );
		}
	}

	/**
	 * AJAX handler for clearing Divi CSS cache
	 */
	public function ajax_clear_divi_css_cache() {
		// Check nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'clear_divi_css_cache_nonce' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'Security check failed.', 'divi-cache-clearer' ) ) );
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => esc_html__( 'You do not have permission to perform this action.', 'divi-cache-clearer' ) ) );
		}

		// Clear Divi CSS cache using Divi's native functions
		$this->clear_divi_css_cache();

		// Send success response
		wp_send_json_success( array( 'message' => esc_html__( 'Divi CSS cache cleared successfully!', 'divi-cache-clearer' ) ) );
	}

	/**
	 * Clear Divi CSS cache using Divi's native functions
	 */
	private function clear_divi_css_cache() {
		// Method 1: Use Divi's ET_Core_PageResource class if available
		if ( class_exists( 'ET_Core_PageResource' ) && method_exists( 'ET_Core_PageResource', 'remove_static_resources' ) ) {
			\ET_Core_PageResource::remove_static_resources( 'all', 'all' );
		}

		// Method 2: Use Divi's AJAX action directly
		if ( function_exists( 'et_core_page_resource_clear' ) ) {
			$_POST['et_owner']                   = 'all';
			$_POST['et_post_id']                 = 'all';
			$_POST['clear_page_resources_nonce'] = wp_create_nonce( 'clear_page_resources' );

			et_core_page_resource_clear();
		}

		// Set transient for admin notice (for non-AJAX requests)
		set_transient( 'divi_cache_cleared', true, 60 );
	}

	/**
	 * Display admin notices
	 */
	public function display_admin_notices() {
		// Check if our transient is set (for non-AJAX requests)
		if ( get_transient( 'divi_cache_cleared' ) ) {
			?>
			<div class="notice notice-success is-dismissible">
				<p><strong><?php esc_html_e( 'Divi CSS cache cleared successfully!', 'divi-cache-clearer' ); ?></strong></p>
			</div>
			<?php

			// Delete the transient
			delete_transient( 'divi_cache_cleared' );
		}
	}
}

// Initialize the class
new DnxteCache_Clearer();
