<?php

function panda_enqueue_styles() {
    $ver = '1.0';
    $base = get_template_directory_uri() . '/assets/';

    /*wp_enqueue_style('panda-style', get_stylesheet_uri());
    wp_enqueue_style('panda-mobile',  $base . '/css/mobile.css',  ['panda-style'], $ver);
    wp_enqueue_style('panda-tablet',  $base . '/css/tablet.css',  ['panda-mobile'], $ver);
    wp_enqueue_style('panda-desktop', $base . '/css/desktop.css', ['panda-tablet'], $ver);*/

    wp_enqueue_style( 'panda-main', $base . '/css/main.css', [], $ver );

    wp_enqueue_script('categories-hover', $base . '/js/categories-hover.js', array(), null, true);
    wp_enqueue_script('dropcat', $base . '/js/dropcat.js', array(), null, true);
    wp_enqueue_script('shop-links', $base . '/js/shop-links.js', array(), null, true);
    wp_localize_script( 'shop-links', 'pandaThemeVars', [
        'shopUrl' => get_permalink( wc_get_page_id( 'shop' ) )
    ] );
}
add_action('wp_enqueue_scripts', 'panda_enqueue_styles');

// WooCommerce support
add_action('after_setup_theme', function () {
    add_theme_support('woocommerce');
});


// Search bar
add_action( 'wp_ajax_live_search', 'panda_live_search' );
add_action( 'wp_ajax_nopriv_live_search', 'panda_live_search' );
function panda_live_search() { 
    if ( empty( $_GET['term'] ) ) {
        wp_send_json( [] );
    }
    $term = sanitize_text_field( wp_unslash( $_GET['term'] ) );

    $args = [
        'post_type'      => 'product',
        'posts_per_page' => 5,
        's'              => $term,
        'post_status'    => 'publish',
    ];
    $query = new WP_Query( $args );
    $results = [];

    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            $results[] = [
                'title'     => get_the_title(),
                'permalink' => get_permalink(),
                'thumb'     => get_the_post_thumbnail_url( get_the_ID(), 'thumbnail' ),
            ];
        }
        wp_reset_postdata();
    }

    wp_send_json( $results );
}

add_action( 'wp_enqueue_scripts', function(){
    wp_enqueue_script(
        'panda-live-search',
        get_template_directory_uri() . '/assets/js/live-search.js',
        [ 'jquery' ],
        '1.0',
        true
    );
    wp_localize_script( 'panda-live-search', 'pandaLiveSearch', [
        'ajax_url' => admin_url( 'admin-ajax.php' ),
    ] );
});


// Slider
add_action( 'wp_enqueue_scripts', 'enqueue_slick_slider_assets' );
function enqueue_slick_slider_assets() {
    wp_enqueue_style( 'slick-css', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css', array(), '1.8.1' );
    wp_enqueue_style( 'slick-theme-css', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick-theme.css', array('slick-css'), '1.8.1' );
    wp_enqueue_script( 'slick-js', 'https://cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js', array('jquery'), '1.8.1', true );
    wp_enqueue_script( 'my-slider-init', get_stylesheet_directory_uri() . '/assets/js/product-slider.js', array('slick-js'), '1.0', true );
}

add_shortcode( 'product_slider', 'render_product_slider' );
function render_product_slider( $atts ) {
    $atts = shortcode_atts( array(
        'limit'   => 6,
        'orderby' => 'rand',
    ), $atts, 'product_slider' );

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => intval( $atts['limit'] ),
        'orderby'        => sanitize_text_field( $atts['orderby'] ),
        'post_status'    => 'publish',
    );
    $loop = new WP_Query( $args );


    wp_enqueue_script("slider-images-js", plugins_url("/pandaGadzety/assets/js/slider-images.js"), [], null, true);

    $productData = [];

    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) {
            $loop->the_post();
            global $product;
            $sku = $product->get_sku();

            if ( $sku ) {
                try {
                    $info = (new \Foxstudio\Plugins\Template\Repository\ProductRepository(SERVER_URL))->getProductInfo($sku);
                    if (!empty($info['message'])) {
                        $productData[$sku] = [
                            'img' => $info['message']['productBaseInfo']['primary_img'] ?? null,
                        ];
                    }
                } catch (\Throwable $e) {
                }
            }
        }
        wp_localize_script("slider-images-js", "archiveImagesData", [
            'products' => $productData
        ]);
        wp_reset_postdata();
    }



    if ( ! $loop->have_posts() ) {
        return '<p>Brak produktów.</p>';
    }

    
    ?>
    <div class="product-slider" >
        <?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
            <div class="slide-item" data-sku="<?php echo esc_attr( $product->get_sku() ); ?>">     
                <?php echo woocommerce_get_product_thumbnail(); ?>
                <div class="slide-item__text">
                    <h2><?php the_title(); ?></h2>
                    <p class="slide-item__description"><?php echo $product->get_short_description(); ?></p>
                    <span class="slide-item__price">Od <?php echo $product->get_price_html(); ?></span>
                    <a href="<?php the_permalink(); ?>" class="btn-primary">Zobacz produkt</a>
                </div>
            </div>
        <?php endwhile; ?>
    </div>
    <?php
    
}


