<?php
class StoreEthan {
    protected $products = array();
    public function __construct()
    {
    }
    public function init()
    {
        $this->hook();

        $this->ajax();
    }
    public function ajax()
    {
        $ajaxs = array(
            'ethan_data_product' => true,
            'more_products' =>      true,
            'load_compare_products' => true,
            'more_posts'            => true,
            'admin_upload_files'    => false,
            'store_task'            => true,
        );
        foreach ($ajaxs as $k => $a){
            add_action( 'wp_ajax_' . $k, array($this , $k) );
            if($a) {
                add_action('wp_ajax_nopriv_' . $k, array($this , $k));
            }
        }
    }
    public function hook()
    {
        add_action('wp_enqueue_scripts', array($this,'frontend_scripts') , 30);
        add_action('product_cat_add_form_fields' ,array($this,'product_cat_form_fields'), 20);
        add_action('product_cat_edit_form_fields' ,array($this,'product_cat_edit_form_fields'), 20);

        add_action( 'created_term', array( $this, 'save_category_fields' ), 10, 3 );
        add_action( 'edit_term', array( $this, 'save_category_fields' ), 10, 3 );
        add_action( 'pre_get_posts',  array($this , 'set_posts_per_page')  );
        add_action('woocommerce_after_add_to_cart_button' , array($this , 'after_add_to_cart_button'));
        add_action('woocommerce_after_add_to_cart_form' , array($this , 'after_add_to_cart_form'));
        add_action( 'pre_get_posts', array($this , 'custom_filter_products_by_price_and_brand' ) ,30);
        add_filter( 'woocommerce_format_sale_price', array($this ,'woocommerce_format_sale_price'), 10, 3 );
        add_action('add_meta_boxes', array($this ,'custom_product_meta_box' ));
        add_action( 'admin_enqueue_scripts', array($this ,'admin_scripts') , 50);
//        add_action( 'init' , array($this , 'init_load') );
        add_action( 'save_post', array($this , 'save_post') ,10 ,3);
        add_action( 'woocommerce_variation_options_pricing' , array($this ,'woocommerce_variation_options_pricing') , 10 ,3 );
        add_action( 'woocommerce_save_product_variation', array($this ,'save_custom_field_variation'), 10, 2 );
        add_action( 'woocommerce_available_variation' , array($this ,'woocommerce_available_variation' ) , 10 ,3 );
        add_action( 'pa_mau-sac_edit_form_fields' , array($this  , 'add_form_fields' ) , 20 ,2 );
        add_filter( 'woocommerce_variable_price_html' , array($this , 'woocommerce_variable_price_html'), 10 ,2);
//        add_action( 'my_midnight_event',  array($this , 'store_task' ));
    }

    public function store_task()
    {
        $this->init_hoook();
        die('ccc');
    }

    public function init_load()
    {
        $this->init_hoook();
    }
    public function getAllKiotProducts($currentItem = 0)
    {
        $service = new Kiotviet_Sync_Service_Auth();
        $params = array(
            'currentItem'   => $currentItem,
            'pageSize'   => 100,
            'includePricebook'   => true,
            'includeInventory'   => true,
            'orderBy'   => 'createdDate',
            'orderDirection'   => 'desc',
            'isMykiot'   => true,
        );
        $response = $service->request('get', 'https://public.kiotapi.com/products', $params);
        if($response['status'] == 'success'){
            foreach ($response['data']['data'] as $key => $product){
                $this->products[] = $product;
            }
            $nextItem = $currentItem + 100;
            if($response['data']['total'] > $nextItem){
                $this->getAllKiotProducts($nextItem);
            }
        }
    }

    public function init_hoook()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'kiotviet_sync_products';

        $wpdb->query( "DELETE FROM $table_name" );
        $service = new Kiotviet_Sync_Service_Auth();

        $this->getAllKiotProducts();
        $res_categories = $service->getAllCategory();
        $all_categories = array();
        if($res_categories['status'] == 'success'){
            $all_categories = $res_categories['data']['data'];
        }

        $categories = array();
        $categoryKvId = [];
        $_products = array();
        $master = 0;

