<?php 
function get_page_id_by_template( $template ) {
    $args = [
        'post_type'  => 'page',
        'numberposts'=> 1,
        'nopaging'   => true,
        'meta_key'   => '_wp_page_template',
        'meta_value' => 'page-templates/template-'.$template.'.php'
    ];
    $pages = get_posts( $args );
    return $pages[0];
}

function get_featured_img( $post_id ){
    global $post;
    $url = get_template_directory_uri();
    if( has_post_thumbnail( $post_id ) ){
       $img_id = get_post_thumbnail_id( $post_id ); 
        $images=wp_get_attachment_image_src( $img_id, false, false ); 
        return $images[0];
    }else{
        $post = get_post( $post_id );        
        if( isset( $post ) ){
            $preg=preg_match_all( '/<img.*?src="(.*?)"/', stripslashes( $post->post_content ), $matches );
            if( $preg ){ $i=0;
                foreach( $matches[1] as $image_url ){ $i++;
                    //if(empty($image_url)) continue;
                    if($i==1){return $image_url;}
                }
            }else{
                $images="$url"."/assets/images/nothumb.jpg";
            }
        }else{
            $images="$url"."/assets/images/nothumb.jpg";
        }                
        return $images;
    }
}

function custom_image_size( $post_id, $w, $h, $crop ){
    if( substr( get_featured_img( $post_id), -3 ) == 'gif' ){
        return get_featured_img( $post_id );
    }else{
        $params = array( 'width' => $w, 'height' => $h, 'crop' => $crop );
        return bfi_thumb( get_featured_img( $post_id ), $params );
    }
}

function custom_image_size_url( $url, $w, $h, $crop ){
	$params = array( 'width' => $w, 'height' => $h, 'crop' => $crop );
	return bfi_thumb($url, $params );
}

function add_file_types_to_uploads( $file_types ){
	$new_filetypes = array();
	$new_filetypes['svg'] = 'image/svg+xml';
	$file_types = array_merge( $file_types, $new_filetypes );
	return $file_types;
}
add_action( 'upload_mimes', 'add_file_types_to_uploads' );

add_action( 'wp_body_open', 'add_loading_icon' );
function add_loading_icon(){
    $site_icon = get_field('loading_icon', 'option');?>

    <div class="tbang-loading">
        <div class="tbang_loader">
            <span>
                <?php if($site_icon): ?>
                    <img alt="<?php echo bloginfo('name'); ?>" src="<?php echo $site_icon['url']; ?>">
                <?php endif; ?>
            </span>
        </div>
    </div>
<?php }

add_filter('wpcf7_autop_or_not', '__return_false');
add_filter( 'widget_text', 'do_shortcode' );

if( function_exists('acf_add_options_page') ) {
    
    acf_add_options_page(array(
        'page_title'    => 'Theme Settings',
        'menu_title'    => 'Theme Settings',
        'menu_slug'     => 'theme-settings',
        'capability'    => 'edit_posts',
        'redirect'      => false
    ));
}

function tbang_img_link( $file_name ){
    $base_img = get_stylesheet_directory_uri() . "/assets/images/";

    if($file_name && $file_name != ""){
        $url = $base_img . $file_name;
    }else{
        $url = $base_img . "nothumb.jpg";
    }

    return $url;
}

function share_social(){ ?>
    <ul class="share">
        <li class="facebook"><a class="channel-facebook" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=<?php the_permalink() ?>" onclick="window.open(this.href, 'mywin', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); return false;"><i class="fa fa-facebook"></i></a></li>

        <li class="twitter"><a class="channel-twitter" target="_blank" href="https://twitter.com/home?status=<?php the_title(); ?> <?php the_permalink() ?>" onclick="window.open(this.href, 'mywin', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); return false;"><i class="fa fa-twitter"></i></a></li>        

        <li class="google"><a class="channel-google" target="_blank" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" onclick="window.open(this.href, 'mywin', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); return false;"><i class="fa fa-google-plus"></i></a></li>
    </ul>
<?php
}

add_filter( 'acf/settings/save_json', 'tbang_json_save_point' );
function tbang_json_save_point( $path ) {
    $path = get_stylesheet_directory() . '/assets/acf-json';
    return $path;
}

add_filter( 'acf/settings/load_json', 'tbang_json_load_point' );
function tbang_json_load_point( $paths ) {
    unset( $paths[0] );
    $paths[] = get_stylesheet_directory() . '/assets/acf-json';
    return $paths;
}

add_filter( 'acf/settings/show_admin', 'tbang_acf_show_admin' );
function tbang_acf_show_admin( $show ) {
    
    return current_user_can( 'administrator' );
}

