<?php


//thank you page 

add_action('woocommerce_thankyou', 'howcan_order_wrapper_start', 1);
function howcan_order_wrapper_start() {
    echo '<div class="container my-5 mt-5 mb-5"><div class="row justify-content-center"><div class="col-lg-8">';
}

add_action('woocommerce_thankyou', 'howcan_order_wrapper_end', 99);
function howcan_order_wrapper_end() {
    echo '</div></div></div>';
}
// print bitton 

add_action('woocommerce_thankyou', 'howcan_print_button_bootstrap', 5);
function howcan_print_button_bootstrap() {
    ?>
    <div class="text-end mb-3 no-print">
        <button onclick="window.print()" class="btn btn-outline-dark btn-sm">
            🖨 Print Invoice
        </button>
    </div>
    <?php
}




// Source - https://stackoverflow.com/a
// Posted by LoicTheAztec, modified by community. See post 'Timeline' for change history
// Retrieved 2026-01-27, License - CC BY-SA 4.0

add_action( 'woocommerce_checkout_before_customer_details', 'custom_before_checkout_form' ); 
function custom_before_checkout_form(){
    // Loop though cart items 
    foreach ( WC()->cart->get_cart() as $item ) { 
        // Get the WC_Product Object 
        $product = $item['data'];

        echo '<div align="center">' . $product->get_meta( 'checkout_name' ) . '</div><br>'; 
    }
}



add_filter('woocommerce_form_field_args','howcan_premium_checkout_fields',10,3);
function howcan_premium_checkout_fields($args){
    $args['input_class'][] = 'form-control';
    $args['label_class'][] = 'form-label';
    return $args;
}


// fix cart empty issus

add_filter( 'the_content', 'howcan_force_wc_cart_fix', 999 );  
  
function howcan_force_wc_cart_fix( $content ) {  
    if ( function_exists( 'is_cart' ) && is_cart() ) {  
        remove_all_filters( 'the_content' );  
        return do_shortcode( '[woocommerce_cart]' );  
    }  
  
    if ( function_exists( 'is_checkout' ) && is_checkout() ) {  
        remove_all_filters( 'the_content' );  
        return do_shortcode( '[woocommerce_checkout]' );  
    }  
  
    return $content;  
} 


remove_action('woocommerce_before_main_content','woocommerce_breadcrumb',20);

remove_action('woocommerce_before_shop_loop','woocommerce_result_count',20);
remove_action('woocommerce_before_shop_loop','woocommerce_catalog_ordering',30);


add_action('woocommerce_before_main_content','woocommerce_output_content_wrapper',10);



// === HowCan Theme Ads Panel === //
function howcan_ads_menu() {
    add_menu_page(
        'HowCan Ads Settings',
        'HowCan Ads',
        'manage_options',
        'howcan-ads',
        'howcan_ads_page',
        'dashicons-megaphone',
        61
    );
}
add_action('admin_menu', 'howcan_ads_menu');

// Settings Fields
function howcan_ads_register() {
    register_setting('howcan_ads_group', 'ads_header');
    register_setting('howcan_ads_group', 'ads_sidebar');
    register_setting('howcan_ads_group', 'ads_footer');
    register_setting('howcan_ads_group', 'ads_inside_post'); // For in-article ads
}
add_action('admin_init', 'howcan_ads_register');

function howcan_ads_page() { ?>
    <div class="wrap">
        <h1>HowCan Theme AdSense Settings</h1>
        <form method="post" action="options.php">
            <?php settings_fields('howcan_ads_group'); ?>
            <?php do_settings_sections('howcan_ads_group'); ?>

            <h2>Header Ads</h2>
            <textarea name="ads_header" rows="5" class="large-text"><?php echo esc_textarea(get_option('ads_header')); ?></textarea>

            <h2>Sidebar Ads</h2>
            <textarea name="ads_sidebar" rows="5" class="large-text"><?php echo esc_textarea(get_option('ads_sidebar')); ?></textarea>

            <h2>Footer Ads</h2>
            <textarea name="ads_footer" rows="5" class="large-text"><?php echo esc_textarea(get_option('ads_footer')); ?></textarea>

            <h2>Inside Post (In-Article Ad)</h2>
            <textarea name="ads_inside_post" rows="5" class="large-text"><?php echo esc_textarea(get_option('ads_inside_post')); ?></textarea>

            <?php submit_button(); ?>
        </form>
    </div>
<?php }

