<?php
/**
 * storeethan functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package storeethan
 */

if ( ! defined( '_S_VERSION' ) ) {
	// Replace the version number of the theme on each release.
	define( '_S_VERSION', '1.0.0' );
}

if ( ! defined( 'STORE_THEME_URL' ) ) {
    // Replace the version number of the theme on each release.
    define( 'STORE_THEME_URL', get_template_directory_uri() );
    define( 'STORE_ASSETS_URL', STORE_THEME_URL . '/assets/' );
}

if ( ! defined( 'STORE_THEME_PATH' ) ) {
    // Replace the version number of the theme on each release.
    define( 'STORE_THEME_PATH', get_template_directory() );
}

/**
 * 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 storeethan_setup() {
	/*
		* Make theme available for translation.
		* Translations can be filed in the /languages/ directory.
		* If you're building a theme based on storeethan, use a find and replace
		* to change 'storeethan' to the name of your theme in all the template files.
		*/
	load_theme_textdomain( 'storeethan', get_template_directory() . '/languages' );

	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );

	/*
		* 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(
			'menu-1' => esc_html__( 'Primary', 'storeethan' ),
		)
	);

	/*
		* 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(
			'storeethan_custom_background_args',
			array(
				'default-color' => 'ffffff',
				'default-image' => '',
			)
		)
	);

	// Add theme support for selective refresh for widgets.
	add_theme_support( 'customize-selective-refresh-widgets' );
    add_theme_support('custom-header');

	/**
	 * 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_action( 'after_setup_theme', 'storeethan_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 storeethan_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'storeethan_content_width', 640 );
}
add_action( 'after_setup_theme', 'storeethan_content_width', 0 );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function storeethan_widgets_init() {
	register_sidebar(
		array(
			'name'          => esc_html__( 'Sidebar', 'storeethan' ),
			'id'            => 'sidebar-1',
			'description'   => esc_html__( 'Add widgets here.', 'storeethan' ),
			'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', 'storeethan_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function storeethan_scripts() {
	wp_enqueue_style( 'storeethan-style', get_stylesheet_uri(), array(), _S_VERSION );
	wp_style_add_data( 'storeethan-style', 'rtl', 'replace' );

	wp_enqueue_script( 'storeethan-navigation', get_template_directory_uri() . '/js/navigation.js', array(), _S_VERSION, true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'storeethan_scripts' );

/**
 * 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';
require get_template_directory() . '/inc/class-util.php';

require get_template_directory() . '/inc/store.class.php';

function my_schedule_midnight_cron() {
    if ( ! wp_next_scheduled( 'my_midnight_event' ) ) {
        // Set thời gian khởi đầu từ 0h đêm hôm nay
        $start_time = strtotime( '06:00:00' );
        wp_schedule_event( time(), 'daily', 'my_midnight_event' );
    }
}
add_action( 'wp', 'my_schedule_midnight_cron' );
add_action( 'my_midnight_event', 'my_daily_task' );
// add_action( 'init', 'my_daily_task' );
function my_daily_task(){
    $store = new StoreEthan();
    $store->init_hoook();
}

function my_remove_cron_on_theme_deactivation() {
    $timestamp = wp_next_scheduled( 'my_midnight_event' );
    if ( $timestamp ) {
        wp_unschedule_event( $timestamp, 'my_midnight_event' );
    }
    
}
add_action( 'switch_theme', 'my_remove_cron_on_theme_deactivation' );

remove_action( 'woocommerce_before_single_product', 'woocommerce_output_all_notices', 10 );
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );
remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50 );
add_filter('woocommerce_gallery_image_size' , function (){
    return 'full';
});

add_filter('woocommerce_gallery_thumbnail_size' , function (){
    return array(600 , 600);
});

add_filter('woocommerce_product_related_products_heading' , 'ethan_product_related_products_heading');

function ethan_product_related_products_heading()
{
    return __('Các sản phẩm liên quan', 'storeethan');
}

function is_dark_mode()
{
    $category_id = 18;
    $is_dark = false;
    if(is_product_category()){
        $cate = get_queried_object();
        if($cate->term_id == $category_id){
            $is_dark = true;
        }
    }
    if(is_product()){
        $product = wc_get_product(get_the_ID());
        $ids = $product->get_category_ids();
        if(array_search($category_id, $ids) !== false){
            $is_dark = true;
        }
    }
    return $is_dark;
}

function convert_url_to_path($url) {
    // Lấy URL và đường dẫn của thư mục uploads
    $upload_dir = wp_upload_dir();

    // Kiểm tra nếu URL bắt đầu bằng URL của thư mục uploads
    if (strpos($url, $upload_dir['baseurl']) !== false) {
        // Chuyển đổi URL thành đường dẫn file
        $path = str_replace($upload_dir['baseurl'], $upload_dir['basedir'], $url);
        return $path;
    } else {
        // Nếu URL không thuộc thư mục uploads, trả về lỗi hoặc xử lý khác
        return 'Error: URL is not part of the uploads directory.';
    }
}


add_filter( 'body_class', 'ethan_custom_body_class', 10, 2 );
function ethan_custom_body_class($classes, $css_class)
{

    if(is_dark_mode()){
        $classes[] = 'dark';
    }
    return $classes;
}


add_filter('woocommerce_checkout_fields', 'remove_billing_name_fields_checkout');
function remove_billing_name_fields_checkout($fields) {

    unset($fields['billing']['billing_first_name']);
    unset($fields['billing']['billing_last_name']);
    unset($fields['billing']['billing_company']);
    unset($fields['billing']['billing_country']);
    unset($fields['billing']['billing_address_1']);
    unset($fields['billing']['billing_address_2']);
    unset($fields['billing']['billing_postcode']);
    unset($fields['billing']['billing_city']);

    return $fields;
}

add_action('woocommerce_checkout_fields', 'add_billing_full_name_field_checkout',99);
function add_billing_full_name_field_checkout($fields) {
    $fields['billing']['billing_full_name'] = array(
        'label'       => __('Họ và Tên', 'woocommerce'),
        'placeholder' => _x('Vui lòng điền họ và tên...', 'placeholder', 'woocommerce'),
        'required'    => true,
        'class'       => array('form-row-wide'),
        'clear'       => true,
        'priority'    => 1
    );

    $fields['billing']['billing_address_ct'] = array(
        'label'       => __('Địa chỉ nhận hàng', 'woocommerce'),
        'placeholder' => _x('Vui lòng điền địa chỉ nhận hàng...', 'placeholder', 'woocommerce'),
        'required'    => true,
        'class'       => array('form-row-wide'),
        'clear'       => true
    );

    $fields['billing']['billing_message_ct'] = array(
        'type'        => 'textarea',
        'label'       => __('Lời nhắn', 'woocommerce'),
        'placeholder' => _x('Để lại lời nhắn cho chúng tôi...', 'placeholder', 'woocommerce'),
        'required'    => false,
        'class'       => array('form-row-wide'),
        'clear'       => true
    );

    $fields['billing']['billing_email']['label']       = __('Email', 'woocommerce');
    $fields['billing']['billing_email']['placeholder'] = _x('Vui lòng điền địa chỉ email...', 'placeholder', 'woocommerce');

    $fields['billing']['billing_phone']['label']       = __('Số điện thoại liên hệ', 'woocommerce');
    $fields['billing']['billing_phone']['placeholder'] = _x('Vui lòng điền số điện thoại...', 'placeholder', 'woocommerce');

    return $fields;
}

add_action('woocommerce_checkout_update_order_meta', 'save_billing_full_name_field_checkout');
function save_billing_full_name_field_checkout($order_id) {
    if (!empty($_POST['billing_full_name'])) {
        update_post_meta($order_id, '_billing_full_name', sanitize_text_field($_POST['billing_full_name']));
    }

    if (!empty($_POST['billing_address_ct'])) {
        update_post_meta($order_id, '_billing_address_ct', sanitize_text_field($_POST['billing_address_ct']));
    }

    if (!empty($_POST['billing_message_ct'])) {
        update_post_meta($order_id, '_billing_message_ct', sanitize_text_field($_POST['billing_message_ct']));
    }
}


add_action('woocommerce_admin_order_data_after_billing_address', 'display_billing_full_name_in_admin_order_co', 10, 1);
function display_billing_full_name_in_admin_order_co($order){
    $full_name = get_post_meta($order->get_id(), '_billing_full_name', true);
    $address = get_post_meta($order->get_id(), '_billing_address_ct', true);
    $message = get_post_meta($order->get_id(), '_billing_message_ct', true);
    if ($full_name) {
        echo '<p><strong>' . __('Full Name', 'woocommerce') . ':</strong> ' . esc_html($full_name) . '</p>';
    }
    if ($address) {
        echo '<p><strong>' . __('Address', 'woocommerce') . ':</strong> ' . esc_html($address) . '</p>';
    }
    if ($message) {
        echo '<p><strong>' . __('Message', 'woocommerce') . ':</strong> ' . esc_html($message) . '</p>';
    }
}

add_action('wp_ajax_clear_cart', 'clear_mini_cart');
add_action('wp_ajax_nopriv_clear_cart', 'clear_mini_cart');

function clear_cart() {
    WC()->cart->empty_cart();
    wp_send_json_success();
}


function update_cart_fragments( $fragments ) {
    ob_start();
    ?>
    <div class="minicart_items">
        <?php
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
            $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
            $product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key );
            $brands = wp_get_post_terms( $_product->get_id(), 'pwb-brand' );
            $_brand = '';
            if ( !empty($brands) && !is_wp_error($brands) ) {
                foreach ( $brands as $brand ) {
                    $_brand .= $_brand == '' ? $brand->name : ', ' . $brand->name;
                }
            }
            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
                ?>
                <div class="container-fluid container-cart_checkout">
                    <div class="row">
                        <div class="col-lg-8 col-md-8 col-12 left-cart">
                        <span class="product-remove">
                            <?php
                            echo apply_filters(
                                'woocommerce_cart_item_remove_link',
                                sprintf(
                                    '<a href="%s" class="remove-mini_cart" data-cartkey=' .$cart_item_key. ' aria-label="%s" data-product_id="%s" data-product_sku="%s"></a>',
                                    esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
                                    esc_attr( sprintf( __( 'Remove %s from cart', 'woocommerce' ), wp_strip_all_tags( $product_name ) ) ),
                                    esc_attr( $product_id ),
                                    esc_attr( $_product->get_sku() )
                                ),
                                $cart_item_key
                            );
                            ?>
                        </span>
                            <div class="product-thumbnail">
                                <?php
                                $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                                if ( ! $product_permalink ) {
                                    echo $thumbnail;
                                } else {
                                    printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); // PHPCS: XSS ok.
                                }
                                ?>
                            </div>
                            <div class="product-name">
                                <div>
                                    <div class="before_brand">
                                        <?php echo $_product->get_sku(); ?>
                                    </div>
                                    <div class="brands">
                                        <?php echo $_brand; ?>
                                    </div>
                                    <?php
                                    if ( ! $product_permalink ) {
                                        echo wp_kses_post( $product_name . '&nbsp;' );
                                    } else {
                                        echo wp_kses_post( apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key ) );
                                    }

                                    do_action( 'woocommerce_after_cart_item_name', $cart_item, $cart_item_key );

                                    echo wc_get_formatted_cart_item_data( $cart_item );

                                    if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
                                        echo wp_kses_post( apply_filters( 'woocommerce_cart_item_backorder_notification', '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'woocommerce' ) . '</p>', $product_id ) );
                                    }
                                    ?>

                                </div>
                            </div>

                        </div>
                        <div class="col-12 col-md-4 col-lg-4 right-cart">
                            <div class="product-quantity">
                            <span class="tru" key="<?php echo $cart_item_key; ?>">
                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                    <path fill-rule="evenodd" clip-rule="evenodd" d="M2.66602 8C2.66602 7.63181 2.96449 7.33333 3.33268 7.33333H12.666C13.0342 7.33333 13.3327 7.63181 13.3327 8C13.3327 8.36819 13.0342 8.66667 12.666 8.66667H3.33268C2.96449 8.66667 2.66602 8.36819 2.66602 8Z" fill="#111111"/>
                                </svg>
                            </span>
                                <?php
                                if ( $_product->is_sold_individually() ) {
                                    $min_quantity = 1;
                                    $max_quantity = 1;
                                } else {
                                    $min_quantity = 0;
                                    $max_quantity = $_product->get_max_purchase_quantity();
                                }

                                $product_quantity = woocommerce_quantity_input(
                                    array(
                                        'input_name'   => "cart[{$cart_item_key}][qty]",
                                        'input_value'  => $cart_item['quantity'],
                                        'classes'      => array( 'input-text', 'qty', 'text', 'inp_'.$cart_item_key ),
                                        'max_value'    => $max_quantity,
                                        'key'          => $cart_item_key,
                                        'min_value'    => $min_quantity,
                                        'product_name' => $product_name,
                                    ),
                                    $_product,
                                    false
                                );

                                echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
                                ?>
                                <span class="plus" key="<?php echo $cart_item_key; ?>">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path fill-rule="evenodd" clip-rule="evenodd" d="M8.00065 2.66667C8.36884 2.66667 8.66732 2.96514 8.66732 3.33333V12.6667C8.66732 13.0349 8.36884 13.3333 8.00065 13.3333C7.63246 13.3333 7.33398 13.0349 7.33398 12.6667V3.33333C7.33398 2.96514 7.63246 2.66667 8.00065 2.66667Z" fill="#111111"/>
                                        <path fill-rule="evenodd" clip-rule="evenodd" d="M2.66602 8C2.66602 7.63181 2.96449 7.33333 3.33268 7.33333H12.666C13.0342 7.33333 13.3327 7.63181 13.3327 8C13.3327 8.36819 13.0342 8.66667 12.666 8.66667H3.33268C2.96449 8.66667 2.66602 8.36819 2.66602 8Z" fill="#111111"/>
                                    </svg>
                                </span>
                            </div>
                            <div class="product-price">
                                <?php
                                echo WC()->cart->get_product_price( $_product );
                                ?>
                            </div>
                        </div>
                    </div>
                </div>

            <?php }} ?>
        </div>
    <?php
    $fragments['div.mini_cart_vn'] = ob_get_clean();
    ob_start();
    ?>
        <div class="modal-cart-footer">
            <div class="product-subtotal">
                <span>Tổng <?php echo WC()->cart->get_cart_contents_count(); ?> sản phẩm</span>
                <p>
                    <?php
                    echo wc_cart_totals_order_total_html();
                    ?>
                </p>
            </div>
            <div class="go_checkout">
                <a class="btn btn_submit" href="<?php echo wc_get_checkout_url(); ?>"><?php _e('Tiến hành đặt hàng') ?></a>
            </div>
        </div>
    <?php
    $fragments['cart_footer'] = ob_get_clean();
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'update_cart_fragments' );


function ajax_remove_mini_cart_item() {

    if ( ! isset( $_POST['cart_item_key'] ) ) {
        wp_send_json_error( array( 'message' => 'Invalid request' ) );
    }

    $cart_item_key = sanitize_text_field( $_POST['cart_item_key'] );
    WC()->cart->remove_cart_item( $cart_item_key );

    ob_start();
    $empty = false;
    if(WC()->cart->is_empty()) {
        $empty = true;
        ?> <p class="cart-item_empty">Chưa có sản phẩm nào trong giỏ hàng</p> <?php
    } else {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
            $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
            $product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key );
            $brands = wp_get_post_terms( $_product->get_id(), 'pwb-brand' );
            $_brand = '';
            if ( !empty($brands) && !is_wp_error($brands) ) {
                foreach ( $brands as $brand ) {
                    $_brand .= $_brand == '' ? $brand->name : ', ' . $brand->name;
                }
            }
            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
                ?>
                <div class="container-fluid container-cart_checkout">
                    <div class="row">
                        <div class="col-lg-8 col-md-8 col-12 left-cart">
                    <span class="product-remove">
                        <?php
                        echo apply_filters(
                            'woocommerce_cart_item_remove_link',
                            sprintf(
                                '<a href="%s" class="remove-mini_cart" data-cartkey=' .$cart_item_key. ' aria-label="%s" data-product_id="%s" data-product_sku="%s"></a>',
                                esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
                                esc_attr( sprintf( __( 'Remove %s from cart', 'woocommerce' ), wp_strip_all_tags( $product_name ) ) ),
                                esc_attr( $product_id ),
                                esc_attr( $_product->get_sku() )
                            ),
                            $cart_item_key
                        );
                        ?>
                    </span>
                            <div class="product-thumbnail">
                                <?php
                                $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                                if ( ! $product_permalink ) {
                                    echo $thumbnail;
                                } else {
                                    printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); // PHPCS: XSS ok.
                                }
                                ?>
                            </div>
                            <div class="product-name">
                                <div>
                                    <div class="before_brand">
                                        <?php echo $_product->get_sku(); ?>
                                    </div>
                                    <div class="brands">
                                        <?php echo $_brand; ?>
                                    </div>
                                    <?php
                                    if ( ! $product_permalink ) {
                                        echo wp_kses_post( $product_name . '&nbsp;' );
                                    } else {
                                        echo wp_kses_post( apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key ) );
                                    }

                                    do_action( 'woocommerce_after_cart_item_name', $cart_item, $cart_item_key );

                                    echo wc_get_formatted_cart_item_data( $cart_item );

                                    if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
                                        echo wp_kses_post( apply_filters( 'woocommerce_cart_item_backorder_notification', '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'woocommerce' ) . '</p>', $product_id ) );
                                    }
                                    ?>

                                </div>
                            </div>

                        </div>
                        <div class="col-12 col-md-4 col-lg-4 right-cart">
                            <div class="product-quantity">
                        <span class="tru" key="<?php echo $cart_item_key; ?>">
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path fill-rule="evenodd" clip-rule="evenodd" d="M2.66602 8C2.66602 7.63181 2.96449 7.33333 3.33268 7.33333H12.666C13.0342 7.33333 13.3327 7.63181 13.3327 8C13.3327 8.36819 13.0342 8.66667 12.666 8.66667H3.33268C2.96449 8.66667 2.66602 8.36819 2.66602 8Z" fill="#111111"/>
                            </svg>
                        </span>
                                <?php
                                if ( $_product->is_sold_individually() ) {
                                    $min_quantity = 1;
                                    $max_quantity = 1;
                                } else {
                                    $min_quantity = 0;
                                    $max_quantity = $_product->get_max_purchase_quantity();
                                }

                                $product_quantity = woocommerce_quantity_input(
                                    array(
                                        'input_name'   => "cart[{$cart_item_key}][qty]",
                                        'input_value'  => $cart_item['quantity'],
                                        'classes'      => array( 'input-text', 'qty', 'text', 'inp_'.$cart_item_key ),
                                        'max_value'    => $max_quantity,
                                        'min_value'    => $min_quantity,
                                        'key'          => $cart_item_key,
                                        'product_name' => $product_name,
                                    ),
                                    $_product,
                                    false
                                );

                                echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
                                ?>
                                <span class="plus" key="<?php echo $cart_item_key; ?>">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path fill-rule="evenodd" clip-rule="evenodd" d="M8.00065 2.66667C8.36884 2.66667 8.66732 2.96514 8.66732 3.33333V12.6667C8.66732 13.0349 8.36884 13.3333 8.00065 13.3333C7.63246 13.3333 7.33398 13.0349 7.33398 12.6667V3.33333C7.33398 2.96514 7.63246 2.66667 8.00065 2.66667Z" fill="#111111"/>
                                        <path fill-rule="evenodd" clip-rule="evenodd" d="M2.66602 8C2.66602 7.63181 2.96449 7.33333 3.33268 7.33333H12.666C13.0342 7.33333 13.3327 7.63181 13.3327 8C13.3327 8.36819 13.0342 8.66667 12.666 8.66667H3.33268C2.96449 8.66667 2.66602 8.36819 2.66602 8Z" fill="#111111"/>
                                    </svg>
                                </span>
                            </div>
                            <div class="product-price">
                                <?php
                                echo WC()->cart->get_product_price( $_product );
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php }}
        ?>
    <?php
    }

    $mini_cart = ob_get_clean();
    if(!WC()->cart->is_empty()) :
        ?>
        <div class="modal-cart-footer">
            <div class="product-subtotal">
                <span>Tổng <?php echo WC()->cart->get_cart_contents_count(); ?> sản phẩm</span>
                <p>
                    <?php
                    echo wc_cart_totals_order_total_html();
                    ?>
                </p>
            </div>
            <div class="go_checkout">
                <a class="btn btn_submit" href="<?php echo wc_get_checkout_url(); ?>"><?php _e('Tiến hành đặt hàng') ?></a>
            </div>
        </div>
    <?php
    endif;
    $cart_footer = ob_get_clean();
    wp_send_json_success( array(
        'mini_cart' => $mini_cart,
        'cart_footer' => $cart_footer,
        'redirect' => $empty ? home_url() : ''
    ) );
}
add_action( 'wp_ajax_remove_cart_item', 'ajax_remove_mini_cart_item' );
add_action( 'wp_ajax_nopriv_remove_cart_item', 'ajax_remove_mini_cart_item' );
add_action( 'wp_ajax_remove_cart_all_item', 'ajax_remove_cart' );
add_action( 'wp_ajax_nopriv_remove_cart_all_item', 'ajax_remove_cart' );
function ajax_remove_cart()
{
    WC()->cart->empty_cart();
    wp_send_json_success( array(
        'msg' => 'success'
    ) );
    wp_die();
}

add_action( 'wp_ajax_update_qty_cart_item', 'ajax_update_qty_cart_item' );
add_action( 'wp_ajax_nopriv_update_qty_cart_item', 'ajax_update_qty_cart_item' );

function ajax_update_qty_cart_item()
{
    if ( ! isset( $_POST['cart_item_key'] ) ) {
        wp_send_json_error( array( 'message' => 'Invalid request' ) );
    }

    $cart_item_key = sanitize_text_field( $_POST['cart_item_key'] );
    $new_quantity = abs( $_POST['quantity'] );
    WC()->cart->set_quantity( $cart_item_key, $new_quantity, true );
    ob_start();

        foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
            $_product   = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
            $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key );
            $product_name = apply_filters( 'woocommerce_cart_item_name', $_product->get_name(), $cart_item, $cart_item_key );
            $brands = wp_get_post_terms( $_product->get_id(), 'pwb-brand' );
            $_brand = '';
            if ( !empty($brands) && !is_wp_error($brands) ) {
                foreach ( $brands as $brand ) {
                    $_brand .= $_brand == '' ? $brand->name : ', ' . $brand->name;
                }
            }
            if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) {
                $product_permalink = apply_filters( 'woocommerce_cart_item_permalink', $_product->is_visible() ? $_product->get_permalink( $cart_item ) : '', $cart_item, $cart_item_key );
                ?>
                <div class="container-fluid container-cart_checkout">
                    <div class="row">
                        <div class="col-lg-8 col-md-8 col-12 left-cart">
                    <span class="product-remove">
                        <?php
                        echo apply_filters(
                            'woocommerce_cart_item_remove_link',
                            sprintf(
                                '<a href="%s" class="remove-mini_cart" data-cartkey=' .$cart_item_key. ' aria-label="%s" data-product_id="%s" data-product_sku="%s"></a>',
                                esc_url( wc_get_cart_remove_url( $cart_item_key ) ),
                                esc_attr( sprintf( __( 'Remove %s from cart', 'woocommerce' ), wp_strip_all_tags( $product_name ) ) ),
                                esc_attr( $product_id ),
                                esc_attr( $_product->get_sku() )
                            ),
                            $cart_item_key
                        );
                        ?>
                    </span>
                            <div class="product-thumbnail">
                                <?php
                                $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );

                                if ( ! $product_permalink ) {
                                    echo $thumbnail;
                                } else {
                                    printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); // PHPCS: XSS ok.
                                }
                                ?>
                            </div>
                            <div class="product-name">
                                <div>
                                    <div class="before_brand">
                                        <?php echo $_product->get_sku(); ?>
                                    </div>
                                    <div class="brands">
                                        <?php echo $_brand; ?>
                                    </div>
                                    <?php
                                    if ( ! $product_permalink ) {
                                        echo wp_kses_post( $product_name . '&nbsp;' );
                                    } else {
                                        echo wp_kses_post( apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $_product->get_name() ), $cart_item, $cart_item_key ) );
                                    }

                                    do_action( 'woocommerce_after_cart_item_name', $cart_item, $cart_item_key );

                                    echo wc_get_formatted_cart_item_data( $cart_item );

                                    if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) {
                                        echo wp_kses_post( apply_filters( 'woocommerce_cart_item_backorder_notification', '<p class="backorder_notification">' . esc_html__( 'Available on backorder', 'woocommerce' ) . '</p>', $product_id ) );
                                    }
                                    ?>

                                </div>
                            </div>

                        </div>
                        <div class="col-12 col-md-4 col-lg-4 right-cart">
                            <div class="product-quantity">
                        <span class="tru" key="<?php echo $cart_item_key; ?>">
                            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path fill-rule="evenodd" clip-rule="evenodd" d="M2.66602 8C2.66602 7.63181 2.96449 7.33333 3.33268 7.33333H12.666C13.0342 7.33333 13.3327 7.63181 13.3327 8C13.3327 8.36819 13.0342 8.66667 12.666 8.66667H3.33268C2.96449 8.66667 2.66602 8.36819 2.66602 8Z" fill="#111111"/>
                            </svg>
                        </span>
                                <?php
                                if ( $_product->is_sold_individually() ) {
                                    $min_quantity = 1;
                                    $max_quantity = 1;
                                } else {
                                    $min_quantity = 0;
                                    $max_quantity = $_product->get_max_purchase_quantity();
                                }

                                $product_quantity = woocommerce_quantity_input(
                                    array(
                                        'input_name'   => "cart[{$cart_item_key}][qty]",
                                        'classes'      => array( 'input-text', 'qty', 'text', 'inp_'.$cart_item_key ),
                                        'max_value'    => $max_quantity,
                                        'input_value'  => $cart_item['quantity'],
                                        'min_value'    => $min_quantity,
                                        'key'          => $cart_item_key,
                                        'product_name' => $product_name,
                                    ),
                                    $_product,
                                    false
                                );

                                echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key, $cart_item );
                                ?>
                                <span class="plus" key="<?php echo $cart_item_key; ?>">
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                        <path fill-rule="evenodd" clip-rule="evenodd" d="M8.00065 2.66667C8.36884 2.66667 8.66732 2.96514 8.66732 3.33333V12.6667C8.66732 13.0349 8.36884 13.3333 8.00065 13.3333C7.63246 13.3333 7.33398 13.0349 7.33398 12.6667V3.33333C7.33398 2.96514 7.63246 2.66667 8.00065 2.66667Z" fill="#111111"/>
                                        <path fill-rule="evenodd" clip-rule="evenodd" d="M2.66602 8C2.66602 7.63181 2.96449 7.33333 3.33268 7.33333H12.666C13.0342 7.33333 13.3327 7.63181 13.3327 8C13.3327 8.36819 13.0342 8.66667 12.666 8.66667H3.33268C2.96449 8.66667 2.66602 8.36819 2.66602 8Z" fill="#111111"/>
                                    </svg>
                                </span>
                            </div>
                            <div class="product-price">
                                <?php
                                echo WC()->cart->get_product_price( $_product );
                                ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php }
    }
    $mini_cart = ob_get_clean();
    ob_start();
    if(!WC()->cart->is_empty()) :
        ?>
        <div class="modal-cart-footer">
            <div class="product-subtotal">
                <span>Tổng <?php echo WC()->cart->get_cart_contents_count(); ?> sản phẩm</span>
                <p>
                    <?php
                    echo wc_cart_totals_order_total_html();
                    ?>
                </p>
            </div>
            <div class="go_checkout">
                <a class="btn btn_submit" href="<?php echo wc_get_checkout_url(); ?>"><?php _e('Tiến hành đặt hàng') ?></a>
            </div>
        </div>
        <?php
    endif;
    $cart_footer = ob_get_clean();
    wp_send_json_success( array(
        'mini_cart' => $mini_cart,
        'cart_footer' => $cart_footer,
    ) );
}
function save_product_attribute_from_name( $name, $label='', $set=true ){
    if( ! function_exists ('get_attribute_id_from_name') ) return;

    global $wpdb;

    $label = $label == '' ? ucfirst($name) : $label;
    $attribute_id = get_attribute_id_from_name( $name );

    if( empty($attribute_id) ){
        $attribute_id = NULL;
    } else {
        $set = false;
    }
    $args = array(
        'attribute_id'      => $attribute_id,
        'attribute_name'    => $name,
        'attribute_label'   => $label,
        'attribute_type'    => 'select',
        'attribute_orderby' => 'menu_order',
        'attribute_public'  => 0,
    );


    if( empty($attribute_id) ) {
        $wpdb->insert(  "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
        set_transient( 'wc_attribute_taxonomies', false );
    }

    if( $set ){
        $attributes = wc_get_attribute_taxonomies();
        $args['attribute_id'] = get_attribute_id_from_name( $name );
        $attributes[] = (object) $args;
        //print_r($attributes);
        set_transient( 'wc_attribute_taxonomies', $attributes );
    } else {
        return;
    }
}
function get_attribute_id_from_name( $name ){
    global $wpdb;
    $attribute_id = $wpdb->get_col("SELECT attribute_id
    FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
    WHERE attribute_name LIKE '$name'");
    return reset($attribute_id);
}

function create_product_variation( $data ){
    $postname = sanitize_title( $data['title'] );
    $post_data = array(
        'post_author'   => get_current_user_id(),
        'post_name'     => $postname,
        'post_title'    => $data['title'],
        'post_content'  => $data['content'],
        'post_excerpt'  => $data['excerpt'],
        'post_status'   => 'publish',
        'ping_status'   => 'closed',
        'post_type'     => 'product',
        'guid'          => home_url( '/product/'.$postname.'/' ),
    );

    $product_id = wp_insert_post( $post_data );

    $product = new WC_Product_Variable( $product_id );
    $product->save();

    if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
        $product->set_gallery_image_ids( $data['gallery_ids'] );

    // SKU
    if( ! empty( $data['sku'] ) )
        $product->set_sku( $data['sku'] );

    // STOCK (stock will be managed in variations)
    $product->set_stock_quantity( 1000 ); // Set a minimal stock quantity
    $product->set_manage_stock(false);
    $product->set_stock_status('in_stock');

    // Tax class
    if( empty( $data['tax_class'] ) )
        $product->set_tax_class( $data['tax_class'] );

    // WEIGHT
    if( ! empty($data['weight']) )
        $product->set_weight('');
    else
        $product->set_weight($data['weight']);

    $product->validate_props(); // Check validation

    ## ---------------------- VARIATION ATTRIBUTES ---------------------- ##

    $product_attributes = array();
    foreach( $data['attributes'] as $key => $terms ){
        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
        $attr_label = ucfirst($key); // attribute label name
        $attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug

        // NEW Attributes: Register and save them
        if( ! taxonomy_exists( $taxonomy ) )
            save_product_attribute_from_name( $attr_name, $attr_label );

        $product_attributes[$taxonomy] = array (
            'name'         => $taxonomy,
            'value'        => implode('|' , $terms),
            'position'     => $key,
            'is_visible'   => 1,
            'is_variation' => 1,
            'is_taxonomy'  => 1
        );
        wp_set_object_terms($product_id, $terms, $taxonomy);
        foreach ($data['variants'] as $k => $v){
            $variation = new WC_Product_Variation();
            $variation->set_parent_id($product_id);
            $variation->set_regular_price($v['price']); // Giá của variation
            $variation->set_attributes(array($taxonomy => strtolower($terms[$k])));
            $variation->set_sku($v['sku']);
            $variation->set_manage_stock(true);
            $variation->set_stock_quantity($v['inventory_quantity']);
            $variation->set_stock_status('in_stock');
            $variation->set_weight($v['weight']);
            $variation->save();
        }
    }
    update_post_meta( $product_id, '_product_attributes', $product_attributes );
    update_post_meta( $product_id, '_sapo_product_id', $data['id'] );
    $product->save(); // Save the data

}


/**
 * Load Jetpack compatibility file.
 */
if ( defined( 'JETPACK__VERSION' ) ) {
	require get_template_directory() . '/inc/jetpack.php';
}