function render_link( $link, $class = 'more-link' ) {
    if( $link ): 
        $link_url       = $link['url'];
        $link_title     = $link['title'];
        $link_target    = $link['target'] ? $link['target'] : '_self'; ?>
        <a class="<?php echo $class; ?>" href="<?php echo esc_url( $link_url ); ?>" target="<?php echo esc_attr( $link_target ); ?>"><?php echo $link_title; ?></a>
    <?php endif;
}

function product_price( $price, $sale_price, $layout = 'list' ){
    if( $layout == 'list' ){
        if( $sale_price && $sale_price < $price ){ ?>
        <div class="price"><del><?php echo format_money( $price ) ?></del> <span class="percent"><?php _e( 'giảm', 'tbang_text' ) ?> <?php echo sale_percent( $sale_price, $price ) ?></span></div>
        <?php }else{
            $sale_price = $price;
        } ?>
        <div class="sale-price"><?php echo format_money( $sale_price ) ?></div>    

    <?php } else if( $layout == 'single' ){ ?>
        <div class="price">
            <?php if( $sale_price && $sale_price < $price ){ ?>
                <del><?php echo format_money( $price ) ?></del>
            <?php }else{
                $sale_price = $price;
            } ?>
            <ins><?php echo format_money( $sale_price ) ?></ins>

            <?php if( $sale_price && $sale_price < $price ){ ?>
                <span class="percent"><?php _e( 'giảm', 'tbang_text' ) ?> <?php echo sale_percent( $sale_price, $price ) ?>
            <?php } ?>
        </div>
    <?php }else if( $layout == 'related'){ ?>
        <div class="price">
            <?php if( $sale_price && $sale_price < $price ){ ?>
                <del><?php echo format_money( $price ) ?></del>
            <?php }else{
                $sale_price = $price;
            } ?>
            <div class="sale-price"><?php echo format_money( $sale_price ) ?></div>
        </div>
    <?php } ?>
<?php }

function format_money( $price ){
    return number_format( $price, 0, '.', '.' ).'đ';
}

function sale_percent( $sale_price, $price ){
    return round( 100 - ( $sale_price / $price * 100 ) ) . '%';
}

function product_filter(){
    $current_cat = get_query_var( 'product_cat' ) ? get_query_var( 'product_cat' ) : '';
    $sort = isset( $_GET[ 'sort' ] ) ? $_GET[ 'sort' ] : 'feature'; ?>

    <div class="wrap-filter-bar">
        <?php 
        $terms = get_terms( array(
            'taxonomy' => 'product_cat',
            'hide_empty' => false,
        ) );
        if( $terms ): ?>
        <div class="pn-ProductNav_Wrapper">
            <nav id="pnProductNav" class="pn-ProductNav">
                <div id="pnProductNavContents" class="pn-ProductNav_Contents">
                    <?php foreach ( $terms as $term ) { ?>
                        <a href="<?php echo get_term_link( $term ) ?>" class="pn-ProductNav_Link <?php echo $term->slug == $current_cat ? 'active' : ''; ?>"><?php echo $term->name; ?></a>
                    <?php } ?>
                </div>
            </nav>
            <button id="pnAdvancerLeft" class="pn-Advancer pn-Advancer_Left" type="button"></button>
            <button id="pnAdvancerRight" class="pn-Advancer pn-Advancer_Right" type="button"></button>
        </div>
        <?php endif; ?>

        <div class="filter-bar">
            <span><?php _e( 'Sắp xếp theo', 'tbang_text' ) ?></span>
            <div class="list-sort">
                <span data-sort="feature" class="feature <?php echo $sort == 'feature' ? 'active' : ''; ?>"><?php _e( 'Nổi bật', 'tbang_text' ) ?></span>
                <span data-sort="sale" class="sale <?php echo $sort == 'sale' ? 'active' : ''; ?>"><?php _e( '% Giảm', 'tbang_text' ) ?></span>
                <span data-sort="price" class="price <?php echo $sort == 'price' ? 'active' : ''; ?>"><?php _e( 'Giá cao đến thấp', 'tbang_text' ) ?></span>
                <span data-sort="price-down" class="price <?php echo $sort == 'price-down' ? 'active' : ''; ?>"><?php _e( 'Giá thấp đến cao', 'tbang_text' ) ?></span>
            </div>
        </div>
    </div>
<?php }