// Insert Ad Inside Single Post
function howcan_insert_ad_inside_post($content) {
    if (!is_singular('post')) return $content;

    $ad_code = get_option('ads_inside_post');
    if (!$ad_code) return $content;

    $paragraphs = explode('</p>', $content);
    $new_content = '';

    $insert_after = 2; // Paragraph 2 এর পর ad আসবে

    foreach ($paragraphs as $i => $paragraph) {
        if (trim($paragraph)) {
            $new_content .= $paragraph . '</p>';
        }

        if ($i == $insert_after) {
            $new_content .= '<div class="inside-post-ad">' . $ad_code . '</div>';
        }
    }

    return $new_content;
}
add_filter('the_content', 'howcan_insert_ad_inside_post');
// === Add Theme Option for Single Post Layout ===
function howcan_customize_registerr($wp_customize) {

    $wp_customize->add_section('howcan_single_layout_section', [
        'title'    => __('Single Post Layout', 'howcan'),
        'priority' => 130,
    ]);
$wp_customize->add_setting( 'howcan_single_layout', [
    'default'           => 'default',
    'transport'         => 'refresh',
    'sanitize_callback' => 'howcan_sanitize_single_layout',
] );

function howcan_sanitize_single_layout( $input ) {
    $valid = [ 'default', 'newspaper', 'blog' ]; // তোমার থিমে যে layout অপশন আছে তা অনুযায়ী দাও
    return in_array( $input, $valid, true ) ? $input : 'default';
}

    $wp_customize->add_control('howcan_single_layout_control', [
        'label'    => __('Select Single Post Layout', 'howcan'),
        'section'  => 'howcan_single_layout_section',
        'settings' => 'howcan_single_layout',
        'type'     => 'radio',
        'choices'  => [
            'default'   => __('Default Layout', 'howcan'),
            'newspaper' => __('Newspaper Layout', 'howcan'),
        ],
    ]);
}
add_action('customize_register', 'howcan_customize_registerr');


// AJAX Load More for News by Category
add_action('wp_ajax_load_more_news', 'howcan_load_more_news');
add_action('wp_ajax_nopriv_load_more_news', 'howcan_load_more_news');

function howcan_load_more_news() {
  $paged = intval($_GET['page'] ?? 1);
  $cat   = intval($_GET['cat'] ?? 0);

  $args = [
    'post_type' => 'post',
    'posts_per_page' => 6,
    'paged' => $paged,
    'cat' => $cat,
  ];

  $query = new WP_Query($args);

  if ($query->have_posts()) :
    while ($query->have_posts()) : $query->the_post();
?>
      <div class="col-sm-4 mb-4">
        <div class="card h-100 shadow-sm">
          <?php if (has_post_thumbnail()) : ?>
            <a href="<?php the_permalink(); ?>">
              <?php the_post_thumbnail('medium', ['class' => 'card-img-top rounded-top']); ?>
            </a>
          <?php endif; ?>
          <div class="card-body">
            <h6 class="card-title"><a href="<?php the_permalink(); ?>" class="text-decoration-none text-dark"><?php the_title(); ?></a></h6>
            <p class="text-small mb-1"><i class="bi bi-calendar"></i> <?php echo get_the_date(); ?></p>
            <p class="card-text small"><?php echo wp_trim_words(get_the_excerpt(), 15, '...'); ?></p>
          </div>
        </div>
      </div>
<?php
    endwhile;
  endif;
  wp_die();
}


// functions.php
function howcan_back_to_top_scripts() {
    // Style for back-to-top button
    wp_add_inline_style('wp-block-library', '
        #back-to-top {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: rgba(0,0,0,0.4); /* Transparent background */
            color: #fff;
            border: none;
            border-radius: 50%;
            display: none;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            z-index: 9999;
            font-size: 24px;
            transition: background 0.3s ease;
        }
        #back-to-top:hover {
            background: rgba(0,0,0,0.7);
        }
    ');

    // Script for smooth scroll
    wp_add_inline_script('jquery-core', '
        jQuery(document).ready(function($){
            $("body").append("<button id=\"back-to-top\" aria-label=\"Back to top\">&#8679;</button>");
            var btn = $("#back-to-top");
            $(window).scroll(function(){
                if ($(window).scrollTop() > 300) {
                    btn.fadeIn();
                } else {
                    btn.fadeOut();
                }
            });
            btn.on("click", function(e){
                e.preventDefault();
                $("html, body").animate({scrollTop:0}, "300");
            });
        });
    ');
}
add_action('wp_enqueue_scripts', 'howcan_back_to_top_scripts');