        foreach ($this->products as $key => $product){
//                $args = array(
//                    'limit' => 1, // Lấy tất cả sản phẩm khớp
//                    'status' => 'publish', // Chỉ lấy sản phẩm đã được xuất bản
//                    'name' => $product['name'] // Tìm kiếm theo tên sản phẩm chính xác
//                );
//
//                $query = new WC_Product_Query( $args );
//
//                $datas = $query->get_products();
//
//                if ( !empty( $datas ) ) {
//                    continue;
//                }
            $results = array_filter($all_categories, function($v, $k) use ($product) {
                return $v['categoryId'] == $product['categoryId'];
            }, ARRAY_FILTER_USE_BOTH);
            if(count($results) > 0){
                $results = array_values($results);
                $category = $results[0];
                $categories[] = array(
                    'name'  => $category['categoryName'],
                    'categoryKvId' => $category['categoryId'],
                    'dataRaw' => json_encode($category),
                );
                $categoryKvId[] = $category['categoryId'];
            }
            $type = $product['type'] == 1 ? 'simple' : 'variable';
            if( $product['type'] == 2){
                $masterIndex = getMasterFromList($_products , $product);
                if($masterIndex === false){
                    $raw_attributes = array();
                    foreach ($product['attributes'] as $attribute){
                        $raw_attributes[] = array(
                            'name' => $attribute['attributeName'],
                            'value' => array($attribute['attributeValue']),
                            'visible' => 1,
                            'taxonomy' => 1
                        );
                    }
                    $sku = $product['code'] . 'Master';
                    if(strpos($product['code'] , '-') !== false){
                        $str_arr = explode('-' , $product['code']);
                        $sku = $str_arr[0];
                    }
                    $master++;

                    $_products[]  = array(
                        'id'    => 0,
                        'master' => 'ccccc',
                        'kv_id'  => isset($product['masterProductId']) ? $product['masterProductId'] : $product['id'],
                        'data_raw'  => json_encode($product),
                        'type'  => $type,
                        'brand' => isset($product['tradeMarkName']) ? $product['tradeMarkName'] : '',
                        'sku'  => $sku,
                        'nameMaster'  => $product['name'],
                        'name'  => $product['description'],
                        'description'  => $product['description'],
                        'stock_quantity'  => $product['inventories'][0]['onHand'],
                        'sale_price'  => '',
                        'regular_price' => '',
                        'category_kv'  => $product['categoryId'],
                        'manage_stock'  => 1,
                        'weight'  => $product['weight'],
                        'low_stock_amount'  =>  $product['inventories'][0]['onHand'] < 5,
                        'master_product_id'  =>  isset($product['masterProductId']) ? $product['masterProductId'] : $product['id'],
                        'raw_image_id' => !isset($product['images']) ? array() : $product['images'][0],
                        'raw_gallery_image_ids' => array(),
                        'raw_attributes'  => $raw_attributes,
                    );
                }else{
                    foreach ($product['attributes'] as $attribute){
                        foreach ($_products[$masterIndex]['raw_attributes'] as $k => $raw_attribute){
                            if($raw_attribute['name'] == $attribute['attributeName']){
                                if(!array_search($raw_attribute['value'] , $_products[$masterIndex]['raw_attributes'][$k]['value'])){
                                    $_products[$masterIndex]['raw_attributes'][$k]['value'][] = $attribute['attributeValue'];
                                }
                            }
                        }
                    }
                }
                $type = 'variation';
            }
            $raw_attributes = array();
            foreach ($product['attributes'] as $attribute){
                $raw_attributes[] = array(
                    'name' => $attribute['attributeName'],
                    'value' => array($attribute['attributeValue']),
                    'visible' => 1,
                    'taxonomy' => 1
                );
            }
            $brand = isset($product['tradeMarkName']) ? $product['tradeMarkName'] : '';
            $_products[]  = array(
                'id'    => 0,
                'kv_id'  => $product['id'],
                'data_raw'  => json_encode($product),
                'type'  => $type,
                'sku'  => $product['code'],
                'brand' => $brand,
                'nameMaster'  => $product['name'],
                'name'  => $product['fullName'],
                'description'   => $product['description'],
                'stock_quantity'  => $product['inventories'][0]['onHand'],
                'sale_price'  => '',
                'regular_price' => $product['basePrice'],
                'category_kv'  => $product['categoryId'],
                'manage_stock'  => 1,
                'weight'  => $product['weight'],
                'low_stock_amount'  =>  $product['inventories'][0]['onHand'] < 5,
                'master_product_id'  => $masterIndex ? $_products[$masterIndex]['masterProductId'] :
                    (isset($product['masterProductId']) ? $product['masterProductId'] : $product['id']),
                'raw_image_id' => !isset($product['images']) ? array() : $product['images'][0],
                'raw_gallery_image_ids' => array(),
                'raw_attributes'  => $raw_attributes,
            );
        }

