/*
 Theme Name:   Woodmart Child
 Description:  Woodmart Child Theme
 Author:       XTemos
 Author URI:   http://xtemos.com
 Template:     woodmart
 Version:      1.0.0
 Text Domain:  woodmart
*/

// Add ISBN custom field
add_action( 'woocommerce_product_options_general_product_data', 'add_isbn_custom_field' );
function add_isbn_custom_field() {
    woocommerce_wp_text_input( array(
        'id'          => '_book_isbn',
        'label'       => __( 'ISBN', 'woocommerce' ),
        'placeholder' => 'Enter ISBN number',
        'desc_tip'    => true,
        'description' => __( 'ISBN of the book.', 'woocommerce' ),
    ));
}

// Save ISBN custom field
add_action( 'woocommerce_admin_process_product_object', 'save_isbn_custom_field' );
function save_isbn_custom_field( $product ) {
    if ( isset( $_POST['_book_isbn'] ) ) {
        $product->update_meta_data( '_book_isbn', sanitize_text_field( $_POST['_book_isbn'] ) );
    }
}
add_filter( 'woocommerce_catalog_orderby', 'custom_catalog_orderby' );

function custom_catalog_orderby( $sortby ) {

    $sortby = array(
        'date' => 'Od najnovije',
        'popularity' => 'Po popularnosti',
        'price' => 'Cijena od najniže',
        'price-desc' => 'Cijena od najviše',
    );

    return $sortby;
}
function books_by_author_shortcode($atts) {

$atts = shortcode_atts(array(
'author' => '',
), $atts);

$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'pa_autori',
'field' => 'name',
'terms' => $atts['author'],
),
),
);

$query = new WP_Query($args);

if ($query->have_posts()) {

$output = '<div class="author-books">';

while ($query->have_posts()) {
$query->the_post();

global $product;

$output .= '<a class="author-book" href="'.get_permalink().'">';
$output .= woocommerce_get_product_thumbnail();
$output .= '</a>';

}

$output .= '</div>';

wp_reset_postdata();

return $output;

}

}
add_shortcode('author_books', 'books_by_author_shortcode');

function woodmart_authors_shortcode() {

$brands = get_terms(array(
    'taxonomy' => 'product_brand',
    'hide_empty' => true
));

if (empty($brands) || is_wp_error($brands)) {
    return '';
}

$output = '<div class="authors-grid">';

foreach ($brands as $brand) {

    $thumbnail_id = get_term_meta($brand->term_id, 'thumbnail_id', true);
    $image = wp_get_attachment_url($thumbnail_id);
    $link = get_term_link($brand);

    $output .= '<div class="author-card">';
    $output .= '<a href="'.$link.'">';

    if ($image) {
        $output .= '<img src="'.$image.'" alt="'.$brand->name.'">';
    }

    $output .= '<h3>'.$brand->name.'</h3>';
    $output .= '</a>';

    if ($brand->description) {
        $output .= '<p>'.$brand->description.'</p>';
    }

    $output .= '</div>';

}

$output .= '</div>';

return $output;
}

add_shortcode('woodmart_authors', 'woodmart_authors_shortcode');