<?php
namespace GSW\Core;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Builds lightweight source previews for import editors without any PRO-only
 * routing or exclusion behavior.
 */
class Source_Preview
{
    private const PREVIEW_LIMIT            = 100;
    private const PREVIEW_ALLOWED_STATUSES = [ 'in_stock', 'sale', 'waiting' ];

    public static function preview_rows( array $cfg, string $row_id = '', int $limit = self::PREVIEW_LIMIT, int $page = 1 ): array
    {
        $limit = max( 1, $limit );
        $page  = max( 1, $page );

        $cfg['skip_logging'] = true;
        $res                 = Import_CSV_Data::fetch_minimal( $cfg );

        if ( ! empty( $res['error'] ) ) {
            return [
                'items'        => [],
                'error'        => (string) $res['error'],
                'matched'      => 0,
                'shown'        => 0,
                'shown_from'   => 0,
                'shown_to'     => 0,
                'current_page' => 1,
                'total_pages'  => 1,
                'per_page'     => $limit,
                'is_limited'   => false,
                'default_cat'  => self::term_path_label( (int) ( $cfg['category'] ?? 0 ) ),
            ];
        }

        $items             = [];
        $matched           = 0;
        $offset            = ( $page - 1 ) * $limit;
        $stock_status      = new Stock_Status();
        $default_category  = (int) ( $cfg['category'] ?? 0 );
        $default_cat_label = self::term_path_label( $default_category );

        foreach ( (array) ( $res['items'] ?? [] ) as $src ) {
            if ( ! is_array( $src ) ) {
                continue;
            }

            $sku = sanitize_text_field( (string) ( $src['sku'] ?? '' ) );
            if ( '' === $sku ) {
                continue;
            }

            $status = $stock_status->resolve_status( (string) ( $src['status_text'] ?? '' ) );
            if ( ! in_array( $status, self::PREVIEW_ALLOWED_STATUSES, true ) ) {
                continue;
            }

            $matched++;
            if ( $matched <= $offset ) {
                continue;
            }

            if ( count( $items ) >= $limit ) {
                continue;
            }

            $product_id         = function_exists( 'wc_get_product_id_by_sku' ) ? (int) wc_get_product_id_by_sku( $sku ) : 0;
            $has_thumbnail      = self::has_product_thumbnail( $product_id );
            $local_thumb_url    = self::preview_thumbnail_url( $product_id, 'thumbnail', false );
            $local_lightbox_url = self::preview_thumbnail_url( $product_id, 'large', false );
            $source_thumb_url   = '';

            if ( ! $has_thumbnail && ! empty( $cfg['use_images'] ) && ! empty( $src['images_folder'] ) ) {
                $source_thumb_url = self::source_preview_url( $row_id, (string) $src['images_folder'] );
            }

            $thumbnail_url = $local_thumb_url;
            if ( '' === $thumbnail_url ) {
                $thumbnail_url = '' !== $source_thumb_url
                    ? $source_thumb_url
                    : self::preview_thumbnail_url( 0, 'thumbnail', true );
            }

            $lightbox_url = '' !== $local_lightbox_url ? $local_lightbox_url : $source_thumb_url;

            $items[] = [
                'row_index'                => (int) ( $src['row_index'] ?? 0 ),
                'sku'                      => $sku,
                'title'                    => sanitize_text_field( (string) ( $src['title'] ?? '' ) ),
                'status'                   => $status,
                'status_label'             => self::status_label( $status ),
                'thumbnail_url'            => $thumbnail_url,
                'lightbox_url'             => $lightbox_url,
                'has_thumbnail'            => $has_thumbnail,
                'has_source_preview'       => '' !== $source_thumb_url,
                'can_open_lightbox'        => '' !== $lightbox_url,
                'product_categories_label' => self::product_categories_label( $product_id ),
                'default_term_label'       => $default_cat_label,
            ];
        }

        $shown       = count( $items );
        $total_pages = max( 1, (int) ceil( $matched / $limit ) );

        if ( $matched > 0 && $page > $total_pages ) {
            return self::preview_rows( $cfg, $row_id, $limit, $total_pages );
        }

        $shown_from = $shown > 0 ? $offset + 1 : 0;
        $shown_to   = $shown > 0 ? $offset + $shown : 0;

        return [
            'items'        => $items,
            'error'        => '',
            'matched'      => $matched,
            'shown'        => $shown,
            'shown_from'   => $shown_from,
            'shown_to'     => $shown_to,
            'current_page' => $page,
            'total_pages'  => $total_pages,
            'per_page'     => $limit,
            'is_limited'   => $matched > $shown,
            'default_cat'  => $default_cat_label,
        ];
    }

