<?php
/**
 * Caching functionality for AI Blog Theme
 *
 * @package Ai Blog
 */

/**
 * Cache management class
 */
class AI_Blog_Cache {
    
    /**
     * Cache group name
     */
    const CACHE_GROUP = 'ai_blog_cache';
    
    /**
     * Cache expiration time (1 hour)
     */
    const CACHE_EXPIRY = 3600;
    
    /**
     * Initialize cache functionality
     */
    public static function init() {
        // Add cache-related hooks
        add_action('save_post', array(__CLASS__, 'clear_post_cache'));
        add_action('wp_update_nav_menu', array(__CLASS__, 'clear_menu_cache'));
        add_action('customize_save_after', array(__CLASS__, 'clear_customizer_cache'));
        add_action('wp_head', array(__CLASS__, 'add_cache_headers'));
        
        // Add cache warming for critical elements
        add_action('init', array(__CLASS__, 'warm_cache'));
    }
    
    /**
     * Get cached data
     */
    public static function get_cache($key) {
        return wp_cache_get($key, self::CACHE_GROUP);
    }
    
    /**
     * Set cached data
     */
    public static function set_cache($key, $data, $expiry = null) {
        if (is_null($expiry)) {
            $expiry = self::CACHE_EXPIRY;
        }
        return wp_cache_set($key, $data, self::CACHE_GROUP, $expiry);
    }
    
    /**
     * Delete cached data
     */
    public static function delete_cache($key) {
        return wp_cache_delete($key, self::CACHE_GROUP);
    }
    
    /**
     * Clear all theme cache
     */
    public static function clear_all_cache() {
        // Clear common cache keys
        $cache_keys = array(
            'menu_main',
            'recent_posts',
            'popular_posts',
            'categories_list',
            'footer_widgets',
            'customizer_css',
            'google_fonts_url'
        );
        
        foreach ($cache_keys as $key) {
            self::delete_cache($key);
        }
        
        // Clear object cache if available
        if (function_exists('wp_cache_flush')) {
            wp_cache_flush();
        }
    }
    
    /**
     * Clear post-related cache
     */
    public static function clear_post_cache($post_id) {
        // Clear recent posts cache
        self::delete_cache('recent_posts');
        self::delete_cache('popular_posts');
        
        // Clear specific post cache
        self::delete_cache('post_' . $post_id);
        
        // Clear category cache if post has categories
        $categories = get_the_category($post_id);
        if (!empty($categories)) {
            self::delete_cache('categories_list');
        }
    }
    
    /**
     * Clear menu cache
     */
    public static function clear_menu_cache() {
        self::delete_cache('menu_main');
    }
    
    /**
     * Clear customizer cache
     */
    public static function clear_customizer_cache() {
        self::delete_cache('customizer_css');
        self::delete_cache('google_fonts_url');
    }
    
    /**
     * Add cache headers
     */
    public static function add_cache_headers() {
        if (!is_admin() && !is_user_logged_in()) {
            // Add browser cache headers
            header('Cache-Control: public, max-age=3600');
            header('Vary: Accept-Encoding');
            
            // Add ETag for better caching
            $etag = md5(get_template_directory_uri() . get_bloginfo('version'));
            header('ETag: "' . $etag . '"');
        }
    }
    
    /**
     * Warm cache for critical elements
     */
    public static function warm_cache() {
        // Only warm cache for front-end
        if (!is_admin()) {
            // Warm navigation menu cache
            self::get_cached_menu();
            
            // Warm Google Fonts URL cache
            self::get_cached_google_fonts_url();
        }
    }
    
    /**
     * Get cached navigation menu
     */
    public static function get_cached_menu() {
        $cached_menu = self::get_cache('menu_main');
        
        if (false === $cached_menu) {
            ob_start();
            wp_nav_menu(array(
                'theme_location' => 'main-menu',
                'menu_id'        => 'ai-blog-menu',
                'menu_class'     => 'ai-blog-menu',
                'echo'           => false
            ));
            $cached_menu = ob_get_clean();
            
            self::set_cache('menu_main', $cached_menu);
        }
        
        return $cached_menu;
    }
    
    /**
     * Get cached Google Fonts URL
     */
    public static function get_cached_google_fonts_url() {
        $cached_url = self::get_cache('google_fonts_url');
        
        if (false === $cached_url) {
            if (function_exists('ai_blog_fonts_url')) {
                $cached_url = ai_blog_fonts_url();
                self::set_cache('google_fonts_url', $cached_url);
            }
        }
        
        return $cached_url;
    }
    
    /**
     * Get cached recent posts
     */
    public static function get_cached_recent_posts($count = 5) {
        $cache_key = 'recent_posts_' . $count;
        $cached_posts = self::get_cache($cache_key);
        
        if (false === $cached_posts) {
            $cached_posts = wp_get_recent_posts(array(
                'numberposts' => $count,
                'post_status' => 'publish'
            ));
            
            self::set_cache($cache_key, $cached_posts);
        }
        
        return $cached_posts;
    }
    
    /**
     * Get cached categories
     */
    public static function get_cached_categories() {
        $cached_categories = self::get_cache('categories_list');
        
        if (false === $cached_categories) {
            $cached_categories = get_categories(array(
                'orderby' => 'name',
                'order'   => 'ASC'
            ));
            
            self::set_cache('categories_list', $cached_categories);
        }
        
        return $cached_categories;
    }
    
