/*
Theme Name: Flatsome Child
Description: This is a child theme for Flatsome Theme
Author: UX Themes
Template: flatsome
Version: 3.0
*/

/*************** ADD CUSTOM CSS HERE.   ***************/


@media only screen and (max-width: 48em) {
/*************** ADD MOBILE ONLY CSS HERE  ***************/


}
<?php
/**
 * FLATSOME THEME OPTIMIZATION CODE
 * Thêm vào functions.php của child theme
 */

// ========== 1. LOẠI BỎ CÁC SCRIPT VÀ STYLE KHÔNG CẦN THIẾT ==========

function flatsome_remove_unused_scripts() {
    if (!is_admin()) {
        // Loại bỏ jQuery Migrate nếu không cần
        wp_deregister_script('jquery-migrate');
        
        // Loại bỏ Dashicons cho front-end (nếu không đăng nhập)
        if (!is_user_logged_in()) {
            wp_dequeue_style('dashicons');
        }
        
        // Loại bỏ WP Block Library CSS nếu không dùng Gutenberg
        wp_dequeue_style('wp-block-library');
        wp_dequeue_style('wp-block-library-theme');
        wp_dequeue_style('wc-blocks-style');
        
        // Loại bỏ Contact Form 7 CSS/JS khỏi trang không có form
        if (!is_page() && !is_single()) {
            wp_dequeue_script('contact-form-7');
            wp_dequeue_style('contact-form-7');
        }
        
        // Loại bỏ WooCommerce scripts khỏi trang không phải shop
        if (!is_woocommerce() && !is_cart() && !is_checkout() && !is_shop() && !is_product_category() && !is_product_tag() && !is_product()) {
            wp_dequeue_script('wc-add-to-cart');
            wp_dequeue_script('wc-cart-fragments');
            wp_dequeue_script('woocommerce');
            wp_dequeue_script('wc-add-to-cart-variation');
            wp_dequeue_style('woocommerce-layout');
            wp_dequeue_style('woocommerce-smallscreen');
            wp_dequeue_style('woocommerce-general');
        }
    }
}
add_action('wp_enqueue_scripts', 'flatsome_remove_unused_scripts', 999);

// ========== 2. TỐI ƯU HÓA FLATSOME SCRIPTS ==========

function flatsome_optimize_scripts() {
    if (!is_admin()) {
        // Defer JavaScript files
        add_filter('script_loader_tag', function($tag, $handle) {
            $defer_scripts = array(
                'flatsome-js',
                'flatsome-theme-js',
                'jquery-hoverIntent',
                'flatsome-scrollto',
                'flatsome-tooltips',
                'flatsome-lazy-loading'
            );
            
            if (in_array($handle, $defer_scripts)) {
                return str_replace(' src', ' defer src', $tag);
            }
            return $tag;
        }, 10, 2);
        
        // Preload important fonts
        add_action('wp_head', function() {
            echo '<link rel="preload" href="' . get_template_directory_uri() . '/assets/css/icons.css" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">';
        }, 1);
    }
}
add_action('init', 'flatsome_optimize_scripts');

// ========== 3. LOẠI BỎ CÁC TÍNH NĂNG FLATSOME KHÔNG CẦN THIẾT ==========

function disable_flatsome_features() {
    // Tắt Flatsome Panel nếu không cần
    remove_action('wp_enqueue_scripts', 'flatsome_admin_bar_style');
    
    // Tắt Flatsome maintenance mode
    remove_action('init', 'flatsome_maintenance_mode');
    
    // Loại bỏ Flatsome custom fonts nếu không dùng
    add_filter('flatsome_google_fonts_url', '__return_false');
    
    // Tắt Flatsome blog shortcodes nếu không dùng blog
    if (!is_home() && !is_single() && !is_archive()) {
        remove_action('init', 'flatsome_register_blog_shortcodes');
    }
}
add_action('after_setup_theme', 'disable_flatsome_features');

// ========== 4. TỐI ƯU HÓA CSS ==========

