<?php
/**
 * Standard Blog functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package Standard Blog
 */
if ( ! defined( 'STANDARD_BLOG_VERSION' ) ) {
	// Replace the version number of the theme on each release.
	define( 'STANDARD_BLOG_VERSION', '1.0.0' );
}
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
function standard_blog_setup() {
	/*
		* Make theme available for translation.
		* Translations can be filed in the /languages/ directory.
		* If you're building a theme based on Standard Blog, use a find and replace
		* to change 'standard-blog' to the name of your theme in all the template files.
		*/
	load_theme_textdomain( 'standard-blog', get_template_directory() . '/languages' );
	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'register_block_style' );
	add_theme_support( 'register_block_pattern' );
	add_theme_support( 'responsive-embeds' );
	add_theme_support( 'align-wide' );
	add_theme_support( 'editor-styles' );
	add_theme_support( 'wp-block-styles' );
	/*
		* Let WordPress manage the document title.
		* By adding theme support, we declare that this theme does not use a
		* hard-coded <title> tag in the document head, and expect WordPress to
		* provide it for us.
		*/
	add_theme_support( 'title-tag' );
	/*
		* Enable support for Post Thumbnails on posts and pages.
		*
		* @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		*/
	add_theme_support( 'post-thumbnails' );
	// This theme uses wp_nav_menu() in one location.
	register_nav_menus(
		array(
			'primary' => esc_html__( 'Primary Menu', 'standard-blog' ),
		)
	);
	/*
		* Switch default core markup for search form, comment form, and comments
		* to output valid HTML5.
		*/
	add_theme_support(
		'html5',
		array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
			'style',
			'script',
		)
	);
	// Set up the WordPress core custom background feature.
	add_theme_support(
		'custom-background',
		apply_filters(
			'standard_blog_custom_background_args',
			array(
				'default-color' => 'f7f7ff',
				'default-image' => '',
			)
		)
	);
	// Add theme support for selective refresh for widgets.
	add_theme_support( 'customize-selective-refresh-widgets' );
	add_theme_support( 'woocommerce' );
	if ( class_exists( 'WooCommerce' ) ) {
		global $woocommerce;
		if ( version_compare( $woocommerce->version, '3.0.0', '>=' ) ) {
			add_theme_support( 'wc-product-gallery-zoom' );
			add_theme_support( 'wc-product-gallery-lightbox' );
			add_theme_support( 'wc-product-gallery-slider' );
		}
	}
	/**
	 * Add support for core custom logo.
	 *
	 * @link https://codex.wordpress.org/Theme_Logo
	 */
	add_theme_support(
		'custom-logo',
		array(
			'height'      => 250,
			'width'       => 250,
			'flex-width'  => true,
			'flex-height' => true,
		)
	);
	add_theme_support(
		'editor-font-sizes',
		array(
			array(
				'name'      => esc_html__( 'small', 'standard-blog' ),
				'shortName' => esc_html__( 'S', 'standard-blog' ),
				'size'      => 12,
				'slug'      => 'small',
			),
			array(
				'name'      => esc_html__( 'regular', 'standard-blog' ),
				'shortName' => esc_html__( 'M', 'standard-blog' ),
				'size'      => 16,
				'slug'      => 'regular',
			),
			array(
				'name'      => esc_html__( 'larger', 'standard-blog' ),
				'shortName' => esc_html__( 'L', 'standard-blog' ),
				'size'      => 36,
				'slug'      => 'larger',
			),
			array(
				'name'      => esc_html__( 'huge', 'standard-blog' ),
				'shortName' => esc_html__( 'XL', 'standard-blog' ),
				'size'      => 48,
				'slug'      => 'huge',
			),
		)
	);
}
add_action( 'after_setup_theme', 'standard_blog_setup' );
/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function standard_blog_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'standard_blog_content_width', 640 );
}
add_action( 'after_setup_theme', 'standard_blog_content_width', 0 );
/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function standard_blog_widgets_init() {
	register_sidebar(
		array(
			'name'          => esc_html__( 'Sidebar', 'standard-blog' ),
			'id'            => 'sidebar-1',
			'description'   => esc_html__( 'Add widgets here.', 'standard-blog' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);
	for ( $i = 1; $i <= 3; $i++ ) {
		register_sidebar(
			array(
				'name'          => esc_html__( 'Footer Widget Area ', 'standard-blog' ) . $i,
				'id'            => 'footer-' . $i,
				'description'   => esc_html__( 'Add widgets here.', 'standard-blog' ),
				'before_widget' => '<section id="%1$s" class="widget %2$s">',
				'after_widget'  => '</section>',
				'before_title'  => '<h2 class="widget-title">',
				'after_title'   => '</h2>',
			)
		);
	}
}
add_action( 'widgets_init', 'standard_blog_widgets_init' );
/**
 * Register custom fonts.
 */
function standard_blog_fonts_url() {
	$fonts_url     = '';
	$font_families = array();
	$subsets       = 'latin,latin-ext';
	if ( 'off' !== _x( 'on', 'Poppins font: on or off', 'standard-blog' ) ) {
		$font_families[] = 'Poppins:400,600,700';
	}
	if ( 'off' !== _x( 'on', 'Lato font: on or off', 'standard-blog' ) ) {
		$font_families[] = 'Lato:400,600,700';
	}
	if ( ! empty( get_theme_mod( 'standard_blog_site_title_font' ) ) ) {
		$font_families[] = str_replace( '+', ' ', get_theme_mod( 'standard_blog_site_title_font' ) );
	}
	if ( ! empty( get_theme_mod( 'standard_blog_site_description_font' ) ) ) {
		$font_families[] = str_replace( '+', ' ', get_theme_mod( 'standard_blog_site_description_font' ) );
	}
	if ( ! empty( get_theme_mod( 'standard_blog_header_font' ) ) ) {
		$font_families[] = str_replace( '+', ' ', get_theme_mod( 'standard_blog_header_font' ) );
	}
	if ( ! empty( get_theme_mod( 'standard_blog_body_font' ) ) ) {
		$font_families[] = str_replace( '+', ' ', get_theme_mod( 'standard_blog_body_font' ) );
	}
	$query_args = array(
		'family' => urlencode( implode( '|', $font_families ) ),
		'subset' => urlencode( $subsets ),
	);
	if ( $font_families ) {
		$fonts_url = add_query_arg( $query_args, 'https://fonts.googleapis.com/css' );
	}
	return esc_url_raw( $fonts_url );
}
/**
 * Enqueue scripts and styles.
 */
function standard_blog_scripts() {
	// Add custom fonts, used in the main stylesheet.
	wp_enqueue_style( 'standard-blog-fonts', wptt_get_webfont_url( standard_blog_fonts_url() ), array(), null );
	// Slick style.
	wp_enqueue_style( 'standard-blog-slick-style', get_template_directory_uri() . '/assets/css/slick.min.css', array(), '1.8.0' );
	// Fontawesome style.
	wp_enqueue_style( 'standard-blog-fontawesome-style', get_template_directory_uri() . '/assets/css/fontawesome.min.css', array(), '1.8.0' );
	// blocks.
	wp_enqueue_style( 'standard-blog-blocks-style', get_template_directory_uri() . '/assets/css/blocks.min.css' );
	// style.
	wp_enqueue_style( 'standard-blog-style', get_template_directory_uri() . '/style.css', array(), STANDARD_BLOG_VERSION );
	// navigation.
	wp_enqueue_script( 'standard-blog-navigation', get_template_directory_uri() . '/assets/js/navigation.min.js', array(), STANDARD_BLOG_VERSION, true );
	// Slick script.
	wp_enqueue_script( 'standard-blog-slick-script', get_template_directory_uri() . '/assets/js/slick.min.js', array( 'jquery' ), '1.8.0', true );
	// Marquee.
	wp_enqueue_script( 'standard-blog-marquee-script', get_template_directory_uri() . '/assets/js/jquery.marquee.min.js', array( 'jquery' ), '1.8.0', true );
	// Custom script.
	wp_enqueue_script( 'standard-blog-custom-script', get_template_directory_uri() . '/assets/js/custom.min.js', array( 'jquery' ), STANDARD_BLOG_VERSION, true );
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'standard_blog_scripts' );
/**
 * Webfont Loader.
 */
require get_template_directory() . '/inc/wptt-webfont-loader.php';
/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';
/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';
/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/inc/template-functions.php';
/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';
/**
 * Breadcrumb trail class.
 */
require get_template_directory() . '/inc/class-breadcrumb-trail.php';
/**
 * Load Jetpack compatibility file.
 */
if ( defined( 'JETPACK__VERSION' ) ) {
	require get_template_directory() . '/inc/jetpack.php';
}
/**
 * Recommended Plugins.
 */
require get_template_directory() . '/inc/tgmpa/recommended-plugins.php';
/**
 * Widgets.
 */
require get_template_directory() . '/inc/widgets/widgets.php';
/**
 * Custom Style.
 */
require get_template_directory() . '/inc/custom-style.php';
/**
 * One Click Demo Import after import setup.
 */
if ( class_exists( 'OCDI_Plugin' ) ) {
	require get_template_directory() . '/inc/demo-import.php';
}

/**
 * WordPress Multilingual System with Separate Sitemaps
 * Spanish posts use -es suffix and have separate sitemap at /es/post-sitemap.xml
 */

// Register meta fields with REST permissions
add_action('init', function() {
    foreach(['post', 'page'] as $type) {
        register_post_meta($type, '_language_code', [
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'auth_callback' => '__return_true'
        ]);
        register_post_meta($type, '_original_post_id', [
            'show_in_rest' => true,
            'single' => true,
            'type' => 'integer',
            'auth_callback' => '__return_true'
        ]);
        register_post_meta($type, '_translation_group', [
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'auth_callback' => '__return_true'
        ]);
        register_post_meta($type, '_hreflang_tags', [
            'show_in_rest' => true,
            'single' => true,
            'type' => 'string',
            'auth_callback' => '__return_true'
        ]);
    }
});

// URL Rewrite Rules for /es/ and Spanish sitemap - FIXED VERSION
add_action('init', function() {
    // Spanish homepage - FIXED to avoid 403
    add_rewrite_rule('^es/?$', 'index.php?lang=es&is_spanish_home=1', 'top');
    // Spanish blog archive
    add_rewrite_rule('^es/blog/?$', 'index.php?pagename=blog&lang=es', 'top');
    add_rewrite_rule('^es/blog/page/([0-9]+)/?$', 'index.php?pagename=blog&paged=$matches[1]&lang=es', 'top');
    // Spanish categories
    add_rewrite_rule('^es/category/(.+?)/?$', 'index.php?category_name=$matches[1]&lang=es', 'top');
    add_rewrite_rule('^es/category/(.+?)/page/([0-9]+)/?$', 'index.php?category_name=$matches[1]&paged=$matches[2]&lang=es', 'top');
    // Spanish tags
    add_rewrite_rule('^es/tag/(.+?)/?$', 'index.php?tag=$matches[1]&lang=es', 'top');
    add_rewrite_rule('^es/tag/(.+?)/page/([0-9]+)/?$', 'index.php?tag=$matches[1]&paged=$matches[2]&lang=es', 'top');
    // Spanish pagination
    add_rewrite_rule('^es/page/([0-9]+)/?$', 'index.php?paged=$matches[1]&lang=es&is_spanish_home=1', 'top');
    // Spanish single posts
    add_rewrite_rule('^es/([^/]+)/?$', 'index.php?name=$matches[1]&lang=es', 'top');
    // Spanish pages
    add_rewrite_rule('^es/(.+?)/?$', 'index.php?pagename=$matches[1]&lang=es', 'top');
    
    // Spanish sitemap URLs
    add_rewrite_rule('^es/post-sitemap\.xml$', 'index.php?spanish_sitemap=1', 'top');
    add_rewrite_rule('^es/sitemap\.xml$', 'index.php?spanish_sitemap_index=1', 'top');
    
    // Flush rewrite rules if needed
    if (get_option('spanish_rewrite_version') !== '4.0') {
        flush_rewrite_rules();
        update_option('spanish_rewrite_version', '4.0');
    }
});

// Add query vars - UPDATED
add_filter('query_vars', function($vars) {
    $vars[] = 'lang';
    $vars[] = 'spanish_sitemap';
    $vars[] = 'spanish_sitemap_index';
    $vars[] = 'is_spanish_home';
    return $vars;
});

// Handle Spanish homepage specifically
add_action('template_redirect', function() {
    if (get_query_var('is_spanish_home') == 1) {
        // Force WordPress to show the blog homepage for Spanish
        global $wp_query;
        $wp_query->is_home = true;
        $wp_query->is_front_page = true;
        $wp_query->is_404 = false;
    }
});

// Filter homepage and archives to show correct language - UPDATED VERSION
add_action('pre_get_posts', function($query) {
    if (is_admin() || !$query->is_main_query()) return;
    
    // Get current language
    $is_spanish = (get_query_var('lang') === 'es' || get_query_var('is_spanish_home') == 1 || strpos($_SERVER['REQUEST_URI'], '/es/') === 0);
    
    // For Spanish pages (/es/ or /es/blog/)
    if ($is_spanish) {
        if ($query->is_home() || $query->is_archive() || $query->is_category() || $query->is_tag() || get_query_var('is_spanish_home') == 1) {
            // Show only Spanish posts (with -es suffix)
            global $wpdb;
            $spanish_ids = $wpdb->get_col(
                "SELECT ID FROM {$wpdb->posts} 
                 WHERE post_status = 'publish' 
                 AND post_type = 'post'
                 AND post_name LIKE '%-es'"
            );
            
            if (!empty($spanish_ids)) {
                $query->set('post__in', $spanish_ids);
            } else {
                // No Spanish posts, show nothing
                $query->set('post__in', array(0));
            }
        }
        
        // Handle single posts
        if (get_query_var('name')) {
            $requested_slug = get_query_var('name');
            global $wpdb;
            
            $spanish_slug = $requested_slug . '-es';
            $spanish_id = $wpdb->get_var($wpdb->prepare(
                "SELECT ID FROM {$wpdb->posts}
                 WHERE post_status = 'publish'
                 AND post_type IN ('post', 'page')
                 AND post_name = %s
                 LIMIT 1",
                $spanish_slug
            ));
            
            if ($spanish_id) {
                $query->set('p', $spanish_id);
                $query->set('name', '');
                $query->is_single = true;
                $query->is_singular = true;
            }
        }
    } else {
        // For English pages (main site)
        if ($query->is_home() || $query->is_archive() || $query->is_category() || $query->is_tag()) {
            // Exclude Spanish posts from English archives
            global $wpdb;
            $spanish_ids = $wpdb->get_col(
                "SELECT ID FROM {$wpdb->posts} 
                 WHERE post_status = 'publish' 
                 AND post_type = 'post'
                 AND post_name LIKE '%-es'"
            );
            
            if (!empty($spanish_ids)) {
                $query->set('post__not_in', $spanish_ids);
            }
        }
    }
});

// Create Spanish sitemap
add_action('template_redirect', function() {
    // Handle Spanish post sitemap
    if (get_query_var('spanish_sitemap') == 1) {
        header('Content-Type: application/xml; charset=utf-8');
        header('X-Robots-Tag: noindex, follow');
        
        // Get ALL posts with -es suffix
        global $wpdb;
        $spanish_posts = $wpdb->get_results(
            "SELECT ID, post_name, post_modified, post_title 
             FROM {$wpdb->posts} 
             WHERE post_status = 'publish' 
             AND post_type = 'post'
             AND post_name LIKE '%-es'
             ORDER BY post_modified DESC"
        );
        
        // Start XML output
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        
        if ($spanish_posts) {
            foreach ($spanish_posts as $post) {
                $base_slug = preg_replace('/-es$/', '', $post->post_name);
                $url = home_url('/es/' . $base_slug . '/');
                $modified = date('c', strtotime($post->post_modified));
                
                echo "  <url>\n";
                echo "    <loc>" . esc_url($url) . "</loc>\n";
                echo "    <lastmod>" . $modified . "</lastmod>\n";
                echo "    <changefreq>weekly</changefreq>\n";
                echo "    <priority>0.8</priority>\n";
                echo "  </url>\n";
            }
        }
        
        echo '</urlset>';
        exit;
    }
    
    // Handle Spanish sitemap index
    if (get_query_var('spanish_sitemap_index') == 1) {
        header('Content-Type: application/xml; charset=utf-8');
        echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        echo "  <sitemap>\n";
        echo "    <loc>" . home_url('/es/post-sitemap.xml') . "</loc>\n";
        echo "    <lastmod>" . date('c') . "</lastmod>\n";
        echo "  </sitemap>\n";
        echo '</sitemapindex>';
        exit;
    }
});

// Physical sitemap file creation
add_action('save_post', function($post_id) {
    $post = get_post($post_id);
    
    // Only regenerate for Spanish posts
    if ($post && $post->post_status === 'publish' && substr($post->post_name, -3) === '-es') {
        
        // Get all Spanish posts
        global $wpdb;
        $spanish_posts = $wpdb->get_results(
            "SELECT ID, post_name, post_modified 
             FROM {$wpdb->posts} 
             WHERE post_status = 'publish' 
             AND post_type = 'post'
             AND post_name LIKE '%-es'
             ORDER BY post_modified DESC"
        );
        
        // Build sitemap XML
        $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        
        foreach ($spanish_posts as $sp) {
            $base_slug = preg_replace('/-es$/', '', $sp->post_name);
            $url = home_url('/es/' . $base_slug . '/');
            $modified = date('c', strtotime($sp->post_modified));
            
            $xml .= "  <url>\n";
            $xml .= "    <loc>" . esc_url($url) . "</loc>\n";
            $xml .= "    <lastmod>" . $modified . "</lastmod>\n";
            $xml .= "    <changefreq>weekly</changefreq>\n";
            $xml .= "    <priority>0.8</priority>\n";
            $xml .= "  </url>\n";
        }
        
        $xml .= '</urlset>';
        
        // Create /es/ directory if needed
        $es_dir = ABSPATH . 'es';
        if (!file_exists($es_dir)) {
            wp_mkdir_p($es_dir);
        }
        
        // Save sitemap file
        file_put_contents($es_dir . '/post-sitemap.xml', $xml);
    }
});

// Exclude Spanish posts from main WordPress sitemap
add_filter('wp_sitemaps_posts_query_args', function($args, $post_type) {
    if ($post_type === 'post') {
        global $wpdb;
        
        // Get IDs of Spanish posts
        $spanish_ids = $wpdb->get_col(
            "SELECT ID FROM {$wpdb->posts} 
             WHERE post_status = 'publish' 
             AND post_type = 'post'
             AND post_name LIKE '%-es'"
        );
        
        if (!empty($spanish_ids)) {
            $args['post__not_in'] = isset($args['post__not_in']) ? 
                array_merge($args['post__not_in'], $spanish_ids) : $spanish_ids;
        }
    }
    return $args;
}, 10, 2);

// Add Spanish sitemap to robots.txt
add_filter('robots_txt', function($output, $public) {
    if ($public) {
        $output .= "\nSitemap: " . home_url('/es/sitemap.xml');
        $output .= "\nSitemap: " . home_url('/es/post-sitemap.xml');
    }
    return $output;
}, 10, 2);

// Prevent redirects on /es/ URLs
add_filter('redirect_canonical', function($redirect_url, $requested_url) {
    if (strpos($requested_url, '/es/') !== false) {
        return false;
    }
    return $redirect_url;
}, 10, 2);

// Redirect wrong Spanish URLs to correct ones
add_action('template_redirect', function() {
    if (is_404()) return;
    
    $current_url = $_SERVER['REQUEST_URI'];
    
    // If we're on /es/ URL and the slug ends with -es, redirect to without -es
    if (preg_match('/^\/es\/(.+)-es\/?$/i', $current_url, $matches)) {
        $correct_url = '/es/' . $matches[1] . '/';
        wp_redirect(home_url($correct_url), 301);
        exit;
    }
    
    // If someone accesses the direct -es URL, redirect to /es/ version
    if (is_singular() && !is_admin()) {
        global $post;
        if ($post && substr($post->post_name, -3) === '-es') {
            $base_slug = substr($post->post_name, 0, -3);
            $spanish_url = '/es/' . $base_slug . '/';
            
            // Only redirect if we're not already on the /es/ URL
            if (strpos($current_url, '/es/') === false) {
                wp_redirect(home_url($spanish_url), 301);
                exit;
            }
        }
    }
});

// Output hreflang and canonical for all pages
add_action('wp_head', function() {
    $current_url = home_url($_SERVER['REQUEST_URI']);
    $is_spanish = strpos($current_url, '/es/') === 0 || strpos($current_url, home_url('/es')) === 0;
    
    // For homepage
    if ((is_home() || get_query_var('is_spanish_home') == 1) && !is_paged()) {
        if ($is_spanish) {
            echo '<link rel="canonical" href="' . home_url('/es/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="en" href="' . home_url('/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/') . '" />' . "\n";
        } else {
            echo '<link rel="canonical" href="' . home_url('/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="en" href="' . home_url('/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/') . '" />' . "\n";
        }
        return;
    }
    
    // For blog page
    if (is_page('blog')) {
        if ($is_spanish) {
            echo '<link rel="canonical" href="' . home_url('/es/blog/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/blog/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="en" href="' . home_url('/blog/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/blog/') . '" />' . "\n";
        } else {
            echo '<link rel="canonical" href="' . home_url('/blog/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="en" href="' . home_url('/blog/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/blog/') . '" />' . "\n";
            echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/blog/') . '" />' . "\n";
        }
        return;
    }
    
    // For category archives
    if (is_category()) {
        $category = get_queried_object();
        if ($category) {
            $cat_slug = $category->slug;
            if ($is_spanish) {
                echo '<link rel="canonical" href="' . home_url('/es/category/' . $cat_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/category/' . $cat_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="en" href="' . home_url('/category/' . $cat_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/category/' . $cat_slug . '/') . '" />' . "\n";
            } else {
                echo '<link rel="canonical" href="' . home_url('/category/' . $cat_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="en" href="' . home_url('/category/' . $cat_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/category/' . $cat_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/category/' . $cat_slug . '/') . '" />' . "\n";
            }
        }
        return;
    }
    
    // For tag archives
    if (is_tag()) {
        $tag = get_queried_object();
        if ($tag) {
            $tag_slug = $tag->slug;
            if ($is_spanish) {
                echo '<link rel="canonical" href="' . home_url('/es/tag/' . $tag_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/tag/' . $tag_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="en" href="' . home_url('/tag/' . $tag_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/tag/' . $tag_slug . '/') . '" />' . "\n";
            } else {
                echo '<link rel="canonical" href="' . home_url('/tag/' . $tag_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="en" href="' . home_url('/tag/' . $tag_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="es" href="' . home_url('/es/tag/' . $tag_slug . '/') . '" />' . "\n";
                echo '<link rel="alternate" hreflang="x-default" href="' . home_url('/tag/' . $tag_slug . '/') . '" />' . "\n";
            }
        }
        return;
    }
    
    // For single posts
    if (is_singular()) {
        global $post;
        
        // Self-referencing canonical
        echo '<link rel="canonical" href="' . esc_url($current_url) . '" />' . "\n";
        
        // Hreflang tags from meta
        $hreflang = get_post_meta($post->ID, '_hreflang_tags', true);
        if ($hreflang) {
            $tags = json_decode($hreflang, true);
            if (is_array($tags)) {
                foreach ($tags as $tag) {
                    echo '<link rel="alternate" hreflang="' . esc_attr($tag['lang']) . '" href="' . esc_url($tag['url']) . '" />' . "\n";
                }
            }
        }
    }
}, 5);

// Fix pagination for Spanish archives
add_filter('paginate_links', function($link) {
    if (get_query_var('lang') === 'es' || get_query_var('is_spanish_home') == 1) {
        // Ensure Spanish pagination URLs are correct
        $link = str_replace(home_url('/page/'), home_url('/es/page/'), $link);
        $link = str_replace(home_url('/blog/page/'), home_url('/es/blog/page/'), $link);
        $link = str_replace(home_url('/category/'), home_url('/es/category/'), $link);
        $link = str_replace(home_url('/tag/'), home_url('/es/tag/'), $link);
    }
    return $link;
});

// Modify post permalinks in Spanish archives to include /es/
add_filter('post_link', function($permalink, $post) {
    // Only modify if we're on a Spanish page
    if (get_query_var('lang') === 'es' || get_query_var('is_spanish_home') == 1 || strpos($_SERVER['REQUEST_URI'], '/es/') === 0) {
        if (substr($post->post_name, -3) === '-es') {
            $base_slug = substr($post->post_name, 0, -3);
            $permalink = home_url('/es/' . $base_slug . '/');
        }
    }
    return $permalink;
}, 10, 2);

// Admin columns for language
add_filter('manage_posts_columns', function($columns) {
    $columns['language'] = 'Lang';
    return $columns;
});

add_filter('manage_pages_columns', function($columns) {
    $columns['language'] = 'Lang';
    return $columns;
});

add_action('manage_posts_custom_column', function($column, $post_id) {
    if ($column === 'language') {
        $lang = get_post_meta($post_id, '_language_code', true);
        if (!$lang) {
            $post = get_post($post_id);
            if (strpos($post->post_name, '-es') === strlen($post->post_name) - 3) {
                $lang = 'es';
            } else {
                $lang = 'en';
            }
        }
        $flags = ['en' => '🇬🇧', 'es' => '🇪🇸'];
        echo isset($flags[$lang]) ? $flags[$lang] . ' ' . strtoupper($lang) : '🇬🇧 EN';
    }
}, 10, 2);

add_action('manage_pages_custom_column', function($column, $post_id) {
    if ($column === 'language') {
        $lang = get_post_meta($post_id, '_language_code', true);
        if (!$lang) {
            $post = get_post($post_id);
            if (strpos($post->post_name, '-es') === strlen($post->post_name) - 3) {
                $lang = 'es';
            } else {
                $lang = 'en';
            }
        }
        $flags = ['en' => '🇬🇧', 'es' => '🇪🇸'];
        echo isset($flags[$lang]) ? $flags[$lang] . ' ' . strtoupper($lang) : '🇬🇧 EN';
    }
}, 10, 2);

// Fix Yoast SEO sitemap if present
add_filter('wpseo_sitemap_entry', function($url, $type, $post) {
    if ($type === 'post' && $post) {
        // If it's a Spanish post, change URL to /es/ format
        if (substr($post->post_name, -3) === '-es') {
            $base_slug = substr($post->post_name, 0, -3);
            $url['loc'] = home_url('/es/' . $base_slug . '/');
        }
    }
    return $url;
}, 10, 3);

// Exclude Spanish posts from Yoast main sitemap
add_filter('wpseo_exclude_from_sitemap_by_post_ids', function() {
    global $wpdb;
    $spanish_ids = $wpdb->get_col(
        "SELECT ID FROM {$wpdb->posts} 
         WHERE post_status = 'publish' 
         AND post_type = 'post'
         AND post_name LIKE '%-es'"
    );
    return $spanish_ids;
});

// Fix Yoast canonical
add_filter('wpseo_canonical', function($canonical) {
    if (strpos($_SERVER['REQUEST_URI'], '/es/') !== false) {
        return false;
    }
    return $canonical;
}, 20);

// Allow REST API to update custom meta fields
add_filter('rest_post_dispatch', function($response, $server, $request) {
    return $response;
}, 10, 3);

// Language switcher shortcode
add_shortcode('language_switcher', function() {
    if (!is_singular()) return '';
    
    global $post;
    $current_lang = get_post_meta($post->ID, '_language_code', true);
    $output = '<div class="language-switcher">';
    
    if ($current_lang === 'es' || strpos($post->post_name, '-es') !== false) {
        // We're on Spanish, link to English
        $original_id = get_post_meta($post->ID, '_original_post_id', true);
        if ($original_id) {
            $english_post = get_post($original_id);
            if ($english_post) {
                $output .= '<a href="' . get_permalink($english_post) . '">🇬🇧 English</a>';
            }
        } else {
            // Try to find English by removing -es
            $english_slug = preg_replace('/-es$/', '', $post->post_name);
            $output .= '<a href="/' . $english_slug . '/">🇬🇧 English</a>';
        }
    } else {
        // We're on English, link to Spanish
        $base_slug = $post->post_name;
        $output .= '<a href="/es/' . $base_slug . '/">🇪🇸 Español</a>';
    }
    
    $output .= '</div>';
    return $output;
});