<?php
/**
 * =========================================================
 * GREEN VIỆT - FUNCTIONS.PHP TỐI ƯU 2026
 * WordPress + WooCommerce + Flatsome
 * =========================================================
 */

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

/**
 * =========================================================
 * REGISTER SIDEBAR
 * =========================================================
 */
function greenviet_register_sidebars() {

    $sidebars = array(

        array(
            'name' => 'Sidebar Shop 2',
            'id'   => 'sidebar-shop-2',
            'desc' => 'Sidebar danh mục shop'
        ),

        array(
            'name' => 'Sidebar Product 2',
            'id'   => 'sidebar-product-2',
            'desc' => 'Sidebar sản phẩm'
        )

    );

    foreach ($sidebars as $sidebar) {

        register_sidebar(array(
            'name'          => $sidebar['name'],
            'id'            => $sidebar['id'],
            'description'   => $sidebar['desc'],
            'before_widget' => '<aside id="%1$s" class="widget %2$s">',
            'after_widget'  => '</aside>',
            'before_title'  => '<span class="widget-title">',
            'after_title'   => '</span>',
        ));

    }
}
add_action('widgets_init', 'greenviet_register_sidebars');


/**
 * =========================================================
 * WOOCOMMERCE PRODUCT TAB
 * =========================================================
 */
function greenviet_product_tabs($tabs) {

    unset($tabs['additional_information']);
    unset($tabs['reviews']);

    if (isset($tabs['description'])) {
        $tabs['description']['title'] = 'Thông tin chi tiết sản phẩm';
    }

    return $tabs;

}
add_filter('woocommerce_product_tabs', 'greenviet_product_tabs', 98);


/**
 * =========================================================
 * REVIEW XUỐNG DƯỚI
 * =========================================================
 */
function greenviet_product_reviews() {

    if (!comments_open()) {
        return;
    }

    global $product;

    if (!$product) {
        return;
    }

    ?>
    <div class="product-reviews">

        <h2 class="review-title">
            <?php echo sprintf('Đánh giá (%d)', $product->get_review_count()); ?>
        </h2>

        <?php comments_template(); ?>

    </div>

    <div class="clearfix"></div>
    <?php
}
add_action('woocommerce_after_single_product_summary', 'greenviet_product_reviews', 15);


/**
 * =========================================================
 * ẨN VERSION WORDPRESS
 * =========================================================
 */
add_filter('the_generator', '__return_empty_string');


/**
 * =========================================================
 * ADMIN FOOTER
 * =========================================================
 */
function greenviet_admin_footer() {

    echo 'Thiết kế bởi 
    <a href="https://tapdoannangluongxanh.vn" target="_blank" rel="noopener">
    Green Việt
    </a>';

}
add_filter('admin_footer_text', 'greenviet_admin_footer');


/**
 * =========================================================
 * ẨN NOTICE ADMIN
 * =========================================================
 */
function greenviet_admin_css() {
?>
<style>

#flatsome-notice,
.notice.notice-warning,
.update-nag,
.woocommerce-layout__header,
.woocommerce-layout__activity-panel-tabs,
.woocommerce-layout__header-breadcrumbs {
    display: none !important;
}

</style>
<?php
}
add_action('admin_head', 'greenviet_admin_css');


/**
 * =========================================================
 * XÓA LOGO WORDPRESS
 * =========================================================
 */
function greenviet_remove_wp_logo($wp_admin_bar) {
    $wp_admin_bar->remove_node('wp-logo');
}
add_action('admin_bar_menu', 'greenviet_remove_wp_logo', 999);


/**
 * =========================================================
 * CONTACT FORM 7
 * =========================================================
 */
add_filter('wpcf7_load_js', '__return_false');
add_filter('wpcf7_load_css', '__return_false');

function greenviet_cf7_assets() {

    if (!is_singular()) {
        return;
    }

    global $post;

    if (
        isset($post->post_content) &&
        has_shortcode($post->post_content, 'contact-form-7')
    ) {

        if (function_exists('wpcf7_enqueue_scripts')) {
            wpcf7_enqueue_scripts();
        }

        if (function_exists('wpcf7_enqueue_styles')) {
            wpcf7_enqueue_styles();
        }

    }
}
add_action('wp', 'greenviet_cf7_assets');


/**
 * =========================================================
 * LOGIN URL
 * =========================================================
 */
function greenviet_login_logo_url() {
    return home_url('/');
}
add_filter('login_headerurl', 'greenviet_login_logo_url');


/**
 * =========================================================
 * CLASSIC EDITOR
 * =========================================================
 */
add_filter('use_block_editor_for_post', '__return_false');
add_filter('use_widgets_block_editor', '__return_false');


/**
 * =========================================================
 * SHORTCODE SITE TITLE
 * =========================================================
 */
function greenviet_site_title_shortcode() {
    return esc_html(get_bloginfo('name'));
}
add_shortcode('site_title', 'greenviet_site_title_shortcode');


/**
 * =========================================================
 * VALIDATE PHONE VIỆT NAM
 * =========================================================
 */
function greenviet_validate_phone($result, $tel) {

    $tel = preg_replace('/[^0-9+]/', '', $tel);

    if (preg_match('/^(0|\+84)[0-9]{9,10}$/', $tel)) {
        return true;
    }

    return false;

}
add_filter('wpcf7_validate_tel*', 'greenviet_validate_phone', 10, 2);

