<?php
/**
 * Pawfect Theme functions and definitions
 *
 * @package Pawfect
 */



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



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

// -----------------------------------------------------------------------------
// 1. Define Constants
// -----------------------------------------------------------------------------
define( 'PAWFECT_THEME_DIR', get_template_directory() );
define( 'PAWFECT_THEME_URL', get_template_directory_uri() );

$pawfect_theme_info = wp_get_theme();
define( 'PAWFECT_THEME_VERSION', $pawfect_theme_info->get( 'Version' ) );
define( 'PAWFECT_THEME_NAME', $pawfect_theme_info->get( 'Name' ) );


// -----------------------------------------------------------------------------
// 2. Load the WPTT Webfont Loader (for GDPR-compliant local Google Fonts)
// -----------------------------------------------------------------------------
require_once PAWFECT_THEME_DIR . '/inc/wptt-webfont-loader.php';

// -----------------------------------------------------------------------------
// 3. Load the Main Theme Class
// -----------------------------------------------------------------------------
require_once PAWFECT_THEME_DIR . '/inc/class/class-pawfect-theme.php';
// Dynamic CSS and Webfonts are loaded by the main theme class


// -----------------------------------------------------------------------------
// 3. Initialize the Theme
// -----------------------------------------------------------------------------
if ( class_exists( 'Pawfect_Theme' ) ) {
    new Pawfect_Theme();
}

// Dynamic CSS is now handled by the main theme class (class-pawfect-theme.php)
// Removed duplicate instantiation to prevent conflicts



// Initialize Webfonts
if ( class_exists( 'Pawfect_Webfonts' ) ) {
    new Pawfect_Webfonts();
}

// Google Fonts are loaded via class-enqueue-assets.php to avoid duplicate enqueuing.
// Removed duplicate pawfect_enqueue_google_fonts() function.

// Typography now uses 'refresh' transport for proper CSS generation
// No need to override transport method

// Add version to force customizer reload
function pawfect_customizer_version() {
    return '1.0.1'; // Increment this to force reload
}

// Clear customizer cache on theme activation
function pawfect_clear_customizer_cache() {
    // Only delete theme-specific transients instead of flushing entire object cache
    delete_transient('pawfect_customizer_cache');
    wp_cache_delete('pawfect_dynamic_css', 'pawfect');
}
add_action('after_switch_theme', 'pawfect_clear_customizer_cache');