function howcan_customize_register_breaking_news( $wp_customize ) {

    // Section
    $wp_customize->add_section( 'howcan_breaking_news_section', array(
        'title'    => __( 'Breaking News', 'howcan' ),
        'priority' => 160,
    ) );

    // Enable / Disable Breaking News
    $wp_customize->add_setting( 'howcan_breaking_news_enable', array(
        'default'           => true,
        'sanitize_callback' => 'wp_validate_boolean',
    ) );

    $wp_customize->add_control( 'howcan_breaking_news_enable', array(
        'type'    => 'checkbox',
        'section' => 'howcan_breaking_news_section',
        'label'   => __( 'Enable Breaking News', 'howcan' ),
    ) );

    // Label Text
    $wp_customize->add_setting( 'howcan_breaking_news_label', array(
        'default'           => __( 'Breaking News', 'howcan' ),
        'sanitize_callback' => 'sanitize_text_field',
    ) );

    $wp_customize->add_control( 'howcan_breaking_news_label', array(
        'type'    => 'text',
        'section' => 'howcan_breaking_news_section',
        'label'   => __( 'Label Text', 'howcan' ),
        'description' => __( 'Change the text before the scrolling news (e.g., Breaking News, Trending, Update).', 'howcan' ),
    ) );
}
add_action( 'customize_register', 'howcan_customize_register_breaking_news' );

require_once get_template_directory() . '/inc/customizer/front-page/slider.php';
require_once get_template_directory() . '/inc/customizer/front-page/pricing.php';

require_once get_template_directory() . '/inc/customizer/sortable-control.php';

function howcan_front_arange( $wp_customize ) {
    $wp_customize->add_section( 'howcan_reorder_section', array(
        'title' => __( 'Homepage Section Order', 'howcan' ),
        'priority' => 30,
    ));

    // ✅ Recommended Default Order
    $default_order = 'slider,cta,features,about,pricing,blog,testimonials,newsletter';

    $wp_customize->add_setting( 'howcan_section_order', array(
        'default' => $default_order,
        'sanitize_callback' => 'sanitize_text_field',
    ));

    $wp_customize->add_control( new Howcan_Sortable_Control( $wp_customize, 'howcan_section_order', array(
        'label' => __( 'Reorder Homepage Sections', 'howcan' ),
        'section' => 'howcan_reorder_section',
        'choices' => array(
      
       'slider' => __( 'slider Section', 'howcan' ),
            
            'cta' => __( 'CTA Section', 'howcan' ),
            'features' => __( 'Features Section', 'howcan' ),
            'about' => __( 'About Section', 'howcan' ),
            'pricing' => __( 'Pricing Section', 'howcan' ),
            'blog' => __( 'Blog Section', 'howcan' ),
            'testimonials' => __( 'Testimonials Section', 'howcan' ),
            'newsletter' => __( 'Newsletter Section', 'howcan' ),
        ),
    )));
}
add_action( 'customize_register', 'howcan_front_arange' );
// support some of plugin 
function my_theme_register_required_plugins() {

    $plugins = array(
        array(
            'name'      => 'Howcan Pro Addon',
            'slug'      => 'howcan-pro-addons',
        
        'source'    => 'https://drive.google.com/uc?export=download&id=1LsegeOLAfqM5PaJCuPJDkFLSCDwda_bF', // drive URL
      
            'required'  => true, // true    'version'   => '1.0.0',
            'force_activation'   => false,
            'force_deactivation' => false, // true 
        ),
        array(
            'name'      => 'Howtube',
            'slug'      => 'howtube',
       
        'source'    => 'https://drive.google.com/uc?export=download&id=1uKgwuZXhTebNt_aQGZ49vDy6OZHw5s90', // dropbox URL
        
            'required'  => false, // true    'version'   => '1.0.0',
            'force_activation'   => false,
            'force_deactivation' => false, // true 
        ),
        array(
            'name'     => 'One Click Demo Import', // Plugin name
            'slug'     => 'one-click-demo-import', // Plugin slug (from WordPress repo)
            'required' => true, // Make it required
        ),
        
    );

    $config = array(
        'id'           => 'my-theme',                 
        'default_path' => '',                         
        'menu'         => 'tgmpa-install-plugins',   
        'has_notices'  => true,                       
        'dismissable'  => false,                      
        'is_automatic' => false,                      
    );

    tgmpa( $plugins, $config );
}
add_action( 'tgmpa_register', 'my_theme_register_required_plugins' );