    /**
     * Get cached customizer CSS
     */
    public static function get_cached_customizer_css() {
        $cached_css = self::get_cache('customizer_css');
        
        if (false === $cached_css) {
            $cached_css = self::generate_customizer_css();
            self::set_cache('customizer_css', $cached_css);
        }
        
        return $cached_css;
    }
    
    /**
     * Generate customizer CSS
     */
    private static function generate_customizer_css() {
        $css = '';
        
        // Get theme colors
        $primary_color = get_theme_mod('ai_blog_primary_color', '#c70000');
        if ($primary_color !== '#c70000') {
            $css .= ':root { --color-primary: ' . esc_attr($primary_color) . '; }';
        }
        
        // Get custom fonts
        $heading_font = get_theme_mod('ai_blog_heading_font', '');
        if (!empty($heading_font)) {
            $css .= 'h1, h2, h3, h4, h5, h6 { font-family: ' . esc_attr($heading_font) . '; }';
        }
        
        return $css;
    }
}

/**
 * Initialize cache functionality
 */
AI_Blog_Cache::init();

/**
 * Helper functions for theme developers
 */

/**
 * Get cached menu output
 */
function ai_blog_get_cached_menu() {
    return AI_Blog_Cache::get_cached_menu();
}

/**
 * Get cached recent posts
 */
function ai_blog_get_cached_recent_posts($count = 5) {
    return AI_Blog_Cache::get_cached_recent_posts($count);
}

/**
 * Get cached categories
 */
function ai_blog_get_cached_categories() {
    return AI_Blog_Cache::get_cached_categories();
}

/**
 * Clear all theme cache (useful for development)
 */
function ai_blog_clear_cache() {
    AI_Blog_Cache::clear_all_cache();
}

/**
 * Add cache clearing option to admin bar
 */
function ai_blog_add_cache_admin_bar($wp_admin_bar) {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    // Get current page URL for redirect
    $current_url = (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    $redirect_to = is_admin() ? admin_url('themes.php') : $current_url;
    
    $args = array(
        'id'    => 'ai_blog_clear_cache',
        'title' => 'Clear AI Blog Cache',
        'href'  => wp_nonce_url(
            add_query_arg(
                array(
                    'ai_blog_clear_cache' => '1',
                    'redirect_to' => urlencode($redirect_to)
                ),
                admin_url('admin.php')
            ),
            'ai_blog_clear_cache'
        ),
        'meta'  => array(
            'class' => 'ai-blog-clear-cache'
        )
    );
    
    $wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'ai_blog_add_cache_admin_bar', 100);

/**
 * Add Upgrade AI Blog Pro link to admin bar
 */
function ai_blog_add_upgrade_admin_bar($wp_admin_bar) {
    if (!current_user_can('manage_options')) {
        return;
    }
    
    $args = array(
        'id'    => 'ai_blog_upgrade_pro',
        'title' => esc_html__('🔥 Upgrade AI Blog Pro', 'ai-blog'),
        'href'  => 'https://wpthemespace.com/product/ai-blog-pro/?add-to-cart=8864',
        'meta'  => array(
            'class' => 'ai-blog-upgrade-pro',
            'target' => '_blank',
            'title' => esc_attr__('Upgrade to AI Blog Pro - Get premium features and free setup!', 'ai-blog')
        )
    );
    
    $wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'ai_blog_add_upgrade_admin_bar', 101);

/**
 * Handle cache clearing from admin
 */
function ai_blog_handle_cache_clearing() {
    if (isset($_GET['ai_blog_clear_cache']) && $_GET['ai_blog_clear_cache'] == '1') {
        if (!current_user_can('manage_options')) {
            wp_die(__('You do not have sufficient permissions to access this page.','ai-blog'));
        }
        
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'ai_blog_clear_cache')) {
            wp_die(__('Security check failed. Please try again.','ai-blog'));
        }
        
        // Clear the cache
        ai_blog_clear_cache();
        
        // Get redirect URL
        $redirect_to = isset($_GET['redirect_to']) ? urldecode($_GET['redirect_to']) : admin_url('themes.php');
        
        // Redirect with success message
        wp_redirect(add_query_arg('ai_blog_cache_cleared', '1', $redirect_to));
        exit;
    }
}
add_action('admin_init', 'ai_blog_handle_cache_clearing');

/**
 * Show cache cleared notice
 */
function ai_blog_cache_cleared_notice() {
    if (isset($_GET['ai_blog_cache_cleared']) && $_GET['ai_blog_cache_cleared'] == '1') {
        echo '<div class="notice notice-success is-dismissible">
            <p><strong>' . esc_html__('AI Blog Cache cleared successfully!', 'ai-blog') . '</strong></p>
        </div>';
    }
}
add_action('admin_notices', 'ai_blog_cache_cleared_notice');

/**
 * Image optimization and lazy loading
 */
function ai_blog_optimize_images() {
    // Add lazy loading to images
    add_filter('wp_get_attachment_image_attributes', 'ai_blog_add_lazy_loading');
    add_filter('the_content', 'ai_blog_add_lazy_loading_to_content');
}
add_action('init', 'ai_blog_optimize_images');

/**
 * Add lazy loading attribute to images
 */
function ai_blog_add_lazy_loading($attr) {
    if (!is_admin() && !is_feed()) {
        $attr['loading'] = 'lazy';
    }
    return $attr;
}

/**
 * Add lazy loading to content images
 */
function ai_blog_add_lazy_loading_to_content($content) {
    if (!is_admin() && !is_feed()) {
        $content = preg_replace('/<img(.*?)>/i', '<img$1 loading="lazy">', $content);
    }
    return $content;
}
