<?php

/**
 * Term meta coordinator.
 *
 * @package B3WVS\VariationSwatches\Admin
 */
namespace B3WVS\VariationSwatches\Admin;

use B3WVS\VariationSwatches\Admin\TermMeta\Registry;
use B3WVS\VariationSwatches\Admin\TermMeta\Form;
use B3WVS\VariationSwatches\Admin\TermMeta\Sanitizer;
use B3WVS\VariationSwatches\Assets;
defined( 'ABSPATH' ) || exit;
/**
 * TermMeta Class - Main coordinator for term meta functionality
 */
class TermMeta {
    /**
     * Instance of this class.
     *
     * @var TermMeta
     */
    private static $instance = null;

    /**
     * Get instance of this class.
     *
     * @return TermMeta
     */
    public static function get_instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     */
    private function __construct() {
        add_action( 'init', array(Registry::class, 'register') );
        add_action( 'admin_init', array(Registry::class, 'register_form_hooks') );
        add_action(
            'delete_term',
            array($this, 'maybe_flush_usage_stats_cache'),
            10,
            4
        );
        add_action( 'admin_enqueue_scripts', array($this, 'enqueue_admin_scripts') );
    }

    /**
     * Clear usage stats cache when a product-attribute term is deleted.
     *
     * @param int    $term       Term ID.
     * @param int    $tt_id      Term taxonomy ID.
     * @param string $taxonomy   Taxonomy slug.
     * @param mixed  $deleted    Deleted term payload.
     * @return void
     */
    public function maybe_flush_usage_stats_cache(
        $term,
        $tt_id,
        $taxonomy,
        $deleted
    ) {
        unset($term, $tt_id, $deleted);
        if ( !is_string( $taxonomy ) || 0 !== strpos( $taxonomy, 'pa_' ) ) {
            return;
        }
        \b3wvs_flush_usage_stats_cache();
    }

    /**
     * Enqueue admin scripts.
     *
     * @param string $hook Current admin hook.
     */
    public function enqueue_admin_scripts( $hook ) {
        if ( 'term.php' !== $hook && 'edit-tags.php' !== $hook ) {
            return;
        }
        wp_enqueue_style( 'wp-color-picker' );
        wp_enqueue_media();
        Assets::get_instance()->get_enqueuer()->enqueue_asset( 'admin-term-meta', 'src/legacy/admin-term-meta.js', array('jquery', 'wp-color-picker') );
    }

}