// Categories list item- icon 
function howcan_add_folder_icon_to_categories($output, $args) {
    $output = str_replace('<a', '📁 <a', $output);
    return $output;
}
add_filter('wp_list_categories', 'howcan_add_folder_icon_to_categories', 10, 2);


// Add dropdown arrow for menu items with children
function howcan_add_dropdown_arrow( $output, $item, $depth, $args ) {
    if ( isset($args->theme_location) && $args->theme_location === 'primary' ) {
        if ( in_array( 'menu-item-has-children', $item->classes ) ) {
            $output .= '<span class="dropdown-toggle-icon" aria-hidden="true"></span>';
        }
    }
    return $output;
}
add_filter( 'walker_nav_menu_start_el', 'howcan_add_dropdown_arrow', 10, 4 );

// link attributes dynamic for accesbility 
function howcan_add_aria_current( $atts, $item, $args ) {
    if ( in_array( 'current-menu-item', $item->classes ) ) {
        $atts['aria-current'] = 'page';
    }
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'howcan_add_aria_current', 10, 3 );


// 1) parent links attributes add
function howcan_menu_link_attributes( $atts, $item, $args ) {
    if ( in_array( 'menu-item-has-children', (array) $item->classes ) ) {
        $atts['aria-haspopup'] = 'true';
    }
    return $atts;
    
}
add_filter( 'nav_menu_link_attributes', 'howcan_menu_link_attributes', 10, 3 );


// Ensure excerpts have underlined links too
add_filter( 'the_excerpt', function( $excerpt ) {
    return wpautop( $excerpt );
});


/**
 * Custom Footer Info Widget
 */
class Howcan_Footer_Info_Widget extends WP_Widget {

    public function __construct() {
        parent::__construct(
            'howcan_footer_info',
            __( 'Howcan: Footer Info Box', 'howcan' ),
            [ 'description' => __( 'Image + Title + Short description', 'howcan' ) ]
        );
    }

    public function widget( $args, $instance ) {
        echo $args['before_widget'];

        $title = ! empty( $instance['title'] ) ? $instance['title'] : '';
        $desc  = ! empty( $instance['desc'] ) ? $instance['desc'] : '';
        $image = ! empty( $instance['image'] ) ? $instance['image'] : '';

        ?>
        <div class="footer-info-widget d-flex align-items-start">
            <?php if ( $image ) : ?>
                <img src="<?php echo esc_url( $image ); ?>" alt="<?php echo esc_attr( $title ); ?>" class="me-2" style="width:40px;height:40px;padding-right:5px;">
            <?php endif; ?>
            <div>
                <?php if ( $title ) : ?>
                    <h3 class="mb-1 text-light"><?php echo esc_html( $title.' ' ); ?></h3>
                <?php endif; ?>
                <?php if ( $desc ) : ?>
                    <p class="small mb-0"><?php echo esc_html( $desc ); ?></p>
                <?php endif; ?>
            </div>
        </div>
        <?php

        echo $args['after_widget'];
    }

    public function form( $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : '';
        $desc  = ! empty( $instance['desc'] ) ? $instance['desc'] : '';
        $image = ! empty( $instance['image'] ) ? $instance['image'] : '';
        ?>
        <p>
            <label><?php _e( 'Title:', 'howcan' ); ?></label>
            <input class="widefat" name="<?php echo $this->get_field_name( 'title'); ?>" type="text" value="<?php
             if($title){
               
            echo esc_attr( $title );
             }else{
          $btitle =  bloginfo('title');
            echo esc_attr( $btitle );
             }
            
            ?>">
        </p>
        <p>
            <label><?php _e( 'Description:', 'howcan' ); ?></label>
            <textarea class="widefat" name="<?php echo $this->get_field_name( 'desc' ); ?>"><?php echo esc_textarea( $desc ); ?></textarea>
        </p>
        <p>
            <label><?php _e( 'Image URL:', 'howcan' ); ?></label>
            <input class="widefat" name="<?php echo $this->get_field_name( 'image' ); ?>" type="text" value="<?php echo esc_url( $image ); ?>">
        </p>
        <?php
    }

    public function update( $new_instance, $old_instance ) {
        $instance = [];
        $instance['title'] = sanitize_text_field( $new_instance['title'] );
        $instance['desc']  = sanitize_textarea_field( $new_instance['desc'] );
        $instance['image'] = esc_url_raw( $new_instance['image'] );
        return $instance;
    }
}


