<?php
/**
 * Caching Admin Actions
 *
 * Handles admin-side cache actions including product purge/warmup buttons,
 * admin action handlers, and success/error notices.
 *
 * @package Mamba\Modules\Caching\Admin
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Admin;

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

use Mamba\Modules\Caching\Services\Invalidation;
use Mamba\Modules\Caching\Services\Preload\Preloader;

/**
 * Class Actions
 *
 * Registers admin action handlers for cache purging and warmup,
 * and displays admin notices for action results.
 *
 * @since 1.0.0
 */
final class Actions {
    public function register(): void {
        
        // Handlers and notices (kept for potential future use)
        add_action('admin_init', [$this, 'handleAdminActions']);
        add_action('admin_notices', [$this, 'maybeShowNotice']);
    }

    public function addProductButtons(): void {
        global $post;
        if (!$post || $post->post_type !== 'product') return;
        if (!current_user_can('manage_woocommerce') && !current_user_can('manage_options')) return;
        $purgeUrl = wp_nonce_url(add_query_arg([
            'mamba_admin_action' => 'purge_product',
            'post' => $post->ID,
        ]), 'mamba_admin_action');
        $warmUrl = wp_nonce_url(add_query_arg([
            'mamba_admin_action' => 'warmup_product',
            'post' => $post->ID,
        ]), 'mamba_admin_action');
        echo '<div class="misc-pub-section">'
           . '<span class="dashicons dashicons-performance" style="vertical-align:middle;"></span> '
           . esc_html( __('Mamba Cache', 'mamba-cache-for-woocommerce') ) . ' '
           . '<a href="' . esc_url($purgeUrl) . '" class="button button-small" style="margin-left:6px;">' . esc_html( __('Purge', 'mamba-cache-for-woocommerce') ) . '</a>'
           . '<a href="' . esc_url($warmUrl) . '" class="button button-small" style="margin-left:6px;">' . esc_html( __('Warmup', 'mamba-cache-for-woocommerce') ) . '</a>'
           . '</div>';
    }

    public function addTermButtons($term): void {
        if (!($term && isset($term->term_id))) return;
        if (!current_user_can('manage_woocommerce') && !current_user_can('manage_options')) return;
        $purgeUrl = wp_nonce_url(add_query_arg([
            'mamba_admin_action' => 'purge_term',
            'term_id' => (int)$term->term_id,
            'taxonomy' => sanitize_key($term->taxonomy),
        ]), 'mamba_admin_action');
        $warmUrl = wp_nonce_url(add_query_arg([
            'mamba_admin_action' => 'warmup_term',
            'term_id' => (int)$term->term_id,
            'taxonomy' => sanitize_key($term->taxonomy),
        ]), 'mamba_admin_action');
        echo '<tr class="form-field"><th scope="row">' . esc_html( __('Mamba Cache', 'mamba-cache-for-woocommerce') ) . '</th><td>'
           . '<a href="' . esc_url($purgeUrl) . '" class="button button-small">' . esc_html( __('Purge', 'mamba-cache-for-woocommerce') ) . '</a> '
           . '<a href="' . esc_url($warmUrl) . '" class="button button-small">' . esc_html( __('Warmup', 'mamba-cache-for-woocommerce') ) . '</a>'
           . '</td></tr>';
    }

    public function handleAdminActions(): void {
        if (empty($_GET['mamba_admin_action']) || empty($_GET['_wpnonce'])) return;
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'mamba_admin_action')) return;
        if (!current_user_can('manage_woocommerce') && !current_user_can('manage_options')) return;
        $action = sanitize_key(wp_unslash($_GET['mamba_admin_action']));
        if ($action === 'purge_product') {
            $postId = (int) wp_unslash($_GET['post'] ?? 0);
            if ($postId && get_post_type($postId)==='product') {
                Invalidation::clearRelatedProduct($postId);
                $this->redirectWithNotice('mamba_purged=product');
            }
        } elseif ($action === 'warmup_product') {
            $postId = (int) wp_unslash($_GET['post'] ?? 0);
            if ($postId && get_post_type($postId)==='product') {
                $link = get_permalink($postId);
                if ($link) Preloader::warmOne($link);
                $this->redirectWithNotice('mamba_warmup=product');
            }
        } elseif ($action === 'purge_term' || $action === 'warmup_term') {
            $termId = (int) wp_unslash($_GET['term_id'] ?? 0);
            $tax = sanitize_key(wp_unslash($_GET['taxonomy'] ?? ''));
            if ($termId && $tax && taxonomy_exists($tax)) {
                $link = get_term_link($termId, $tax);
                if (!is_wp_error($link)) {
                    if ($action === 'purge_term') Invalidation::clearUrl($link);
                    else Preloader::warmOne($link);
                    $this->redirectWithNotice($action==='purge_term' ? 'mamba_purged=term' : 'mamba_warmup=term');
                }
            }
        }
    }

    private function redirectWithNotice(string $param): void {
        $url = wp_get_referer();
        if (!$url) $url = admin_url();
        $url = add_query_arg($param, '1', remove_query_arg(['mamba_admin_action','post','term_id','taxonomy','_wpnonce'], $url));
        wp_safe_redirect($url);
        exit;
    }

    public function maybeShowNotice(): void {
        if (isset($_GET['mamba_purged'])) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( __('Mamba: Cache purged.', 'mamba-cache-for-woocommerce') ) . '</p></div>';
        }
        if (isset($_GET['mamba_warmup'])) {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( __('Mamba: Warmup scheduled.', 'mamba-cache-for-woocommerce') ) . '</p></div>';
        }
    }
}