        $service_category = new Kiotviet_Sync_Service_Category();
        $service_category->addInit($categories , $categoryKvId);
//            echo '<pre>';
//            print_r($_products);
//            echo '</pre>';
//            die('cc');
        $service_product = new Kiotviet_Sync_Service_Product();
        $product_id = $service_product->addInit($_products);
    }

    public function admin_scripts($hook)
    {
        wp_enqueue_script( 'wp-color-picker' );
        wp_enqueue_style('ethan_frontend', STORE_ASSETS_URL .'css/admin.css?e', array(), _S_VERSION);
        wp_enqueue_script('ethan_script', STORE_ASSETS_URL .'js/admin.js', array('jquery'), _S_VERSION);
        $params = array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'ethan_nonce' )
        );
        wp_localize_script( 'ethan_script', 'ethan_admin', $params );
    }
    public function frontend_scripts()
    {
        wp_enqueue_style( 'slick', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css', array(), _S_VERSION );
        wp_enqueue_style( 'slick-theme', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.css', array(), _S_VERSION );
        wp_enqueue_style('jquery-ui-css', 'https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css');
        wp_enqueue_style('nouislider-css', 'https://cdn.jsdelivr.net/npm/nouislider@15.8.1/dist/nouislider.min.css');


        wp_enqueue_style('ethan_frontend', STORE_ASSETS_URL .'css/frontend.css?e', array(), _S_VERSION);

        wp_enqueue_script('jquery-migrate');
        wp_enqueue_script('jquery-ui-slider');

        wp_enqueue_script( 'airtalk-popper', 'https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js', array('jquery' , 'jquery-ui-slider'), _S_VERSION, true );
        wp_enqueue_script( 'airtalk-bts', 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js', array('jquery' ,'jquery-ui-slider'), _S_VERSION, true );
        wp_enqueue_script( 'slick', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js', array('jquery'), _S_VERSION, true );
        wp_enqueue_script( 'nouislider', 'https://cdn.jsdelivr.net/npm/nouislider@15.8.1/dist/nouislider.min.js', array('jquery', 'jquery-migrate' ,'jquery-ui-slider'), _S_VERSION, true );
        wp_enqueue_script('ethan_script', STORE_ASSETS_URL .'js/frontend.js', array('slick' , 'nouislider'), _S_VERSION);
        $params = array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'ethan_nonce' )
        );
        if(is_product_category() || is_category()){
            $cate = get_queried_object();
            $params['category_id'] = $cate->term_id;
        }

        if(is_product()){
            $params['product_id'] = get_the_ID();
        }
        wp_localize_script( 'ethan_script', 'ethan_frontend', $params );

    }

    public function ethan_data_product()
    {
        if(isset($_POST['product_id'])){
            $product_id = abs($_POST['product_id']);
            $product = wc_get_product( $product_id );
            $post = get_post( $product_id );
            $brands = wp_get_post_terms( $product_id, 'pwb-brand' );
            $_brand = '';
            if ( !empty($brands) && !is_wp_error($brands) ) {
                foreach ( $brands as $brand ) {
                    $_brand .= $_brand == '' ? $brand->name : ', ' . $brand->name;
                }
            }
            $post_thumbnail_id = $product->get_image_id();
            $image             = wp_get_attachment_image($post_thumbnail_id , 'full');
            $sku = '';
            if($product->get_type() == 'variable'){
                $variations = $product->get_available_variations();
                if(count($variations) > 0){
                    $sku = $variations[0]['sku'];
                }
            }else{
                $sku = $product->get_sku();
            }
            $chart = new ChartInterface($product->get_id());

            $chart->ethan_get_sizes();
            $colums = array();
            $rows = array();
            if(!empty($chart->data)){
                $colums = $chart->data['columns'];
                $rows = $chart->data['rows'];
            }
            ob_start();
            ?>

                <thead>
                <tr>
                    <?php foreach ($colums as $k => $cl) : ?>
                        <th class="<?php echo $k > 0 ? 'text-center' : ''; ?>"><?php echo $cl; ?></th>
                    <?php endforeach; ?>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $r) : ?>
                    <tr>
                        <?php foreach ($colums as $k => $cl) : ?>
                            <td class="<?php echo $k > 0 ? 'text-center' : ''; ?>"><?php echo $r[$k]; ?></td>
                        <?php endforeach; ?>
                    </tr>
                <?php endforeach; ?>
                </tbody>

            <?php
            $table = ob_get_clean();
            $data = array(
                'description'   => get_the_content(null, false ,$post),
                'price'         => $product->get_price_html(),
                'title'         => $product->get_name(),
                'table_html'         => $table,
                'sku'           => $sku,
                'brand'         => $_brand,
                'image'         => $image,
            );
            wp_send_json_success($data );
        }
        wp_send_json_error(json_encode(['message' => __('Not found' , 'storeethan')]), 400);
        wp_die();
    }
    public function custom_filter_products_by_price_and_brand( $query ) {
//        if ( is_product_category() && $query->is_main_query() ) {
            $order_by =  isset( $_REQUEST['orderby'] ) ? wc_clean( (string) wp_unslash( $_REQUEST['orderby'] ) ) : '';
            $from = isset( $_REQUEST['price_from'] ) ? abs( $_REQUEST['price_from'] ) : 0;
            $to = isset( $_REQUEST['price_to'] ) ? abs( $_REQUEST['price_to'] ) : 0;
            $brand = isset( $_REQUEST['brand'] ) ? $_REQUEST['brand'] : 0;
            $size = isset( $_REQUEST['size'] ) ? wp_unslash( $_REQUEST['size'] ) : '';
            $color = isset( $_REQUEST['color'] ) ? wp_unslash( $_REQUEST['color'] ) : '';
            $count_filter = 0;
            if($from && $to){
                $meta_query = array(
                    array(
                        'key' => '_price',
                        'value' => array( $from, $to ), // Khoảng giá cần lọc
                        'compare' => 'BETWEEN',
                        'type' => 'NUMERIC'
                    )
                );
                $query->set( 'meta_query', $meta_query );
                $count_filter++;
            }
            global $wp_query;

            $tax_query = isset( $wp_query->tax_query->queries ) ? $wp_query->tax_query->queries : array();
            if($brand){
                $brands = explode(',', $brand);
                $tax_query[] = array(
                    'taxonomy' => 'pwb-brand',
                    'field'    => 'term_id',
                    'terms'    => $brands,
                    'operator' => 'IN'
                );

                $count_filter++;
            }
            if($color){
                $tax_query[] = array(
                    'taxonomy' => 'pa_mau-sac',
                    'field'    => 'slug',
                    'terms'    => $color
                );
                $count_filter++;
            }
            if($size){
                $tax_query[] = array(
                    'taxonomy' => 'pa_kich-thuoc',
                    'field'    => 'slug',
                    'terms'    => $size
                );
                $count_filter++;
            }
            if(count($tax_query) > 0){
                $query->set( 'tax_query', $tax_query );
            }
            if($order_by == '' || $order_by == 'date'){
                $query->set( 'orderby', 'date' );
                $query->set( 'order', 'DESC' );
            }else{
                $query->set('meta_query', array(
                    array(
                        'key' => '_price', // Đảm bảo sản phẩm có giá
                        'compare' => 'EXISTS',
                    ),
                ));
                $count_filter++;
                if($order_by == 'price_asc'){
                    $query->set( 'order', 'ASC' );
                }else{
                    $query->set( 'order', 'DESC' );
                }
                $query->set('orderby', 'meta_value_num');
                if($order_by == 'price_asc'){
                    $query->set('orderby', array(
                        'meta_value_num' => 'ASC',
                        'meta_value' => 'ASC',
                        '_price' => 'ASC',
                    ));
                }else{
                    $query->set('orderby', array(
                        'meta_value_num' => 'DESC',
                        'meta_value' => 'DESC',
                        '_price' => 'DESC',
                    ));
                }
            }
            $query->set( 'count_filter', $count_filter );
//        }
    }
    public function set_posts_per_page( $query ) {

        global $wp_the_query;

//        if ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_search() ) ) {
//            $query->set( 'posts_per_page', 3 );
//        }
//        elseif ( ( ! is_admin() ) && ( $query === $wp_the_query ) && ( $query->is_archive() ) ) {
//            $query->set( 'posts_per_page', 5 );
//        }
        if(is_product_category()){
            $query->set( 'posts_per_page', 24 );
        }
        if ( $query->is_search() && !is_admin() && $query->is_main_query() ) {
            $query->set( 'posts_per_page', 24 );
            $query->set( 'post_type', 'product' );
            add_filter( 'posts_where', 'search_by_title_only', 10, 2 );
        }

        return $query;
    }
    public function product_cat_form_fields($taxonomy){

        ?>
        <div class="form-field term-description-wrap">
            <label for="tag-description"><?php _e( 'Thư viện' ); ?></label>
            <div id="product_cat_gallery" style="float: left; margin-right: 10px;">
                <img src="<?php echo wc_placeholder_img_src(); ?>" width="60px" height="60px">
            </div>
            <div class="images_galllery" style="line-height: 60px;">
<!--                <input type="hidden" id="product_cat_gaollery_id" name="product_cat_thumbnail_id">-->
                <button type="button" class="upload_image_gallery_button button">
                    <?php _e('Tải lên/Thêm ảnh' , 'storeethan'); ?>;
                </button>
            </div>
        </div>
        <script type="text/javascript">
            // Uploading files
            var file_gallery_frame;

            jQuery( document ).on( 'click', '.upload_image_gallery_button', function( event ) {
                event.preventDefault();

                // If the media frame already exists, reopen it.
                if ( file_gallery_frame ) {
                    file_gallery_frame.open();
                    return;
                }

                // Create the media frame.
                file_gallery_frame = wp.media.frames.downloadable_file = wp.media({
                    title: '<?php esc_html_e( 'Choose an image', 'woocommerce' ); ?>',
                    button: {
                        text: '<?php esc_html_e( 'Use image', 'woocommerce' ); ?>'
                    },
                    multiple: true
                });

                // When an image is selected, run a callback.
                file_gallery_frame.on( 'select', function() {
                    var selection           = file_gallery_frame.state().get( 'selection' );
                    var images_galllery = jQuery('.images_galllery');
                    // var attachment_thumbnail = attachment.sizes.thumbnail || attachment.sizes.full;
                    if(selection.length > 0){
                        images_galllery.find('.product_cat_gallery_id').remove();
                        var html = '';
                        selection.map( function( attachment , k ) {
                            attachment = attachment.toJSON();
                            images_galllery.prepend(`<input type="hidden" id="product_cat_gallery_id" name="product_cat_gallery_id[${k}]" value="${attachment.id}">`)
                            html += ` <img src="${attachment.url}" width="60px" height="60px">`
                        });
                        jQuery('#product_cat_gallery').html(html);
                    }
                });

                // Finally, open the modal.
                file_gallery_frame.open();
            });

        </script>
        <div class="clear"></div>
        <?php
    }
    public function product_cat_edit_form_fields($taxonomy)
    {
        $ids = get_term_meta($taxonomy->term_id, 'gallery_ids', true);
        $images = '<img src="' .wc_placeholder_img_src(). '" width="60px" height="60px">';
        if(!empty($ids)){
            $images = '';
            foreach ($ids as $id) {
                $images .= '<img src="' .wp_get_attachment_thumb_url($id). '" width="60px" height="60px">';
            }
        }
        ?>
        <tr class="form-field term-thumbnail-wrap">
			<th scope="row" valign="top"><label><?php esc_html_e( 'Thư viện', 'woocommerce' ); ?></label></th>
            <td>
                <div id="product_cat_gallery" style="margin-right: 10px;">
                    <?php echo $images; ?>
                </div>
                <div class="images_galllery" style="line-height: 60px;">
                    <!--                <input type="hidden" id="product_cat_gaollery_id" name="product_cat_thumbnail_id">-->
                    <button type="button" class="upload_image_gallery_button button">
                        <?php _e('Tải lên/Thêm ảnh' , 'storeethan'); ?>;
                    </button>
                </div>
                <script type="text/javascript">
                    var file_gallery_frame;

                    jQuery( document ).on( 'click', '.upload_image_gallery_button', function( event ) {
                        event.preventDefault();

                        // If the media frame already exists, reopen it.
                        if ( file_gallery_frame ) {
                            file_gallery_frame.open();
                            return;
                        }

                        // Create the media frame.
                        file_gallery_frame = wp.media.frames.downloadable_file = wp.media({
                            title: '<?php esc_html_e( 'Choose an image', 'woocommerce' ); ?>',
                            button: {
                                text: '<?php esc_html_e( 'Use image', 'woocommerce' ); ?>'
                            },
                            multiple: true
                        });

                        // When an image is selected, run a callback.
                        file_gallery_frame.on( 'select', function() {
                            var selection           = file_gallery_frame.state().get( 'selection' );
                            var images_galllery = jQuery('.images_galllery');
                            // var attachment_thumbnail = attachment.sizes.thumbnail || attachment.sizes.full;
                            if(selection.length > 0){
                                images_galllery.find('.product_cat_gallery_id').remove();
                                var html = '';
                                selection.map( function( attachment , k ) {
                                    attachment = attachment.toJSON();
                                    images_galllery.prepend(`<input type="hidden" id="product_cat_gallery_id" name="product_cat_gallery_id[${k}]" value="${attachment.id}">`)
                                    html += ` <img src="${attachment.url}" width="60px" height="60px">`
                                });
                                jQuery('#product_cat_gallery').html(html);
                            }
                        });

                        // Finally, open the modal.
                        file_gallery_frame.open();
                    });

                </script>
                <div class="clear"></div>
            </td>
        </tr>
        <?php
    }
    public function save_category_fields($term_id, $tt_id = '', $taxonomy = '')
    {
        if ( isset( $_POST['product_cat_gallery_id'] ) && 'product_cat' === $taxonomy ) {
            update_term_meta( $term_id, 'gallery_ids',  $_POST['product_cat_gallery_id'] );
        }
        if ( isset( $_POST['color_term'] ) && 'pa_mau-sac' === $taxonomy ) {
            update_term_meta( $term_id, 'color_term',  $_POST['color_term'] );
        }
    }
    public function after_add_to_cart_button()
    {
        ?>
        <button type="button" class="btn btn_compare" id="btn_compare">So sánh với sản phẩm khác</button>
        <?php
    }
    public function after_add_to_cart_form()
    {
        wc_get_template('single-product/after_add_to_cart.php');
    }
    public function woocommerce_format_sale_price($price, $regular_price, $sale_price){
        $formatted_regular_price = is_numeric( $regular_price ) ? wc_price( $regular_price ) : $regular_price;
        $formatted_sale_price    = is_numeric( $sale_price ) ? wc_price( $sale_price ) : $sale_price;

        // Strikethrough pricing.
        $price = '<del class="sale_price" aria-hidden="true">' . $formatted_regular_price . '</del> ';
        // Add the sale price.
        $price .= '<ins aria-hidden="true">' . $formatted_sale_price . '</ins>';
        return $price;
    }

    public function more_posts()
    {
        $nonce = $_POST['nonce'];
        if (!wp_verify_nonce($nonce, 'ethan_nonce')) {
            die('Security!');
        }
        $category = $_POST['category'];
        $page = $_POST['page'];
        $args = array(
            'post_status'    => 'publish',
            'posts_per_page' => 8,
            'paged'          => $page,
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field'    => 'term_id',
                    'terms'    => $category,
                ),
            ),
        );
        $query = new WP_Query($args);
        ob_start();
        while ( $query->have_posts() ) :
            $query->the_post();
            global $post;
            $post_id = get_the_ID();
            $thumbnail_id = get_post_thumbnail_id($post_id);
            $image_url = wp_get_attachment_image_src($thumbnail_id, 'full');
            $url = '';
            if ($image_url) {
                $url = $image_url[0];
            }
            $categories = get_the_category($post_id);
            $cate = '';
            foreach ($categories as $category) {
                $cate .= $cate == '' ? $category->name : ', ' . $category->name;
            }
            $datetime = new DateTime($post->post_date);
            $day_with_suffix = addOrdinalSuffix($datetime->format('j'));
            $d =  $datetime->format('M') . ' ' .$day_with_suffix . ', ' . $datetime->format('Y');
            ?>
            <div class="col-md-3 col-12 post">
                <a href="<?php echo get_permalink(); ?>">
                    <div class="card_post">
                        <img src="<?php echo $url; ?>" alt="Ảnh bài viết">
                        <div class="props-of-post">
                            <div class="type_post">
                                <?php echo $cate; ?>
                            </div>
                            <div class="name_post">
                                <?php the_title(); ?>
                            </div>
                            <div class="date_post">
                                <!--July 14th, 2024-->
                                <?php echo $d; ?>
                            </div>
                        </div>
                    </div>
                </a>
            </div>
        <?php endwhile;
        $content =ob_get_clean();
        wp_send_json_success(array('content' => $content));

        wp_die();
    }
    public function more_products()
    {
        $nonce = $_POST['nonce'];
        if (!wp_verify_nonce($nonce, 'ethan_nonce')) {
            die('Security!');
        }
        $category = $_POST['category'];
        $page = $_POST['page'];
        $args = array(
            'post_status'    => 'publish',
            'posts_per_page' => 8,
            'paged'          => $page,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat', // Taxonomy là product_cat
                    'field'    => 'term_id', // Truy vấn bằng term ID
                    'terms'    => $category, // Term ID bạn muốn lấy
                ),
            ),
        );
        $products = wc_get_products( $args );

        ob_start();
        foreach ($products as $product){
            $GLOBALS['product'] = $product;
            $GLOBALS['post'] = get_post($product->get_id());
            wc_get_template_part('content', 'product');
        }
        $content =ob_get_clean();
        wp_send_json_success(array('content' => $content));

        wp_die();
    }
    public function load_compare_products()
    {
        $nonce = $_POST['nonce'];
        if (!wp_verify_nonce($nonce, 'ethan_nonce')) {
            die('Security!');
        }
        $product_id = isset($_POST['product_id']) ? abs($_POST['product_id']) : 0;
        $page = isset($_POST['page']) ? abs($_POST['page']) : 1;
        $product = wc_get_product($product_id);
        $products = get_posts(
            array(
                'post_type' => 'product',
                'tax_query' => [
                    [
                        'taxonomy' => 'product_cat',
                        'field'    => 'term_id',
                        'terms' => $product->get_category_ids(),
                        'operator'  => 'IN',
                        'include_children' => false
                    ],
                ],
                'numberposts' => 20,
                'paged'          => $page,
            )
        );
        ob_start();
        ?>
        <?php foreach ($products as $post) :
            $_product = wc_get_product($post->ID);
            $post_thumbnail_id = $_product->get_image_id();
            $image             = $post_thumbnail_id ? wp_get_attachment_image_src($post_thumbnail_id , 'full')[0] : wc_placeholder_img_src();
            ?>
            <div class="card_post">
                <img src="<?php echo $image; ?>" alt="">
                <div class="name_post">
                    <?php echo $_product->get_name(); ?>
                </div>
                <div class="card_price">
                    <?php echo number_format($_product->get_price()); ?>
                </div>
                <a href="" data-productid="<?php echo $post->ID; ?>" class="btn btn_compare start_compare"><?php _e('So sánh'); ?></a>
            </div>
        <?php endforeach;
        $content = ob_get_clean();
        wp_send_json_success(array('content' => $content));
    }
    public function custom_product_meta_box()
    {
        add_meta_box(
            'video_product',
            'Video product',
            array($this , 'custom_product_meta_box_callback'),
            'product',                  
            'side',            
            'high'
        );
    }
    public function custom_product_meta_box_callback($post){
        $url = get_post_meta( $post->ID, 'product_video_link',true );

        $name = '';
        if(trim($url) != ''){
            $file = convert_url_to_path($url);
            $name = basename($file);
        }

        ?>
            <div class="video_product">
                <input id="inp_video" accept="video/mp4" type="file" style="display: none;">
                <input type="hidden" name="video_link" value="<?php echo $url; ?>">
                <div class="loader"></div>
                <p class="name_video"><?php echo $name; ?></p>
                <a class="" id="open_video" href="">Thiết lập video sản phẩm</a>
            </div>

        <?php
    }
    public function admin_upload_files()
    {
        $res = array(
            'success'   => false,
            'msg'       => ''
        );
        if (!empty($_FILES['file']['name'])) {

            $uploaded_file = wp_handle_upload($_FILES['file'], array('test_form' => false));
            $file_type = wp_check_filetype($_FILES['file']['name']);

            if ($file_type['ext'] !== 'mp4') {
                $res['msg'] = __('Không phải là file video');
            }else{
                if ($uploaded_file && !isset($uploaded_file['error'])) {
                    $res['name'] = basename($uploaded_file['file']);
                    $res['url'] = $uploaded_file['url'];
                    $res['success'] = true;
                } else {
                    // Xử lý lỗi upload
                    $res['msg'] = $uploaded_file['error'];
                }
            }

        }

        echo json_encode($res);
        wp_die();
    }
    public function save_post( $post_id, $post, $update )
    {
        if(isset($_POST['video_link'])){

            update_post_meta( $post_id, 'product_video_link',$_POST['video_link'] );
        }
    }
    public function woocommerce_variation_options_pricing($loop, $variation_data, $variation)
    {
        $color = get_post_meta( $variation->ID, '_color_field', true );
        ?>
        <input type="text" name="color_field[<?php echo $loop; ?>]" value="<?php echo $color ? $color : '#fff' ?>" class="my-color-field<?php echo $loop; ?>" />
        <script>
            jQuery(document).ready(function($){
                $('.my-color-field<?php echo $loop; ?>').wpColorPicker({
                    change: function(event, ui) {
                        var $input = $(this);
                        setTimeout(function() {
                            $input.val(ui.color.toString()).change();
                        }, 1);
                    }
                });
            });
        </script>
        <?php
    }
    public function save_custom_field_variation( $variation_id, $i ) {
        if ( isset( $_POST['color_field'][$i] ) ) {
            update_post_meta( $variation_id, '_color_field', sanitize_text_field( $_POST['color_field'][$i] ) );
        }
    }
    public function woocommerce_available_variation($data , $product_variable , $variation)
    {
        $color = get_post_meta( $variation->get_id(), '_color_field', true );
        $data['color'] = $color ? $color : '#fff';
        return $data;
    }

    public function add_form_fields($tag, $taxonomy)
    {
        $color = get_term_meta($tag->term_id , 'color_term' , true);
        ?>
        <tr class="form-field term-description-wrap">
            <th scope="row"><label for="description"><?php _e( 'Chọn màu' ); ?></label></th>
            <td>
                <input type="text" name="color_term"
                       value="<?php echo $color ? $color : '#fff' ?>" class="my-color-field" />
            </td>
        </tr>

        <script>
            jQuery(document).ready(function($){
                $('.my-color-field').wpColorPicker({
                    change: function(event, ui) {
                        var $input = $(this);
                        setTimeout(function() {
                            $input.val(ui.color.toString()).change();
                        }, 1);
                    }
                });
            });
        </script>
        <?php
    }
    public function woocommerce_variable_price_html($price, $product)
    {
        $prices = $product->get_variation_prices( true );

        $min_price     = current( $prices['price'] );
        $max_price     = end( $prices['price'] );
        $min_reg_price = current( $prices['regular_price'] );
        $max_reg_price = end( $prices['regular_price'] );

        if ( $min_price !== $max_price ) {
            $price = wc_price( $min_price );
        }
        return $price;
    }

}
$at = new StoreEthan();
$at->init();