function greenviet_validate_phone($result, $tag) {

    $name = $tag->name;

    if (isset($_POST[$name])) {

        $tel = sanitize_text_field($_POST[$name]);
        $tel = preg_replace('/[^0-9+]/', '', $tel);

        if (!preg_match('/^(0|\+84)[0-9]{9,10}$/', $tel)) {
            $result->invalidate($tag, 'Số điện thoại không hợp lệ');
        }

    }

    return $result;
}


/**
 * =========================================================
 * EMAIL ORDER SHOW IMAGE
 * =========================================================
 */
function greenviet_wc_email_items($args) {

    $args['show_image'] = true;
    $args['show_sku']   = true;

    return $args;

}
add_filter('woocommerce_email_order_items_args', 'greenviet_wc_email_items');


/**
 * =========================================================
 * CHECKOUT PAGE
 * =========================================================
 */
function greenviet_checkout_fields($fields) {

    unset($fields['billing']['billing_company']);
    unset($fields['billing']['billing_address_2']);
    unset($fields['billing']['billing_last_name']);

    $fields['billing']['billing_first_name']['placeholder'] = 'Họ và tên';
    $fields['billing']['billing_phone']['placeholder']      = 'Số điện thoại';

    return $fields;

}
add_filter('woocommerce_checkout_fields', 'greenviet_checkout_fields');


/**
 * =========================================================
 * OPTIONAL FIELD CHECKOUT
 * =========================================================
 */
function greenviet_optional_fields($fields) {

    if (!is_checkout()) {
        return $fields;
    }

    $optional_fields = array(
        'billing_email',
        'billing_company',
        'billing_city',
        'billing_address_2',
        'billing_state',
        'billing_postcode',
        'billing_last_name'
    );

    foreach ($optional_fields as $field) {

        if (isset($fields[$field])) {
            $fields[$field]['required'] = false;
        }

    }

    return $fields;

}
add_filter('woocommerce_billing_fields', 'greenviet_optional_fields', 20);


/**
 * =========================================================
 * GIÁ 0Đ => LIÊN HỆ
 * =========================================================
 */
function greenviet_price_html($price, $product) {

    if ((float)$product->get_price() <= 0) {
        return '<span class="amount">Liên hệ</span>';
    }

    return $price;

}
add_filter('woocommerce_get_price_html', 'greenviet_price_html', 10, 2);


/**
 * =========================================================
 * THÊM ẢNH CHECKOUT
 * =========================================================
 */
function greenviet_checkout_product_image($name, $cart_item) {

    if (!is_checkout()) {
        return $name;
    }

    $product = $cart_item['data'];

    if (!$product) {
        return $name;
    }

    return '
    <div class="ts-product-image">
        ' . $product->get_image(array(60,60)) . '
    </div>
    ' . $name;

}
add_filter('woocommerce_cart_item_name', 'greenviet_checkout_product_image', 10, 2);


/**
 * =========================================================
 * TẮT SRCSET
 * =========================================================
 */
add_filter('wp_calculate_image_srcset', '__return_false');


/**
 * =========================================================
 * TỐI ƯU ADMIN
 * =========================================================
 */
function greenviet_remove_metaboxes() {
    remove_meta_box('postcustom', 'product', 'normal');
}
add_action('add_meta_boxes', 'greenviet_remove_metaboxes', 50);


/**
 * =========================================================
 * CANONICAL PAGINATION
 * =========================================================
 */
function greenviet_rankmath_canonical($canonical) {

    if (is_paged()) {

        $link = home_url(add_query_arg(array(), $_SERVER['REQUEST_URI']));
        $arr  = explode('/page/', $link);

        return trailingslashit($arr[0]);

    }

    return $canonical;

}
add_filter('rank_math/frontend/canonical', 'greenviet_rankmath_canonical');


/**
 * =========================================================
 * BREADCRUMB BLOG
 * =========================================================
 */
function greenviet_blog_breadcrumb() {

    if (!function_exists('rank_math_the_breadcrumbs')) {
        return;
    }

?>
<div class="row">
    <div class="col large-12">
        <?php rank_math_the_breadcrumbs(); ?>
    </div>
</div>
<?php

}
add_action('flatsome_before_blog', 'greenviet_blog_breadcrumb');


/**
 * =========================================================
 * RELATED PRODUCT TEXT
 * =========================================================
 */
function greenviet_related_text($translated, $text, $domain) {

    if ($text === 'Related products' && $domain === 'woocommerce') {
        return 'Sản phẩm tương tự';
    }

    return $translated;

}
add_filter('gettext', 'greenviet_related_text', 10, 3);


/**
 * =========================================================
 * SECURITY HEADER
 * =========================================================
 */
function greenviet_security_headers() {

    if (!is_admin()) {

        header('X-Frame-Options: SAMEORIGIN');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: strict-origin-when-cross-origin');

    }

}
add_action('send_headers', 'greenviet_security_headers');


/**
 * =========================================================
 * DISABLE XML-RPC
 * =========================================================
 */
add_filter('xmlrpc_enabled', '__return_false');


/**
 * =========================================================
 * REMOVE EMOJI
 * =========================================================
 */
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');


/**
 * =========================================================
 * REMOVE META WORDPRESS
 * =========================================================
 */
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_shortlink_wp_head');
remove_action('wp_head', 'rest_output_link_wp_head');