    public static function term_path_label( int $term_id ): string
    {
        if ( $term_id <= 0 || ! taxonomy_exists( 'product_cat' ) ) {
            return __( '(no category)', DITSGSW_TEXT_DOMAIN );
        }

        $term = get_term( $term_id, 'product_cat' );
        if ( ! $term || is_wp_error( $term ) ) {
            return '#' . $term_id;
        }

        $labels = [];
        $ids    = array_reverse( array_map( 'intval', get_ancestors( $term_id, 'product_cat', 'taxonomy' ) ) );
        $ids[]  = $term_id;

        foreach ( $ids as $id ) {
            $node = get_term( $id, 'product_cat' );
            if ( $node && ! is_wp_error( $node ) ) {
                $labels[] = $node->name;
            }
        }

        if ( empty( $labels ) ) {
            return '#' . $term_id;
        }

        return implode( ' -> ', $labels );
    }

    public static function term_path_labels( array $term_ids ): array
    {
        $labels = [];
        foreach ( array_values( array_unique( array_filter( array_map( 'intval', $term_ids ) ) ) ) as $term_id ) {
            $labels[] = self::term_path_label( $term_id );
        }

        return $labels;
    }

    public static function expand_term_ids( int $term_id ): array
    {
        if ( $term_id <= 0 || ! taxonomy_exists( 'product_cat' ) ) {
            return [];
        }

        $term = get_term( $term_id, 'product_cat' );
        if ( ! $term || is_wp_error( $term ) ) {
            return [];
        }

        $ids = array_reverse( array_map( 'intval', get_ancestors( $term_id, 'product_cat', 'taxonomy' ) ) );
        $ids[] = $term_id;

        return array_values( array_unique( array_filter( $ids ) ) );
    }

    protected static function preview_thumbnail_url( int $product_id, string $size = 'thumbnail', bool $fallback = true ): string
    {
        if ( $product_id > 0 ) {
            $thumb = get_the_post_thumbnail_url( $product_id, $size );
            if ( is_string( $thumb ) && '' !== $thumb ) {
                return $thumb;
            }
        }

        if ( $fallback && function_exists( 'wc_placeholder_img_src' ) ) {
            return (string) wc_placeholder_img_src( $size );
        }

        return '';
    }

    protected static function has_product_thumbnail( int $product_id ): bool
    {
        return $product_id > 0 && function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( $product_id );
    }

    protected static function source_preview_url( string $row_id, string $folder_spec ): string
    {
        $folder_spec = trim( $folder_spec );
        if ( '' === $folder_spec ) {
            return '';
        }

        $url = add_query_arg(
            [
                'action' => 'gsw_source_image_preview',
                'row_id' => $row_id,
                'folder' => $folder_spec,
            ],
            admin_url( 'admin-ajax.php' )
        );

        return wp_nonce_url( $url, 'gsw_source_image_preview', 'nonce' );
    }

    protected static function product_categories_label( int $product_id ): string
    {
        if ( $product_id <= 0 || ! taxonomy_exists( 'product_cat' ) ) {
            return '';
        }

        $terms = wp_get_post_terms( $product_id, 'product_cat' );
        if ( is_wp_error( $terms ) || empty( $terms ) ) {
            return '';
        }

        $names = [];
        foreach ( $terms as $term ) {
            if ( isset( $term->name ) && '' !== $term->name ) {
                $names[] = $term->name;
            }
        }

        return implode( ', ', array_unique( $names ) );
    }

    protected static function status_label( string $status ): string
    {
        switch ( $status ) {
            case 'sale':
                return __( 'Sale', DITSGSW_TEXT_DOMAIN );
            case 'waiting':
                return __( 'Waiting', DITSGSW_TEXT_DOMAIN );
            case 'in_stock':
                return __( 'In stock', DITSGSW_TEXT_DOMAIN );
            case 'sold':
                return __( 'Sold', DITSGSW_TEXT_DOMAIN );
            default:
                return __( 'Unknown', DITSGSW_TEXT_DOMAIN );
        }
    }
}
