<?php

/**
 * Blynex Theme Functions
 *
 * This file contains the core functionality of the Blynex theme.
 * It initializes the theme, loads required files, and sets up basic configurations.
 * The functions.php file serves as the entry point for the theme's PHP functionality.
 *
 * @package WordPress
 * @subpackage Blynex
 * @since 1.0.0
 */

/**
 * Ensure WooCommerce block attributes are properly formatted
 * Fixes the 'foreach() argument must be of type array|object, string given' warning
 */
add_filter('render_block_data', function ($parsed_block) {
    // Check if this is a WooCommerce block
    if (strpos($parsed_block['blockName'] ?? '', 'woocommerce/') === 0) {
        // Ensure spacing.padding is an array
        if (
            isset($parsed_block['attrs']['style']['spacing']['padding']) &&
            !is_array($parsed_block['attrs']['style']['spacing']['padding'])
        ) {
            $padding_value = $parsed_block['attrs']['style']['spacing']['padding'];
            $parsed_block['attrs']['style']['spacing']['padding'] = [
                'top' => $padding_value,
                'right' => $padding_value,
                'bottom' => $padding_value,
                'left' => $padding_value
            ];
        }
    }
    return $parsed_block;
}, 10, 1);

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

/**
 * Display the review count with proper formatting
 */
function blynex_product_review_count()
{
    if (!post_type_supports('product', 'comments')) {
        return;
    }

    $count = (int) get_comments_number();
    $text = sprintf(
        _n('%d customer review', '%d customer reviews', $count, 'blynex'),
        $count
    );

    $review_link = get_permalink() . '#reviews';

    return '<a href="' . esc_url($review_link) . '" class="review-count-link">' . esc_html($text) . '</a>';
}
/**
 * Suppress multiple text domains warning for theme check
 * 
 * This is needed because WooCommerce uses its own text domain
 * and theme check flags this as a warning.
 */
function blynex_suppress_text_domain_warnings()
{
    add_filter('override_load_textdomain', function ($retval, $domain) {
        if ('woocommerce' === $domain) {
            return true; // Skip loading WooCommerce text domain
        }
        return $retval;
    }, 10, 2);

    // Also add filter for theme check plugin
    add_filter('theme_check_locale_code_skip_text_domains', function ($domains) {
        $domains[] = 'woocommerce';
        return $domains;
    });
}
add_action('after_setup_theme', 'blynex_suppress_text_domain_warnings', 1);

/**
 * Load theme core functionality
 *
 * The class-loader.php file contains the main theme class and autoloader.
 * This file initializes the theme's core functionality and sets up hooks.
 */
require_once get_template_directory() . '/includes/class-loader.php';


/**
 * Initialize the theme
 *
 * Creates a singleton instance of the main theme class.
 * This ensures the theme is properly initialized with all required functionality.
 */
if (class_exists('Blynex_Theme')) {
    Blynex_Theme::get_instance();
}

/**
 * Enable custom styling options for image blocks
 *
 * This function adds theme support for spacing, colors and enables
 * padding, background color, and text color controls for image blocks.
 */
function blynex_enable_image_block_supports()
{
    // Enable image block supports using the register_block_type_args filter
    add_filter('register_block_type_args', function ($args, $name) {
        if ($name === 'core/image' || $name === 'core/cover') {
            // Ensure supports array exists
            if (!isset($args['supports'])) {
                $args['supports'] = array();
            }
            // Add spacing support
            $args['supports']['spacing'] = array(
                'padding' => true,
                'margin' => true,
                '__experimentalDefaultControls' => array(
                    'padding' => true,
                    'margin' => true
                )
            );
            // Add color support
            $args['supports']['color'] = array(
                'text' => true,
                'background' => true,
                '__experimentalDefaultControls' => array(
                    'text' => true,
                    'background' => true
                )
            );
            // Add border support
            $args['supports']['border'] = array(
                'radius' => true,
                '__experimentalDefaultControls' => array(
                    'radius' => true
                )
            );
        }
        return $args;
    }, 10, 2);
}
add_action('init', 'blynex_enable_image_block_supports', 5);