add_filter( 'pre_get_posts', function( $query ){
    if( is_admin() ) return $query;
    
    if( isset( $query->query_vars['post_type'] ) && is_array( $query->query_vars['post_type'] ) && in_array( 'product', $query->query_vars['post_type'] ) && isset( $_GET[ 'sort' ] ) ) {
        $sort = isset( $_GET[ 'sort' ] ) ? $_GET[ 'sort' ] : 'feature';

        if( $sort == 'sale' ){            
            $query->set( 'meta_key', '_discount_amount' );
            $query->set( 'order', 'DESC' );
            $query->set( 'orderby', 'meta_value' );

        }else if( $sort == 'price' ){
            $query->set( 'meta_key', 'sale_price' );
            $query->set( 'order', 'DESC' );
            $query->set( 'orderby', 'meta_value' );
            
        }else if( $sort == 'price-down' ){
            $query->set( 'meta_key', 'sale_price' );
            $query->set( 'order', 'ASC' );
            $query->set( 'orderby', 'meta_value' );
        }

    }else if ( $query->is_main_query() && $query->is_search() ) {
        $query->set( 'post_type', array( 'product' ) );
    }

    return $query;
} );

add_action( 'save_post', function( $post_id ){
    if( get_post_type( $post_id ) == 'product' ){
        $price = get_field( 'price', $post_id );
        $sale_price = get_field( 'sale_price', $post_id );

        $discount = 0;
        if( $sale_price < $price ){
            $discount = round( 100 - ( $sale_price / $price * 100 ) );
        }

        update_post_meta( $post_id, '_discount_amount', $discount );
    }
}, 10, 1 );

add_filter( 'wpcf7_form_elements', function( $form ){
    global $post;
    $price_html = '';

    if( is_singular( 'product' ) ){
        $price = (float) get_field( 'price', $post->ID );
        $sale_price = (float) get_field( 'sale_price', $post->ID );
        if( $sale_price && $sale_price < $price ){
            $price = $sale_price;
        }

        if( ! is_numeric( $price ) || $price == '' ){
            $price = 0;
        }

        $price_html = '
            <ul class="cf7-price-html">
                <li><strong>Tiền hàng</strong> <span>' . format_money( $price ) . '</span></li>
                <li><strong>Phí ship</strong> <span>0đ</span></li>
                <li><strong>Tổng Tiền</strong> <span>' . format_money( $price ) . '</span></li>
            </ul>
        ';

        $form = str_replace( 'HTML_PRICE', $price_html, $form );
        $form = str_replace( 'PRICE_VALUE', format_money( $price ), $form );
        $form = str_replace( 'PRODUCT_NAME', get_the_title( $post->ID ), $form );
        $form = str_replace( 'PRODUCT_URL', get_permalink( $post->ID ), $form );

    }elseif ( is_singular( 'landing_page' ) ) {
        $products = get_field( 'product_list', $post->ID );
        
        if( $products ){
            $html_item = '<input type="hidden" name="post_id" value="' . $post->ID . '" />';
            foreach( $products as $key => $product ) {             
                $html_item .= '
                    <div class="wrap-item">
                        <input type="checkbox" id="product-' . $key . '" name="product_item[]" value="' . $product['product_name'] . ': ' . format_money( $product['price'] ) . '">
                        <label for="product-' . $key . '">' . $product['product_name'] . ': ' . format_money( $product['price'] ) . '</label><br>
                    </div>
                ';
            }

            $price_html = "<div class='wrap-select-product'>" . $html_item . "</div>";
        }

        $form = str_replace( 'HTML_LP_PRICE', $price_html, $form );
        $form = str_replace( 'PRODUCT_URL', get_permalink( $post->ID ), $form );        
    }
    
    return $form;
}, 10 );

// add_action( 'wpcf7_mail_sent', function( $cf7 ){
add_action( 'wpcf7_before_send_mail', function( $cf7 ){

    if( $cf7->id() === 349 ){
        $submission = WPCF7_Submission::get_instance();
        $posted_data = $submission->get_posted_data();

        $link_drive_file = get_field( 'link_drive_file', $posted_data['post_id'] );

        if( $link_drive_file ){
            preg_match( "/\/d\/(.+?)\/.+?gid=(\d+)/", $link_drive_file, $matches );

            $GGS = new CF7GSC_googlesheet();

            $GGS->auth();
            $GGS->setSpreadsheetId( $matches[1] );
            $GGS->setWorkTabId( $matches[2] );


            $data = [
                'ho-ten'    => $posted_data['ho-ten'], 
                'sdt'       => $posted_data['sdt'], 
                'dia-chi'   => $posted_data['dia-chi'], 
                'san-pham'  => implode( " || ", $posted_data['product_item'] ),
                'url'       => $posted_data['your-url']
            ];

            $GGS->add_row( $data );
        }
    }
} );

$Gs_Connector_Service = new Gs_Connector_Service;
add_action( 'wpcf7_before_send_mail', array( $Gs_Connector_Service, 'cf7_save_to_google_sheets' ) );