// register custom footer 
function howcan_register_custom_footer_widget() {
    register_widget( 'Howcan_Footer_Info_Widget' );
}
add_action( 'widgets_init', 'howcan_register_custom_footer_widget' );


// Custom Sidebar (Footer Info)
function howcan_footer_info_sidebar() {
    register_sidebar( array(
        'id'            => 'footer-info',
        'name'          => __( 'Footer Info Widget Area', 'howcan' ),
        'description'   => __( 'Displays the Howcan Footer Info Widget.', 'howcan' ),
        'before_widget' => '<div id="%1$s" class="widget %2$s mb-4"><b>',
        'after_widget'  => '</b></div>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ) );
}
add_action( 'widgets_init', 'howcan_footer_info_sidebar' );



// ===============
// csv  Export Function
// ===============
function howcan_export_customizer_settings() {
    if (isset($_POST['howcan_export_settings']) && check_admin_referer('howcan_export_nonce')) {
        if (!current_user_can('manage_options')) {
            return;
        }

        $mods = get_theme_mods();
        if ($mods) {
            $json = json_encode($mods);
            header('Content-disposition: attachment; filename=howcan-customizer-settings.json');
            header('Content-Type: application/json');
            echo $json;
            exit;
        }
    }
}
add_action('admin_init', 'howcan_export_customizer_settings');

// ===============
// csv Import Function
// ===============
function howcan_import_customizer_settings() {
    if (isset($_POST['howcan_import_settings']) && check_admin_referer('howcan_import_nonce')) {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (!empty($_FILES['howcan_import_file']['tmp_name'])) {
            $json = file_get_contents($_FILES['howcan_import_file']['tmp_name']);
            $mods = json_decode($json, true);

            if (is_array($mods)) {
                foreach ($mods as $key => $value) {
                    set_theme_mod($key, $value);
                }
                wp_safe_redirect(admin_url('themes.php?page=howcan-export-import&imported=true'));
                exit;
            }
        }
    }
}
add_action('admin_init', 'howcan_import_customizer_settings');

// ===============
// Admin Page UI (Card style)
// ===============
function howcan_export_import_page() {
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('Customizer Export/Import', 'howcan'); ?></h1>
        
        <div style="display:flex;gap:20px;flex-wrap:wrap;max-width:900px;">

            <!-- Export Card -->
            <div style="flex:1;min-width:300px;background:#fff;border:1px solid #ccd0d4;border-radius:8px;padding:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);">
                <h2 style="margin-top:0;"><?php esc_html_e('Export Settings', 'howcan'); ?></h2>
                <p><?php esc_html_e('Download your theme’s Customizer settings as a .json file.', 'howcan'); ?></p>
                <form method="post">
                    <?php wp_nonce_field('howcan_export_nonce'); ?>
                    <input type="hidden" name="howcan_export_settings" value="1">
                    <p>
                        <button class="button button-primary">
                            <?php esc_html_e('Download Export File', 'howcan'); ?>
                        </button>
                    </p>
                </form>
            </div>

            <!-- Import Card -->
            <div style="flex:1;min-width:300px;background:#fff;border:1px solid #ccd0d4;border-radius:8px;padding:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);">
                <h2 style="margin-top:0;"><?php esc_html_e('Import Settings', 'howcan'); ?></h2>
                <p><?php esc_html_e('Upload a .json file to restore your theme’s Customizer settings.', 'howcan'); ?></p>
                
                <?php if (isset($_GET['imported'])): ?>
                    <div class="notice notice-success is-dismissible">
                        <p><?php esc_html_e('Customizer settings imported successfully!', 'howcan'); ?></p>
                    </div>
                <?php endif; ?>

                <form method="post" enctype="multipart/form-data">
                    <?php wp_nonce_field('howcan_import_nonce'); ?>
                    <input type="hidden" name="howcan_import_settings" value="1">
                    <input type="file" name="howcan_import_file" accept=".json" required>
                    <p style="margin-top:10px;">
                        <button class="button button-primary">
                            <?php esc_html_e('Import Settings', 'howcan'); ?>
                        </button>
                    </p>
                </form>
            </div>

        </div>
    </div>
    <?php
}
add_action('admin_menu', function() {
    add_theme_page(
        __('Customizer Export/Import', 'howcan'),
        __('Customizer Export/Import', 'howcan'),
        'manage_options',
        'howcan-export-import',
        'howcan_export_import_page'
    );
});



// ================================
// HowCan Theme Functions
// after setup theme 
// ================================

function howcan_theme_setup() {

// functions.php

    // Load language files
    load_theme_textdomain('howcan', get_template_directory() . '/languages');

    require get_template_directory() . '/inc/block-pattern.php';
    require get_template_directory() . '/inc/enque-style.php';
    require get_template_directory() . '/inc/widgets.php';
    require get_template_directory() . '/inc/admin-notice.php';
    require get_template_directory() . '/inc/theme-options/free-options.php';
   
    require get_template_directory() . '/inc/comments-styleing.php';
     
// tgmpa 
require_once get_template_directory() . '/inc/class-tgm-plugin-activation.php';

//subscriber 
require_once get_template_directory() . '/inc/subcriber.php';

    // Theme Supports
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-logo',array(
        'default-image'      => get_template_directory_uri() . '/assets/images/logo.png',
      ));
    add_theme_support('custom-background');
    add_theme_support('automatic-feed-links');
    add_theme_support('html5', ['comment-form', 'comment-list', 'gallery', 'caption']);
    add_theme_support('align-wide');
    add_theme_support('responsive-embeds');
    add_theme_support('custom-line-height');
    add_theme_support('custom-spacing');
    add_theme_support('editor-styles');
    add_editor_style('assets/css/editor-style.css');
    add_theme_support('wp-block-styles');

    add_theme_support('custom-header', array(
        'width' => 1600,
        'height' => 100,
        'flex-width' => true,
        'flex-height' => true,
        'header-text' => false,
         'default-image'      => get_template_directory_uri() . '/assets/images/header.jpg',
    ));
    
     // WooCommerce support
    add_theme_support( 'woocommerce' );
    add_theme_support( 'wc-product-gallery-zoom' );
    add_theme_support( 'wc-product-gallery-lightbox' );
    add_theme_support( 'wc-product-gallery-slider' );
    

    // Add support for Elementor
    add_theme_support('elementor');

    // Register Navigation Menus
    register_nav_menus([
        'primary' => __('Primary Menu', 'howcan'),
        'top-menu' => __('Top Menu', 'howcan'),
        'social-menu' => __('Social Menu', 'howcan'),
    ]);
}
add_action('after_setup_theme', 'howcan_theme_setup');