function flatsome_optimize_css() {
    // Inline critical CSS
    add_action('wp_head', function() {
        echo '<style id="critical-css">
        body{font-family:inherit}
        .header{background:#fff;border-bottom:1px solid #eee}
        .nav-top{background:#000}
        .button{background:#0073aa;color:#fff;padding:10px 20px;border:none;cursor:pointer}
        .loading{opacity:0.5}
        </style>';
    }, 1);
    
    // Defer non-critical CSS
    add_filter('style_loader_tag', function($tag, $handle) {
        $defer_styles = array(
            'flatsome-icons',
            'flatsome-shop',
            'flatsome-blog'
        );
        
        if (in_array($handle, $defer_styles)) {
            $tag = str_replace('rel="stylesheet"', 'rel="preload" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"', $tag);
        }
        return $tag;
    }, 10, 2);
}
add_action('wp_enqueue_scripts', 'flatsome_optimize_css', 1);

// ========== 5. LOẠI BỎ CÁC WIDGET VÀ SHORTCODE KHÔNG DÙNG ==========

function remove_unused_widgets() {
    // Unregister unused widgets
    add_action('widgets_init', function() {
        unregister_widget('WP_Widget_Calendar');
        unregister_widget('WP_Widget_Archives');
        unregister_widget('WP_Widget_Links');
        unregister_widget('WP_Widget_Meta');
        unregister_widget('WP_Widget_Search');
        unregister_widget('WP_Widget_Text');
        unregister_widget('WP_Widget_Categories');
        unregister_widget('WP_Widget_Recent_Posts');
        unregister_widget('WP_Widget_Recent_Comments');
        unregister_widget('WP_Widget_RSS');
        unregister_widget('WP_Widget_Tag_Cloud');
    }, 11);
}
// remove_unused_widgets(); // Uncomment nếu muốn dùng

// ========== 6. TỐI ƯU HÓA IMAGES VÀ LAZY LOADING ==========

function flatsome_optimize_images() {
    // Enable lazy loading cho images
    add_filter('wp_get_attachment_image_attributes', function($attr) {
        $attr['loading'] = 'lazy';
        return $attr;
    });
    
    // Remove image sizes không dùng
    add_filter('intermediate_image_sizes', function($sizes) {
        return array_diff($sizes, ['medium_large', 'large', '1536x1536', '2048x2048']);
    });
    
    // Tối ưu WebP
    add_filter('wp_generate_attachment_metadata', function($metadata, $attachment_id) {
        $file = get_attached_file($attachment_id);
        if ($file && function_exists('imagewebp')) {
            $image = wp_get_image_editor($file);
            if (!is_wp_error($image)) {
                $webp_file = preg_replace('/\.(jpg|jpeg|png)$/i', '.webp', $file);
                $image->save($webp_file, 'image/webp');
            }
        }
        return $metadata;
    }, 10, 2);
}
add_action('init', 'flatsome_optimize_images');

// ========== 7. LOẠI BỎ CÁC EMBEDS VÀ EMOJI ==========

function remove_wp_bloat() {
    // Remove emoji scripts
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('admin_print_styles', 'print_emoji_styles');
    
    // Remove WordPress embeds
    remove_action('wp_head', 'wp_oembed_add_discovery_links');
    remove_action('wp_head', 'wp_oembed_add_host_js');
    
    // Remove RSS feed links
    remove_action('wp_head', 'feed_links', 2);
    remove_action('wp_head', 'feed_links_extra', 3);
    
    // Remove RSD link
    remove_action('wp_head', 'rsd_link');
    
    // Remove wlwmanifest.xml
    remove_action('wp_head', 'wlwmanifest_link');
    
    // Remove WordPress generator
    remove_action('wp_head', 'wp_generator');
    
    // Remove shortlink
    remove_action('wp_head', 'wp_shortlink_wp_head');
}
add_action('init', 'remove_wp_bloat');

// ========== 8. TỐI ƯU HÓA DATABASE QUERIES ==========

function optimize_database_queries() {
    // Limit post revisions
    if (!defined('WP_POST_REVISIONS')) {
        define('WP_POST_REVISIONS', 3);
    }
    
    // Remove query strings from static resources
    add_filter('script_loader_src', 'remove_script_version', 15, 1);
    add_filter('style_loader_src', 'remove_script_version', 15, 1);
    
    function remove_script_version($src) {
        $parts = explode('?ver', $src);
        return $parts[0];
    }
}
add_action('init', 'optimize_database_queries');

// ========== 9. PRELOAD VÀ PREFETCH RESOURCES ==========

function add_resource_hints() {
    echo '<link rel="preconnect" href="//fonts.googleapis.com" crossorigin>';
    echo '<link rel="preconnect" href="//fonts.gstatic.com" crossorigin>';
    echo '<link rel="dns-prefetch" href="//ajax.googleapis.com">';
    echo '<link rel="dns-prefetch" href="//maxcdn.bootstrapcdn.com">';
    
    // Preload critical resources
    if (is_front_page()) {
        echo '<link rel="preload" href="' . get_stylesheet_directory_uri() . '/style.css" as="style">';
        echo '<link rel="preload" href="' . get_template_directory_uri() . '/assets/js/flatsome.js" as="script">';
    }
}
add_action('wp_head', 'add_resource_hints', 1);

// ========== 10. CONDITIONAL LOADING ==========

function conditional_script_loading() {
    // Chỉ load Contact Form 7 trên pages có form
    if (function_exists('wpcf7_enqueue_scripts')) {
        wp_dequeue_script('contact-form-7');
        wp_dequeue_style('contact-form-7');
        
        if (is_page() || is_single()) {
            global $post;
            if (has_shortcode($post->post_content, 'contact-form-7')) {
                wp_enqueue_script('contact-form-7');
                wp_enqueue_style('contact-form-7');
            }
        }
    }
    
    // Conditional WooCommerce loading
    if (class_exists('WooCommerce')) {
        if (!is_woocommerce() && !is_cart() && !is_checkout()) {
            wp_dequeue_style('woocommerce-layout');
            wp_dequeue_style('woocommerce-smallscreen');
            wp_dequeue_style('woocommerce-general');
            wp_dequeue_script('wc-add-to-cart');
            wp_dequeue_script('wc-cart-fragments');
        }
    }
}
add_action('wp_enqueue_scripts', 'conditional_script_loading', 999);

// ========== 11. MINIFY HTML OUTPUT ==========

function minify_html_output($buffer) {
    if (!is_admin() && !is_user_logged_in()) {
        $search = array(
            '/\>[^\S ]+/s',     // strip whitespaces after tags, except space
            '/[^\S ]+\</s',     // strip whitespaces before tags, except space
            '/(\s)+/s',         // shorten multiple whitespace sequences
            '/<!--(.|\s)*?-->/' // Remove HTML comments
        );
        $replace = array(
            '>',
            '<',
            '\\1',
            ''
        );
        $buffer = preg_replace($search, $replace, $buffer);
    }
    return $buffer;
}

function start_html_minification() {
    if (!is_admin() && !is_user_logged_in()) {
        ob_start('minify_html_output');
    }
}
add_action('init', 'start_html_minification');

// ========== 12. DISABLE UNUSED FLATSOME FEATURES ==========

// Tắt Flatsome Live Search nếu không dùng
add_filter('flatsome_live_search', '__return_false');

// Tắt Flatsome Portfolio nếu không dùng
add_filter('flatsome_portfolio', '__return_false');

// Tắt Flatsome maintenance mode
remove_action('template_redirect', 'flatsome_maintenance_mode');

// Loại bỏ Flatsome admin styles
function remove_flatsome_admin_styles() {
    wp_dequeue_style('flatsome-admin');
    wp_dequeue_script('flatsome-admin');
}
add_action('wp_enqueue_scripts', 'remove_flatsome_admin_styles', 999);

// ========== 13. CACHE CONTROL ==========

function add_cache_headers() {
    if (!is_admin() && !is_user_logged_in()) {
        header('Cache-Control: public, max-age=31536000');
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
    }
}
add_action('send_headers', 'add_cache_headers');

// ========== 14. REMOVE UNUSED SHORTCODES ==========

function remove_unused_shortcodes() {
    // Loại bỏ các shortcode không dùng
    remove_shortcode('gallery');
    remove_shortcode('audio');
    remove_shortcode('video');
    remove_shortcode('playlist');
    remove_shortcode('embed');
    
    // Loại bỏ Flatsome shortcodes không dùng (uncomment nếu cần)
    // remove_shortcode('portfolio');
    // remove_shortcode('blog_posts');
    // remove_shortcode('team_member');
}
// add_action('init', 'remove_unused_shortcodes'); // Uncomment nếu muốn dùng

// ========== 15. OPTIMIZE FONTS ==========

function optimize_google_fonts() {
    // Remove default Flatsome Google Fonts
    add_filter('flatsome_google_fonts', function($fonts) {
        // Chỉ giữ lại fonts thực sự cần thiết
        return array(
            'Lato:400,700' // Ví dụ chỉ giữ Lato
        );
    });
    
    // Preload Google Fonts
    add_action('wp_head', function() {
        echo '<link rel="preload" href="https://fonts.googleapis.com/css?family=Lato:400,700&display=swap" as="style" onload="this.onload=null;this.rel=\'stylesheet\'">';
    }, 1);
}
add_action('after_setup_theme', 'optimize_google_fonts');

?>

<!-- ========== CSS OPTIMIZATION (Thêm vào style.css) ========== -->
<style>
/* Critical CSS cho Above the Fold */
.header-wrapper { 
    background: #fff; 
    box-shadow: 0 2px 5px rgba(0,0,0,0.1); 
}

.nav-top { 
    display: none; 
}

/* Lazy load placeholder */
.lazy-loading {
    background: #f0f0f0;
    min-height: 200px;
}

/* Optimize hero section */
.hero-section {
    min-height: 400px;
    background-size: cover;
    background-position: center;
}

/* Mobile first approach */
@media (max-width: 768px) {
    .hide-on-mobile { display: none !important; }
    .header-search { display: none; }
    .nav-sidebar { transform: translateX(-100%); }
}

/* Preload animations */
.fade-in {
    animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}
</style>