/**
 * Skip send mail
 */
add_filter( 'wpcf7_skip_mail', function( $skip_mail, $contact_form ){
    return true;
}, 10, 2);

function page_child(){
    global $post;

    if( $post->post_parent ):
        $pages = get_pages( array(
            'hierarchical'  => 0,
            'parent'        => $post->post_parent
        ) );

        if( $pages ):

            echo '<ul class="list-page">';
            foreach( $pages as $page ):
                $class = $post->ID == $page->ID ? 'active' : '';
                
                echo '<li class="' . $class . '" ><a href="' . get_permalink( $page->ID ) . '">' . $page->post_title . '</a></li>';
                
            endforeach;
            echo '</ul>';

        endif;
    endif;
}

function tbang_comment( $comment, $args, $depth ) {
    if ( 'div' === $args['style'] ) {
        $tag       = 'div';
        $add_below = 'comment';
    } else {
        $tag       = 'li';
        $add_below = 'div-comment';
    }?>
    <<?php echo $tag; ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ); ?> id="comment-<?php comment_ID() ?>"><?php 
    if ( 'div' != $args['style'] ) { ?>
        <div id="div-comment-<?php comment_ID() ?>" class="comment-body"><?php
    } ?>
        <div class="comment-author vcard"><?php 
            if ( $args['avatar_size'] != 0 ) {
                echo get_avatar( $comment, $args['avatar_size'] ); 
            }  ?>

            <div class="comment-meta commentmetadata">
                <?php  printf( __( '<cite class="fn">%s</cite>' ), get_comment_author_link() ); ?>
                <?php if( user_can( $comment->user_id, 'administrator' ) ) {  ?>
                    <span class="is-admin-comment"><?php _e( 'Quản trị viên', 'tbang_text' ) ?></span>
                <?php } ?>

                <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>"><?php
                    printf( 
                        __('%1$s at %2$s'), 
                        get_comment_date(),  
                        get_comment_time() 
                    ); ?>
                </a>
                <?php 
                comment_reply_link( 
                    array_merge( 
                        $args, 
                        array( 
                            'add_below' => $add_below, 
                            'depth'     => $depth, 
                            'max_depth' => $args['max_depth'] 
                        ) 
                    ) 
                ); ?>
                <?php edit_comment_link( __( '(Edit)' ), '  ', '' ); ?>

                <?php 
                if ( $comment->comment_approved == '0' ) { ?>
                    <em class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></em><br/><?php 
                } ?>
                <div class="comment-text"><?php comment_text(); ?></div>                
            </div>            
        </div><?php 
    if ( 'div' != $args['style'] ) : ?>
        </div><?php 
    endif;
}

function bbase_star( $total ){ ?>
	<label class="rating-label">
		<input
		class="rating"
		max="5"
		step="0.5"
		style="--value:<?php echo $total; ?>"
		type="range"
		value="<?php echo $total; ?>">
	</label>
<?php }


add_action( 'get_header', function(){
    if( ! is_singular( 'product' ) ) return;
    $products = isset( $_COOKIE['products'] ) ?  $_COOKIE['products'] : '';
    $products = json_decode( $products );

    if( ! $products ){
        $products = [];
    }

    $pid = get_the_ID();
    if( !in_array( $pid, $products ) ){
        array_push( $products, $pid );
    }    

    $products = json_encode( $products );
    setcookie( 'products', $products, time()+360000, '/' );
});

add_action('init', function () {
    add_rewrite_rule('^san-pham/page/([0-9]+)','index.php?pagename=san-pham&paged=$matches[1]', 'top');
    flush_rewrite_rules();
}, 1000);


/**
 * Ajax search Global
 */
add_action( 'wp_ajax_global_search_ajax', 'global_search_ajax' );
add_action( 'wp_ajax_nopriv_global_search_ajax', 'global_search_ajax' );
function global_search_ajax(){
    $results                = array();
    $keyword                = $_POST[ 'data' ];
    $key =                  'cache_' . sanitize_title( $keyword );

    $data = get_transient( $key );
    if( $data ) wp_send_json( $data );

    if( $keyword ){
        $args = array(
            'post_status'            => array( 'publish' ),
            'post_type'              => array( 'product' ),
            's'                      => $keyword,
            'posts_per_page'         => 10,
        );

        $query = new WP_Query( $args );
        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) { $query->the_post();
                $post_url       = get_the_permalink();
                $output_title   = get_the_title();
                $results['result'][] = [ 'label' => $output_title, 'url' => $post_url ];
            }
        }
        wp_reset_postdata();
    }

    set_transient( $key, $results, 7200 );
    $data = get_transient( $key );

    wp_send_json( $results );
}