// mail 
add_filter('wp_mail_content_type', function() {
    return 'text/html';
});
// ✅ Preconnect and preload fonts
function howcan_preload_fonts_header() {
    echo '<link rel="preconnect" href="https://fonts.googleapis.com">';
    echo '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
    echo '<link rel="preload" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" as="style">';
    echo '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap">';
}
add_action('wp_head', 'howcan_preload_fonts_header', 5);


// ✅ Defer JS (except jQuery)
function howcan_defer_scripts( $tag, $handle, $src ) {
    if ( is_admin() ) return $tag;
    if ( strpos( $handle, 'jquery' ) !== false ) return $tag;
    return '<script src="' . $src . '" defer></script>';
}
add_filter( 'script_loader_tag', 'howcan_defer_scripts', 10, 3 );


// ✅ Defer main stylesheet
function howcan_defer_main_css() {
    $style_uri = get_stylesheet_uri();
    echo '<link rel="stylesheet" href="' . esc_url( $style_uri ) . '" media="print" onload="this.media=\'all\'">';
    echo '<noscript><link rel="stylesheet" href="' . esc_url( $style_uri ) . '"></noscript>';
}
add_action('wp_head', 'howcan_defer_main_css', 20);


//post view count incriment
function howcan_track_post_views() {
    if ( is_single() && get_theme_mod( 'howcan_enable_post_views', true ) ) {
        global $post;
        if ( $post ) {
            howcan_set_post_views( $post->ID );
        }
    }
}
add_action( 'wp_head', 'howcan_track_post_views', 5 );

//post view set 
function howcan_set_post_views( $postID ) {
    if ( ! is_singular( 'post' ) ) {
        return;
    }

    $count_key = 'howcan_post_views_count';
    $count = get_post_meta( $postID, $count_key, true );

    if ( ! is_numeric( $count ) ) {
        $count = 1;
        update_post_meta( $postID, $count_key, $count );
    } else {
        $count++;
        update_post_meta( $postID, $count_key, $count );
    }
}
// view count 
function howcan_get_post_views( $postID ) {
    $count_key = 'howcan_post_views_count';
    $count = get_post_meta( $postID, $count_key, true );

    if ( ! is_numeric( $count ) ) {
        $count = 0;
    }

    return sprintf( _n( '%s view', '%s views', $count, 'howcan' ), $count );
}
  