<?php
namespace CWPM\Compat;

defined( 'ABSPATH' ) || exit;

class WooCommerce {

	/**
	 * Check if WooCommerce is active.
	 *
	 * @return bool
	 */
	public static function is_active() {
		return class_exists( 'WooCommerce' );
	}

	/**
	 * Get all attachment IDs referenced by WooCommerce.
	 *
	 * @return int[] Array of attachment IDs.
	 */
	public static function get_used_attachment_ids() {
		if ( ! self::is_active() ) {
			return array();
		}

		$ids = array();

		foreach ( self::get_category_thumbnail_usage() as $entry ) {
			$ids[] = $entry['attach_id'];
		}

		$placeholder = self::get_placeholder_id();
		if ( $placeholder ) {
			$ids[] = $placeholder;
		}

		return array_unique( array_filter( $ids ) );
	}

	/**
	 * Get structured usage data for WooCommerce category thumbnails.
	 *
	 * Each entry contains the attachment ID plus the term context needed to
	 * build a proper usage link (term ID, category name, edit URL).
	 *
	 * @return array[] List of [ attach_id, term_id, title, edit_url, context, type ].
	 */
	public static function get_category_thumbnail_usage() {
		if ( ! self::is_active() ) {
			return array();
		}

		global $wpdb;

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery -- bulk scan of Woo product-cat thumbnail termmeta; readonly analytics.
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT tm.meta_value AS attach_id, t.term_id, t.name
                 FROM {$wpdb->termmeta} tm
                 INNER JOIN {$wpdb->terms} t ON t.term_id = tm.term_id
                 WHERE tm.meta_key = %s
                 AND tm.meta_value > 0",
				'thumbnail_id'
			)
		);

		$usage = array();
		foreach ( $rows as $row ) {
			$term_id = (int) $row->term_id;
			$usage[] = array(
				'attach_id' => absint( $row->attach_id ),
				'term_id'   => $term_id,
				'title'     => $row->name ?: __( '(no title)', 'coffeewp-media-cleanup' ),
				'edit_url'  => admin_url( 'term.php?taxonomy=product_cat&tag_ID=' . $term_id ),
				'context'   => 'category-thumbnail',
				'type'      => 'product_cat',
			);
		}

		return $usage;
	}

	/**
	 * Get the WooCommerce placeholder image attachment ID (0 if unset).
	 *
	 * @return int
	 */
	public static function get_placeholder_id() {
		$val = get_option( 'woocommerce_placeholder_image', 0 );
		return $val ? absint( $val ) : 0;
	}

	/**
	 * Is WooCommerce deep scan currently enabled?
	 *
	 * Returns false by default and the live state if an extension hooks the
	 * `cwpm/woocommerce_deep_enabled` filter. Kept callable so templates can
	 * ask without needing to know whether any extension is loaded.
	 *
	 * @return bool
	 */
	public static function is_deep_enabled() {
		return (bool) apply_filters( 'cwpm_woocommerce_deep_enabled', false );
	}
}
