<?php

namespace CodeConfig\EAW\App;

use CodeConfig\EAW\Utils\Helpers;
use CodeConfig\EAW\Utils\Singleton;
use WC_Product;
defined( 'ABSPATH' ) || exit( 'No direct script access allowed' );
/**
 * GallerySlider class handles custom product gallery slider functionality
 */
class GallerySlider {
    use Singleton;
    /**
     * Initialize hooks
     *
     * @return void
     */
    public function doHooks() : void {
        if ( wp_is_block_theme() ) {
        }
        $gallery = Helpers::getSetting( 'enableGallerySlider' );
        $galleryOnShop = Helpers::getSetting( 'enableGalleryOnShop' );
        if ( $gallery == '1' ) {
            add_action( 'init', [$this, 'registerGallerySliderEndpoint'] );
            add_action( 'woocommerce_before_single_product_summary', [$this, 'renderGallerySlider'], 20 );
        }
    }

    /**
     * Configure gallery slider by removing default WooCommerce gallery features
     *
     * @return void
     */
    public function registerGallerySliderEndpoint() : void {
        $features = ['wc-product-gallery-zoom', 'wc-product-gallery-lightbox', 'wc-product-gallery-slider'];
        foreach ( $features as $feature ) {
            remove_theme_support( $feature );
        }
        remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
        remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );
        remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
        remove_action( 'woocommerce_product_thumbnails', 'woocommerce_show_product_thumbnails', 20 );
    }

    /**
     * Check if a product has a valid video attached
     *
     * @param int $product_id
     * @return bool
     */
    private function hasProductVideo( int $product_id ) : bool {
        $video_data = get_post_meta( $product_id, '_product_video_data', true );
        return is_array( $video_data ) && !empty( $video_data['type'] ) && !empty( $video_data['videoid'] );
    }

    /**
     * Render custom gallery slider
     *
     * @param bool $is_return Whether to return or echo the output
     * @return void|string
     */
    public function renderGallerySlider( $is_return = false ) {
        $product = wc_get_product( get_the_ID() );
        if ( !$product ) {
            return ( $is_return ? '' : null );
        }
        // Settings with defaults
        $settings = [
            'product_attrs'         => $this->getProductAttributes( $product ) ?? [],
            'enable_thumbnail'      => Helpers::getSetting( 'enableGalleryThumbnail' ) == '1',
            'galleryLayout'         => Helpers::getSetting( 'galleryLayoutType' ),
            'galleryThumbnailType'  => Helpers::getSetting( 'galleryThumbType' ),
            'galleryNavPosition'    => Helpers::getSetting( 'galleryNavPosition' ),
            'sliderNavBorderRadius' => Helpers::getSetting( 'sliderNavBorderRadius' ),
            'arrowColors'           => [
                'background'          => Helpers::getSetting( 'pSliderArrowBgColor' ),
                'backgroundHover'     => Helpers::getSetting( 'pSliderArrowActiveBgColor' ),
                'arrowIconColor'      => Helpers::getSetting( 'pSliderArrowIconColor' ),
                'arrowIconColorHover' => Helpers::getSetting( 'pSliderArrowIconHoverColor' ),
            ],
            'selectPaginationType'  => Helpers::getSetting( 'selectPaginationType' ),
            'paginationVisibility'  => Helpers::getSetting( 'enablePaginationVisibility' ),
            'vertical'              => Helpers::getSetting( 'galleryVertical' ),
        ];
        $images = $this->getAllImages( $product, $settings ) ?? [];
        ob_start();
        ccpeaw_get_template( 'products/single', [
            'sliderSettings' => $settings,
            'product'        => $product,
            'images'         => $images,
        ], 'product-slider' );
        $output = ob_get_clean();
        if ( $is_return ) {
            return esc_html( $output );
        }
        echo esc_html( $output );
    }

    /**
     * Get all images (featured, gallery, variation) with deduplication
     *
     * @param WC_Product $product
     * @param array $settings
     * @return array
     */
    private function getAllImages( WC_Product $product, array $settings ) : array {
        $images = [];
        $seen_urls = [];
        // Featured image
        if ( Helpers::getSetting( 'enableFeaturedImage', '1' ) == '1' ) {
            $featured = $this->getFeaturedImage( $product );
            if ( $featured && !in_array( $featured['url'], $seen_urls ) ) {
                $images[] = [
                    'id'  => $featured['id'],
                    'src' => esc_url( $featured['url'] ),
                    'alt' => esc_attr( ( $featured['caption'] ?: $product->get_name() ) ),
                ];
                $seen_urls[] = $featured['url'];
            }
        }
        // Gallery images
        if ( Helpers::getSetting( 'enableProductGallery' ) == '1' ) {
            $gallery = $this->getGalleryImages( $product );
            foreach ( $gallery as $index => $image ) {
                if ( !in_array( $image['url'], $seen_urls ) ) {
                    $images[] = [
                        'id'  => $image['id'],
                        'src' => esc_url( $image['url'] ),
                        'alt' => esc_attr( ( $image['caption'] ?: $product->get_name() ) ),
                    ];
                    $seen_urls[] = $image['url'];
                }
            }
        }
        return $images;
    }

    /**
     * Get product featured image URL with caption
     *
     * @param WC_Product $product
     * @return array|null
     */
    private function getFeaturedImage( WC_Product $product ) : ?array {
        $image_id = $product->get_image_id();
        if ( !$image_id ) {
            return null;
        }
        $image = wp_get_attachment_image_src( $image_id, 'full' );
        $caption = wp_get_attachment_caption( $image_id );
        return ( $image ? [
            'id'      => $image_id,
            'url'     => $image[0],
            'caption' => ( $caption ?: $product->get_name() ),
        ] : null );
    }

    /**
     * Get product gallery image URLs and captions
     *
     * @param WC_Product $product
     * @return array
     */
    private function getGalleryImages( WC_Product $product ) : array {
        $gallery_ids = $product->get_gallery_image_ids();
        $gallery_images = [];
        foreach ( $gallery_ids as $index => $image_id ) {
            $image = wp_get_attachment_image_src( $image_id, 'full' );
            $caption = wp_get_attachment_caption( $image_id );
            if ( $image ) {
                $gallery_images[] = [
                    'id'      => $image_id,
                    'url'     => $image[0],
                    'caption' => ( $caption ?: $product->get_name() ),
                ];
            }
        }
        return $gallery_images;
    }

    /**
     * Get product attributes with name and value
     *
     * @param WC_Product $product
     * @return array
     */
    private function getProductAttributes( WC_Product $product ) : array {
        $attributes = [];
        foreach ( $product->get_attributes() as $attribute_name => $attribute ) {
            if ( $attribute->is_taxonomy() ) {
                $terms = wp_get_post_terms( $product->get_id(), $attribute_name, [
                    'fields' => 'names',
                ] );
                $attributes[$attribute_name] = ( !empty( $terms ) ? implode( ', ', $terms ) : '' );
            } else {
                $attributes[$attribute_name] = ( $attribute->get_options() ? implode( ', ', $attribute->get_options() ) : '' );
            }
        }
        return $attributes;
    }

}