function blynex_enqueue_theme_scripts()
{
    // Enqueue theme styles
    wp_enqueue_style('blynex-style-index', get_theme_file_uri('build/style-index.css'), array());

    // Add inline CSS for skip link as backup
    $skip_link_css = "
    .skip-link {
        position: absolute !important;
        top: -40px !important;
        left: 6px !important;
        background: #000 !important;
        color: #fff !important;
        padding: 8px 16px !important;
        text-decoration: none !important;
        border-radius: 4px !important;
        z-index: 10000 !important;
        transition: top 0.3s ease !important;
        font-weight: bold !important;
        display: block !important;
        width: auto !important;
        height: auto !important;
        overflow: visible !important;
    }
    .skip-link:focus {
        top: 42px !important;
        outline: 2px solid #fff !important;
        outline-offset: 2px !important;
    }
    ";
    wp_add_inline_style('blynex-style-index', $skip_link_css);
}
add_action('wp_enqueue_scripts', 'blynex_enqueue_theme_scripts');

// Add skip link for accessibility at the very top of the body
add_action('wp_body_open', function () {
    echo '<a href="#main-content" class="skip-link screen-reader-text" id="skip-link">' . esc_html__('Skip to content', 'blynex') . '</a>';
});


/**
 * Debug function to verify block supports are enabled
 * Add ?debug_blocks=1 to any admin URL to see block configurations
 */
function blynex_debug_block_supports()
{
    if (isset($_GET['debug_blocks']) && $_GET['debug_blocks'] == '1' && current_user_can('manage_options')) {
        echo '<div style="background: #fff; padding: 20px; margin: 20px; border: 1px solid #ccc;">';
        echo '<h3>Image Block Registration Debug</h3>';
        $registry = WP_Block_Type_Registry::get_instance();
        $image_block = $registry->get_registered('core/image');
        $cover_block = $registry->get_registered('core/cover');
        echo '<h4>Core/Image Block Supports:</h4>';
        echo '<pre>' . print_r($image_block->supports ?? 'No supports found', true) . '</pre>';
        echo '<h4>Core/Cover Block Supports:</h4>';
        echo '<pre>' . print_r($cover_block->supports ?? 'No supports found', true) . '</pre>';
        echo '<h4>Current Theme JSON Settings:</h4>';
        $theme_json = WP_Theme_JSON_Resolver::get_merged_data();
        $settings = $theme_json->get_settings();
        echo '<h5>Global Color Settings:</h5>';
        echo '<pre>' . print_r($settings['color'] ?? 'No color settings', true) . '</pre>';
        echo '<h5>Global Spacing Settings:</h5>';
        echo '<pre>' . print_r($settings['spacing'] ?? 'No spacing settings', true) . '</pre>';
        echo '</div>';
    }
}
add_action('admin_notices', 'blynex_debug_block_supports');

//add body class for zolo blocks
function zoloblocks_editor_body_class($classes)
{
    if (is_admin() && isset($_GET['action']) && $_GET['action'] === 'edit') { // phpcs:ignore
        $classes .= ' zolo-editor';
    }
    return $classes;
}
add_filter('admin_body_class', 'zoloblocks_editor_body_class');

// Check if WooCommerce is active and load WooCommerce integration
if (class_exists('WooCommerce')) {
    require_once get_template_directory() . '/includes/class-woocommerce.php';
    if (class_exists('Blynex_WooCommerce')) {
        new Blynex_WooCommerce();
    }
    add_action('woocommerce_after_shop_loop_item_title', 'blynex_display_review_count', 5);
    function blynex_display_review_count()
    {
        global $product;
        $review_count = $product->get_review_count();
        $rating = $product->get_average_rating();
        if ($review_count > 0) {
            $review_link = get_permalink() . '#reviews';
            $rating_html = wc_get_rating_html($rating, $review_count);
            echo '<div class="review-count-wrapper" style="margin: 5px 0; font-size: 0.9em; display: flex; justify-content: center; align-items: center; gap: 4px;">';
            echo '<a href="' . esc_url($review_link) . '" class="woocommerce-review-link" style="color: #666; text-decoration: none; display: inline-flex; align-items: center;">';
            echo '<span style="display: inline-block; margin-right: 4px;">' . $rating_html . '</span>';
            echo '<span>(' . esc_html($review_count) . ' ' . _n('review', 'reviews', $review_count, 'blynex') . ')</span>';
            echo '</a>';
            echo '</div>';
        }
    }
}