// Clean up customizer cache
function pawfect_clean_customizer_cache() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ( is_admin() && isset( $_GET['customize_theme'] ) && current_user_can( 'manage_options' ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $customize_theme = sanitize_text_field( wp_unslash( $_GET['customize_theme'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if ( ! empty( $customize_theme ) ) {
            wp_cache_delete( 'pawfect_theme_typography', 'theme_mod' );
            delete_transient( 'customize_changeset_data' );
        }
    }
}
add_action( 'admin_init', 'pawfect_clean_customizer_cache' );

// AJAX handler for customizer live preview font loading (GDPR-compliant).
// Returns a local WPTT-proxied URL instead of the Google Fonts CDN URL.
function pawfect_get_local_font_url() {
    if ( ! current_user_can( 'edit_theme_options' ) ) {
        wp_send_json_error( 'Unauthorized', 403 );
    }

    $font_family = isset( $_POST['font_family'] ) ? sanitize_text_field( wp_unslash( $_POST['font_family'] ) ) : '';

    if ( empty( $font_family ) ) {
        wp_send_json_error( 'No font family specified' );
    }

    $font_url = 'https://fonts.googleapis.com/css2?family=' . urlencode( $font_family ) . ':wght@300;400;500;600;700;800&display=swap';

    if ( function_exists( 'wptt_get_webfont_url' ) ) {
        $local_url = wptt_get_webfont_url( $font_url );
        wp_send_json_success( array( 'url' => $local_url ) );
    } else {
        wp_send_json_error( 'WPTT Webfont Loader not available' );
    }
}
add_action( 'wp_ajax_pawfect_get_local_font_url', 'pawfect_get_local_font_url' );

// Note: Database cleanup functions removed per WordPress.org theme review requirements.
// Raw $wpdb->query() calls without $wpdb->prepare() are security vulnerabilities.
// Automatic cleanup on every page load also impacts performance.
// -----------------------------------------------------------------------------
// Automatically update old PNG file references to WebP in theme mods (Backward Compatibility)
// -----------------------------------------------------------------------------
function pawfect_upgrade_png_to_webp_in_db() {
    // Only run this upgrade for version 1.0.4 or higher
    if ( version_compare( PAWFECT_THEME_VERSION, '1.0.4', '<' ) ) {
        return;
    }

    // Migration version: bump this when you need to re-run the migration.
    // v1.2.2: Re-run because previous migration missed some DB entries,
    // causing dozens of 404 errors for .png files that only exist as .webp.
    $migration_key = 'pawfect_webp_upgraded_1_2_2';
    if ( get_option( $migration_key ) ) {
        return;
    }
    
    $theme_mods = get_theme_mods();
    if ( ! empty( $theme_mods ) ) {
        $updated = false;
        foreach ( $theme_mods as $key => $value ) {
            if ( is_string( $value ) && preg_match( '/\.(png|jpg|jpeg)/i', $value ) ) {
                // Safely only replace theme default images, keeping actual user media uploads intact.
                // We check for both unescaped and JSON-escaped paths.
                if ( 
                    strpos( $value, '/assets/images/' ) !== false || 
                    strpos( $value, '/inc/pawfect/img/' ) !== false ||
                    strpos( $value, 'assets\/images' ) !== false ||
                    strpos( $value, 'inc\/pawfect\/img' ) !== false
                ) {
                    $theme_mods[$key] = preg_replace( '/\.(png|jpg|jpeg)/i', '.webp', $value );
                    $updated = true;
                }
            }
        }
        
        if ( $updated ) {
            update_option( 'theme_mods_' . get_stylesheet(), $theme_mods );
        }
    }
    
    update_option( $migration_key, true );
}
add_action( 'init', 'pawfect_upgrade_png_to_webp_in_db' );


// Include WooCommerce support
// Note: add_theme_support('woocommerce') is declared in class-theme-setup.php
if (class_exists('WooCommerce')) {
    require_once get_template_directory() . '/inc/woocommerce/cart-functions.php';
    require_once get_template_directory() . '/inc/woocommerce/shop-functions.php';
    require_once get_template_directory() . '/inc/woocommerce/wishlist-functions.php';
    require_once get_template_directory() . '/inc/woocommerce/quick-view-functions.php';
}

// Include blog helper functions
require_once get_template_directory() . '/inc/blog-helpers.php';

/**
 * Widgets
 */
require_once get_template_directory() . '/inc/widgets/sidebars.php';

/**
 * Refactored functionality files (Issue #12: Code Organization)
 */
require_once get_template_directory() . '/inc/emoji-disable.php';
require_once get_template_directory() . '/inc/body-classes.php';
require_once get_template_directory() . '/inc/social-icons.php';
require_once get_template_directory() . '/inc/class/class-preloader.php';
require_once get_template_directory() . '/inc/class/class-plugin-notify.php';

/**
 * Comment callback function matching HTML design
 */
if (!function_exists('pawfect_comment_callback')):
    function pawfect_comment_callback($comment, $args, $depth) {
        $GLOBALS['comment'] = $comment;
        $is_author = $comment->user_id && $comment->user_id == get_post()->post_author;
        $avatar_size = $depth > 0 ? 48 : 64;
        $comment_class = 'pawfect-flex pawfect-space-x-4';
        ?>
        <li <?php comment_class($comment_class); ?> id="comment-<?php comment_ID(); ?>">
            <img src="<?php echo esc_url( get_avatar_url($comment, $avatar_size) ); ?>" alt="<?php echo esc_attr(get_comment_author()); ?> Avatar" class="pawfect-w-12 pawfect-h-12 md:pawfect-w-16 md:pawfect-h-16 pawfect-rounded-full" />

            <div class="pawfect-flex-1">
                <div class="pawfect-flex pawfect-items-center pawfect-justify-between">
                    <div>
                        <h4 class="pawfect-font-bold pawfect-text-lg">
                            <?php echo esc_html( get_comment_author() ); ?>
                            <?php if ($is_author): ?>
                                <span class="pawfect-ml-2 pawfect-text-xs pawfect-font-sans pawfect-uppercase pawfect-bg-accent pawfect-text-white pawfect-px-2 pawfect-py-1 pawfect-rounded"><?php esc_html_e('Author', 'pawfect'); ?></span>
                            <?php endif; ?>
                        </h4>
                        <p class="pawfect-text-xs pawfect-text-text-light">
                            <?php
                            /* translators: 1: comment date, 2: comment time */
                            printf( esc_html__( '%1$s at %2$s', 'pawfect' ), esc_html( get_comment_date('F j, Y') ), esc_html( get_comment_time() ) );
                            ?>
                        </p>
                    </div>
                    <?php
                    comment_reply_link(array_merge($args, array(
                        'depth'     => $depth,
                        'max_depth' => $args['max_depth'],
                        'before'    => '<a href="#" class="pawfect-text-sm pawfect-font-bold pawfect-text-accent hover:pawfect-underline">',
                        'after'     => '</a>',
                    )));
                    ?>
                </div>

                <?php if ($comment->comment_approved == '0'): ?>
                    <p class="pawfect-text-sm pawfect-text-yellow-600 pawfect-italic pawfect-mt-2">
                        <?php esc_html_e('Your comment is awaiting moderation.', 'pawfect'); ?>
                    </p>
                <?php endif; ?>

                <div class="comment-content pawfect-mt-2 pawfect-text-text-light">
                    <?php comment_text(); ?>
                </div>
            </div>
        <?php
        // Note: </li> is automatically added by WordPress
    }
endif;




// -----------------------------------------------------------------------------
// WooCommerce Shop Page Customizer Settings
// -----------------------------------------------------------------------------
if (class_exists('WooCommerce')) {
    // Set products per page from customizer
    add_filter('loop_shop_per_page', function($products_per_page) {
        return get_theme_mod('pawfect_shop_products_per_page', 12);
    });

    // Set default sorting from customizer
    add_filter('woocommerce_default_catalog_orderby', function($orderby) {
        return get_theme_mod('pawfect_shop_default_sorting', 'menu_order');
    });

    // Set shop columns from customizer
    add_filter('loop_shop_columns', function($columns) {
        return get_theme_mod('pawfect_shop_columns', 3);
    });

    // Remove WooCommerce default result count and sorting if disabled in customizer
    add_action('init', function() {
        if (!get_theme_mod('pawfect_shop_show_result_count', true)) {
            remove_action('woocommerce_before_shop_loop', 'woocommerce_result_count', 20);
        }

        if (!get_theme_mod('pawfect_shop_show_sorting', true)) {
            remove_action('woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30);
        }
    });

    // Add body classes for shop page layout
    add_filter('body_class', function($classes) {
        // Only run if WooCommerce is active and functions exist
        if (class_exists('WooCommerce') && function_exists('is_shop') && function_exists('is_product_category') && function_exists('is_product_tag')) {
            if (is_shop() || is_product_category() || is_product_tag()) {
                $shop_layout = get_theme_mod('pawfect_shop_layout', 'sidebar-left');
                $card_style = get_theme_mod('pawfect_shop_card_style', 'modern');

                $classes[] = 'pawfect-shop-' . $shop_layout;
                $classes[] = 'pawfect-shop-card-' . $card_style;
            }
        }
        return $classes;
    });
}

// -----------------------------------------------------------------------------
// 5. Animation Helper Functions
// -----------------------------------------------------------------------------

/**
 * Check if site animations are enabled
 *
 * @return bool True if animations are enabled, false otherwise
 */
function pawfect_animations_enabled() {
    // The setting is 'pawfect_animation_disabled' with default true (enabled)
    // When toggle is ON (true), animations are enabled
    // When toggle is OFF (false), animations are disabled
    return get_theme_mod('pawfect_animation_disabled', true);
}

/**
 * Get AOS animation attributes if animations are enabled
 *
 * @param string $animation Animation type (fade-up, fade-left, etc.)
 * @param int $duration Animation duration in milliseconds
 * @param int $delay Animation delay in milliseconds
 * @return string Animation attributes or empty string
 */
function pawfect_get_aos_attrs($animation = 'fade-up', $duration = 600, $delay = 0) {
    if (!pawfect_animations_enabled()) {
        return '';
    }

    $attrs = 'data-aos="' . esc_attr($animation) . '"';
    $attrs .= ' data-aos-duration="' . esc_attr($duration) . '"';

    if ($delay > 0) {
        $attrs .= ' data-aos-delay="' . esc_attr($delay) . '"';
    }

    return $attrs;
}

// Body class functions moved to inc/body-classes.php

/**
 * Add smooth scroll implementation if enabled
 */
function pawfect_smooth_scroll_implementation() {
    $smooth_scroll_enabled = get_theme_mod('pawfect_smooth_scroll_enabled', true);

    if ($smooth_scroll_enabled) {
        // Add smooth scroll JS via wp_add_inline_script
        $smooth_scroll_js = '
        document.addEventListener("DOMContentLoaded", function() {
            document.querySelectorAll("a[href^=\\"#\\"]").forEach(function(anchor) {
                anchor.addEventListener("click", function (e) {
                    var href = this.getAttribute("href");
                    if (href === "#" || href === "#top") return;
                    var target = document.querySelector(href);
                    if (target) {
                        e.preventDefault();
                        target.scrollIntoView({ behavior: "smooth", block: "start" });
                    }
                });
            });
            var scrollToTopLinks = document.querySelectorAll("a[href=\\"#\\"], a[href=\\"#top\\"]");
            scrollToTopLinks.forEach(function(link) {
                link.addEventListener("click", function(e) {
                    e.preventDefault();
                    window.scrollTo({ top: 0, behavior: "smooth" });
                });
            });
        });
        ';
        wp_add_inline_script('pawfect-main', $smooth_scroll_js);

        // Add smooth scroll CSS via wp_add_inline_style
        $smooth_scroll_css = '
            html { scroll-behavior: smooth; }
            @media (prefers-reduced-motion: reduce) {
                html { scroll-behavior: auto; }
            }
            /* Fallback Menu Styling */
            .pawfect-page-menu-fallback ul { display: flex; align-items: center; justify-content: center; gap: 1.5rem; list-style: none; margin: 0; padding: 0; }
            .pawfect-page-menu-fallback ul li { display: inline-block; position: relative; }
            .pawfect-page-menu-fallback ul li a { text-transform: uppercase; font-size: 17px; font-weight: 500; color: inherit; text-decoration: none; }
            .pawfect-mobile-menu-fallback ul { display: flex; flex-direction: column; gap: 0.75rem; list-style: none; padding-left: 0; margin: 0; }
            .pawfect-mobile-menu-fallback ul li a { color: #ffffff; text-decoration: none; font-size: 16px; font-weight: 500; }
        ';
        wp_add_inline_style('pawfect-style', $smooth_scroll_css);
    }
}
add_action('wp_enqueue_scripts', 'pawfect_smooth_scroll_implementation', 30);

// Preloader functions moved to inc/class/class-preloader.php

// Plugin Recommendation System moved to inc/class/class-plugin-notify.php

// Note: WebP upgrade migration already handled by pawfect_upgrade_png_to_webp_in_db() above.
// Duplicate pawfect_free_upgrade_png_to_webp_in_db() removed for performance.

// -----------------------------------------------------------------------------
// Template Helper: Animated Arrow Button Icon (SVG)
// -----------------------------------------------------------------------------
/**
 * Returns the SVG markup for the Pawfect animated arrow-in-circle button icon.
 *
 * Use this function instead of hardcoding the SVG block in templates.
 * Accepts optional CSS classes to control sizing and spacing.
 *
 * Usage: <?php echo pawfect_get_button_icon(); ?>
 * Usage: <?php echo pawfect_get_button_icon( 'pawfect-w-4 pawfect-h-4 pawfect-ml-2' ); ?>
 *
 * @since 1.0.5
 * @param string $classes Optional. Space-separated CSS classes for the SVG element.
 *                        Default: 'pawfect-w-5 pawfect-h-5 pawfect-ml-2'
 * @return string The escaped SVG HTML string.
 */
function pawfect_get_button_icon( $classes = 'pawfect-w-5 pawfect-h-5 pawfect-ml-2' ) {
    $classes = esc_attr( $classes );
    return '<svg class="' . $classes . '" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><mask id="pawfect-arrow-mask"><rect width="24" height="24" fill="white" /><path class="pawfect-animated-arrow" d="M14.79 12.53L11.26 16.06C11.11 16.21 10.92 16.28 10.73 16.28C10.54 16.28 10.35 16.21 10.2 16.06C9.91 15.77 9.91 15.29 10.2 15L13.2 12L10.2 9C9.91 8.71 9.91 8.23 10.2 7.94C10.49 7.65 10.97 7.65 11.26 7.94L14.79 11.47C15.09 11.76 15.09 12.24 14.79 12.53Z" fill="black" /></mask></defs><path d="M12 2C6.49 2 2 6.49 2 12C2 17.51 6.49 22 12 22C17.51 22 22 17.51 22 12C22 6.49 17.51 2 12 2Z" fill="currentColor" mask="url(#pawfect-arrow-mask)"></path></svg>';
}