add_shortcode( 'related_products_slider', function( $atts ) {
    $limit = isset( $atts['limit'] ) ? intval( $atts['limit'] ) : 4;
    $related = wc_get_related_products( get_the_ID(), $limit );
    if ( empty( $related ) ) {
        return '<p>Brak podobnych produktów.</p>';
    }

    return do_shortcode( '[product_slider ids="' . implode( ',', $related ) . '" limit="' . $limit . '" orderby="post__in"]' );
} );



// landing page slider

add_shortcode( 'hero_slider', 'panda_render_hero_slider' );
function panda_render_hero_slider( $atts ) {
    $slides = [
        get_template_directory_uri() . '/assets/images/slide1.png',
        get_template_directory_uri() . '/assets/images/slide2.png',
        get_template_directory_uri() . '/assets/images/slide3.png',
    ];
    ob_start();
    ?>
    <section class="hero-uv">
      <div class="hero-uv__inner">
        <div class="hero-uv__text">
          <h2>Nowa kolekcja kubków<br><strong>z nadrukiem UV</strong></h2>
          <p>Dodaj na kubek logo z Twoim ulubionym nadrukiem.</p>
          <a href="<?php echo esc_url( wc_get_page_permalink( 'shop' ) ); ?>" class="btn-primary">Zobacz produkty</a>
        </div>
        <div class="hero-uv__slider">
          <?php foreach ( $slides as $src ): ?>
            <div class="hero-uv__slide">
              <img src="<?php echo esc_url( $src ); ?>" alt="">
            </div>
          <?php endforeach; ?>
        </div>
      </div>
    </section>
    <?php
    return ob_get_clean();
}


// widget for shop
function register_shop_sidebar() {
  register_sidebar( array(
    'name'          => 'Shop Filters',
    'id'            => 'shop-filters',
    'before_widget' => '<div class="widget %2$s">',
    'after_widget'  => '</div>',
    'before_title'  => '<h2 class="widget-title">',
    'after_title'   => '</h2>',
  ) );
}
add_action( 'widgets_init', 'register_shop_sidebar' );

// breadcrumbs separator change
add_filter( 'woocommerce_breadcrumb_defaults', 'my_change_breadcrumb_separator' );
function my_change_breadcrumb_separator( $defaults ) {
    $defaults['delimiter'] = ' <span class="breadcrumb-sep">&gt;</span> ';
    return $defaults;
}

// changing cart button on product to see product
/*add_filter( 'woocommerce_loop_add_to_cart_link', 'panda_replace_add_to_cart_with_view_product', 10, 2 );
function panda_replace_add_to_cart_with_view_product( $button_html, $product ) {
    $url   = $product->get_permalink();
    $label = esc_html__( 'Zobacz produkt', 'panda-theme' );
    $classes = 'view-product';

    return sprintf(
        '<a href="%1$s" class="%2$s">%3$s</a>',
        esc_url( $url ),
        esc_attr( $classes ),
        $label
    );
}*/

// Wstawianie własnego „Zobacz produkt” w pętli po produktach
add_action( 'woocommerce_after_shop_loop_item', 'panda_replace_add_to_cart_with_view_product', 10 );

function panda_replace_add_to_cart_with_view_product() {
    global $product;
    $url     = $product->get_permalink();
    $label   = esc_html__( 'Zobacz produkt', 'panda-theme' );
    $classes = 'view-product';

    printf(
        '<a href="%1$s" class="%2$s">%3$s</a>',
        esc_url( $url ),
        esc_attr( $classes ),
        $label
    );
}


add_action('wp_enqueue_scripts', function() {
    if ( is_shop() || is_product_category() ) {
        wp_enqueue_script("slider-images-js", plugins_url("/pandaGadzety/assets/js/slider-images.js"), [], null, true);

        global $wp_query;

        $productData = [];

        foreach ( $wp_query->posts as $post ) {
            $product = wc_get_product( $post->ID );
            if ( ! $product ) continue;

            $sku = $product->get_sku();

            if ( $sku ) {
                try {
                    $info = (new \Foxstudio\Plugins\Template\Repository\ProductRepository(SERVER_URL))->getProductInfo($sku);
                    if (!empty($info['message'])) {
                        $productData[$sku] = [
                            'img' => $info['message']['productBaseInfo']['primary_img'] ?? null,
                        ];
                    }
                } catch (\Throwable $e) {}
            }
        }

        wp_localize_script("slider-images-js", "archiveImagesData", [
            'products' => $productData
        ]);
    }
});
