<?php

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

if (! defined('ICONVERT_SHOPLY_VERSION')) {
	define('ICONVERT_SHOPLY_VERSION', '1.0.36');
}

/**
 * 
 * Theme setup.
 */
add_action(
	'after_setup_theme',
	function () {
		add_theme_support( 'wp-block-styles' );
		add_theme_support( 'editor-styles' );
		add_theme_support( 'responsive-embeds' );
		add_theme_support( 'align-wide' );
		add_theme_support( 'post-thumbnails' );
		add_theme_support( 'title-tag' );
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'html5', array( 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script' ) );

		// WooCommerce hooks: this is a block theme, so most product templates are
		// served as block templates from `templates/`. Declaring support keeps the
		// "this theme does not declare WooCommerce support" admin notice quiet.
		// Catalog images: bump WC's thumbnail crop to 600px so product cards on
		// shop/home pages serve higher-res images (default 300x300 looks soft on
		// retina). Also set a wider single-product image for the gallery.
		add_theme_support(
			'woocommerce',
			array(
				'thumbnail_image_width' => 600,
				'single_image_width'    => 800,
				'gallery_thumbnail_image_width' => 150,
			)
		);
		add_theme_support( 'wc-product-gallery-zoom' );
		add_theme_support( 'wc-product-gallery-lightbox' );
		add_theme_support( 'wc-product-gallery-slider' );

	}
);

/**
 * Enqueue front-end styles.
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		wp_enqueue_style(
			'iconvert-shoply-style',
			get_stylesheet_uri(),
			array(),
			ICONVERT_SHOPLY_VERSION
		);
	}
);

/**
 * Editor styles so the block editor mirrors the front end.
 */
add_action(
	'after_setup_theme',
	function () {
		add_editor_style( array(
			'style.css',
		) );
	}
);

/**
 * Register the iConvert Shoply pattern category so theme patterns are grouped together
 * in the inserter.
 */
add_action(
	'init',
	function () {
		if ( function_exists( 'register_block_pattern_category' ) ) {
			register_block_pattern_category(
				'iconvert-shoply',
				array(
					'label'       => _x( 'iConvert Shoply', 'Block pattern category', 'iconvert-shoply' ),
					'description' => __( 'Patterns for the iConvert Shoply theme.', 'iconvert-shoply' ),
				)
			);
		}
	}
);

/**
 * Block style variations.
 */
add_action(
	'init',
	function () {
		if ( ! function_exists( 'register_block_style' ) ) {
			return;
		}
		register_block_style(
			'core/list',
			array(
				'name'  => 'plain',
				'label' => __( 'Plain', 'iconvert-shoply' ),
			)
		);
		register_block_style(
			'core/cover',
			array(
				'name'  => 'hero',
				'label' => __( 'Hero', 'iconvert-shoply' ),
			)
		);
	}
);

/**
 * Strip the "Archives:" / "Category:" / "Tag:" prefix from the wp:query-title
 * block so the page hero shows just the bare archive name ("Shop" instead of
 * "Archives: Shop", "Cleansers" instead of "Category: Cleansers").
 */
add_filter( 'get_the_archive_title_prefix', '__return_empty_string' );

/**
 * Default logo fallback.
 *
 * wp:site-logo renders empty when no logo is uploaded via Appearance → Site
 * Identity. This filter substitutes the bundled assets/img/logo.png so the
 * brand shows on a fresh install. Site Identity uploads still take over.
 */
function iconvert_shoply_default_logo_html() {
	return sprintf(
		'<a class="custom-logo-link" rel="home" href="%1$s"><img class="custom-logo" src="%2$s" alt="%3$s" width="140" height="36" /></a>',
		esc_url( home_url( '/' ) ),
		esc_url( get_template_directory_uri() . '/assets/img/logo.png' ),
		esc_attr( get_bloginfo( 'name', 'display' ) )
	);
}
add_filter(
	'render_block_core/site-logo',
	function ( $block_content ) {
		if ( '' !== trim( $block_content ) || get_theme_mod( 'custom_logo' ) ) {
			return $block_content;
		}
		return '<div class="wp-block-site-logo">' . iconvert_shoply_default_logo_html() . '</div>';
	}
);




/**
 * Homepage chip filter — pre_get_posts hook for ?iconvert_shoply_cat=<slug>.
 *
 * The homepage "Shop by category" pattern (patterns/category-tag-row.php)
 * renders a chip strip directly via PHP get_terms() instead of using WC's
 * product-filter-taxonomy block. Each chip links to `?iconvert_shoply_cat=<slug>`.
 *
 * Why a custom URL key: WC's filter blocks write `?categories=<slug>` and
 * `?tags=<slug>` URLs. Those keys are registered as WP public query vars
 * (via MainQueryController::add_query_vars), so when they appear on the
 * homepage URL, WP_Query::parse_query() line 2042 sees `! empty( $this->query )`
 * and skips the static-front-page substitution — the page renders as the
 * blog index instead of the static front page. Using a theme-namespaced key
 * (`iconvert_shoply_cat`) avoids the collision entirely.
 *
 * This hook reads `$_GET['iconvert_shoply_cat']` and injects a tax_query into any
 * product query running on the homepage. It only fires for product queries
 * (post_type=product) so blog queries and other non-product loops pass
 * through unchanged.
 */
add_action(
	'pre_get_posts',
	function ( $query ) {
		if ( is_admin() || ! is_front_page() ) {
			return;
		}
		if ( empty( $_GET['iconvert_shoply_cat'] ) ) {
			return;
		}
		$post_type = $query->get( 'post_type' );
		if ( 'product' !== $post_type && ( ! is_array( $post_type ) || ! in_array( 'product', $post_type, true ) ) ) {
			return;
		}
		$slug = sanitize_title( wp_unslash( $_GET['iconvert_shoply_cat'] ) );
		if ( '' === $slug ) {
			return;
		}
		$tax_query   = (array) $query->get( 'tax_query' );
		$tax_query[] = array(
			'taxonomy' => 'product_cat',
			'field'    => 'slug',
			'terms'    => array( $slug ),
			'operator' => 'IN',
		);
		$query->set( 'tax_query', $tax_query );
	}
);

/**
 * Inject aria-current="page" into the active chip's anchor at server-render
 * time.
 *
 * Why a render_block filter (and not a static attribute in the pattern's
 * source markup): wp:button's save() doesn't model aria-current as an
 * attribute, so adding `aria-current="page"` to the source markup creates a
 * byte-mismatch between the pattern PHP's output and what save() would
 * produce — and the editor would show "Attempt block recovery" on the
 * active chip.
 *
 * This filter runs AFTER block validation, on the rendered HTML string, so
 * the source-vs-save() byte-compare passes cleanly and the accessibility
 * affordance is preserved on the front end.
 */
add_filter(
	'render_block_core/button',
	function ( $block_content, $block ) {
		if ( empty( $block['attrs']['className'] ) ) {
			return $block_content;
		}
		// Only act on our chip buttons in the active state. The pattern adds
		// the "is-active" modifier class to exactly one chip per page render.
		if ( false === strpos( $block['attrs']['className'], 'iconvert-shoply-chip' ) ) {
			return $block_content;
		}
		if ( false === strpos( $block['attrs']['className'], 'is-active' ) ) {
			return $block_content;
		}
		// Inject aria-current onto the FIRST anchor in the rendered button.
		// Use a one-shot string replace (not preg) — the button block's
		// rendered HTML always contains exactly one <a class="wp-block-button__link
		// wp-element-button"... so this is safe and cheap.
		return preg_replace(
			'/(<a\s+class="wp-block-button__link wp-element-button"[^>]*)>/',
			'$1 aria-current="page">',
			$block_content,
			1
		);
	},
	10,
	2
);



/**
 * Suppress WooCommerce's hooked customer-account + mini-cart blocks INSIDE this
 * theme's header parts. We already inline both blocks intentionally in those
 * parts; without this filter WC's hooked-blocks feature would inject a second
 * pair after the closing </nav>, producing duplicate icons in the header.
 *
 * Implementation: scoped to ONLY this theme's specific template-part IDs via
 * the WP core `hooked_block_types` filter (WP 6.4+). Other themes, other parts,
 * and other plugins are not affected. wp.org-compliant — uses a documented
 * public filter, leaves no persistent state after theme deactivation.
 */
add_filter(
	'hooked_block_types',
	function ( $hooked_blocks, $relative_position, $anchor_block_type, $context ) {
		// Only suppress hooks anchored on core/navigation — that's where WC's
		// customer-account + mini-cart hooks target. Other hooks pass through.
		if ( 'core/navigation' !== $anchor_block_type ) {
			return $hooked_blocks;
		}
		// Detect whether the rendered context belongs to this theme.
		// $context can be one of:
		//   - WP_Block_Template (id like 'iconvert-shoply//header-home')
		//   - WP_Post (template-part stored as a post; active theme owns it)
		//   - array (pattern data; ['slug' => 'iconvert-shoply/main-nav', ...])
		$is_our_context = false;
		$theme          = get_stylesheet();
		if ( $context instanceof WP_Block_Template ) {
			$is_our_context = is_string( $context->id ) && 0 === strpos( $context->id, $theme . '//' );
		} elseif ( $context instanceof WP_Post ) {
			$is_our_context = true;
		} elseif ( is_array( $context ) && isset( $context['slug'] ) ) {
			$is_our_context = is_string( $context['slug'] ) && 0 === strpos( $context['slug'], $theme . '/' );
		}
		if ( ! $is_our_context ) {
			return $hooked_blocks;
		}
		return array_values( array_diff(
			$hooked_blocks,
			array( 'woocommerce/customer-account', 'woocommerce/mini-cart' )
		) );
	},
	10,
	4
);
function iconvert_shoply_is_woocommerce_activated() {
    return class_exists( 'WooCommerce' );
}
if( is_admin()) {
    require_once __DIR__ . '/inc/class-iconvert-shoply-plugin-install.php';
    require_once __DIR__ . '/inc/class-iconvert-shoply-admin.php';
}
