<?php
/**
 * WP_Products_Controller
 * نمایش محصولات WooCommerce یا پست‌نوع product وردپرس
 *
 * GET /acc/v1/wp/products          لیست محصولات (صفحه‌بندی، جستجو، دسته)
 * GET /acc/v1/wp/products/{id}     جزئیات یک محصول
 * GET /acc/v1/wp/categories        لیست دسته‌بندی‌ها
 */

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

class WP_Products_Controller {

    public static function register_routes(): void {
        $ns = 'acc/v1';
        $p  = 'acc_jwt_check_permission';

        // ── ERP (JWT) ──────────────────────────────────────
        register_rest_route( $ns, '/wp/products', [
            'methods'             => 'GET',
            'callback'            => [ self::class, 'get_products' ],
            'permission_callback' => $p,
        ] );
        register_rest_route( $ns, '/wp/products/(?P<id>\d+)', [
            'methods'             => 'GET',
            'callback'            => [ self::class, 'get_product' ],
            'permission_callback' => $p,
        ] );
        register_rest_route( $ns, '/wp/categories', [
            'methods'             => 'GET',
            'callback'            => [ self::class, 'get_categories' ],
            'permission_callback' => $p,
        ] );

        // ── PUBLIC (بدون JWT — برای صفحه عمومی فروشگاه) ───
        register_rest_route( $ns, '/public/products', [
            'methods'             => 'GET',
            'callback'            => [ self::class, 'get_products' ],
            'permission_callback' => '__return_true',
        ] );
        register_rest_route( $ns, '/public/categories', [
            'methods'             => 'GET',
            'callback'            => [ self::class, 'get_categories' ],
            'permission_callback' => '__return_true',
        ] );
        register_rest_route( $ns, '/public/products/(?P<id>\d+)', [
            'methods'             => 'GET',
            'callback'            => [ self::class, 'get_product' ],
            'permission_callback' => '__return_true',
        ] );
    }

    /* ══════════════════════════════════════════════════
       لیست محصولات
    ══════════════════════════════════════════════════ */
    public static function get_products( WP_REST_Request $req ): WP_REST_Response {
        $page     = max( 1, (int)$req->get_param('page') ?: 1 );
        $per_page = min( 100, max( 1, (int)$req->get_param('per_page') ?: 24 ) );
        $search   = sanitize_text_field( $req->get_param('search') ?? '' );
        $category = sanitize_text_field( $req->get_param('category') ?? '' );
        $orderby  = sanitize_key( $req->get_param('orderby') ?: 'date' );
        $order    = in_array( strtoupper( $req->get_param('order') ?? '' ), ['ASC','DESC'] )
                    ? strtoupper( $req->get_param('order') ) : 'DESC';

        // Cache key — فقط برای صفحات بدون جستجو
        $cache_key = 'acc_products_' . md5( "$page|$per_page|$search|$category|$orderby|$order" );
        if ( ! $search ) {
            $cached = get_transient( $cache_key );
            if ( $cached !== false ) return new WP_REST_Response( $cached );
        }

        // اگر WooCommerce فعال باشد
        $response = self::wc_active()
            ? self::_get_wc_products( $page, $per_page, $search, $category, $orderby, $order )
            : self::_get_wp_products( $page, $per_page, $search, $category, $orderby, $order );

        // ذخیره در cache — ۵ دقیقه
        if ( ! $search ) {
            set_transient( $cache_key, $response->get_data(), 5 * MINUTE_IN_SECONDS );
        }

        return $response;
    }

    public static function get_product( WP_REST_Request $req ): WP_REST_Response {
        $id = (int)$req->get_param('id');

        if ( self::wc_active() ) {
            $product = wc_get_product( $id );
            if ( ! $product ) return new WP_REST_Response( ['message' => 'یافت نشد'], 404 );
            return new WP_REST_Response( ['data' => self::_format_wc( $product )] );
        }

        $post = get_post( $id );
        if ( ! $post || $post->post_type !== 'product' ) {
            return new WP_REST_Response( ['message' => 'یافت نشد'], 404 );
        }
        return new WP_REST_Response( ['data' => self::_format_post( $post, true )] );
    }

    /* ══════════════════════════════════════════════════
       دسته‌بندی‌ها
    ══════════════════════════════════════════════════ */
    public static function get_categories( WP_REST_Request $req ): WP_REST_Response {
        $taxonomy = self::wc_active() ? 'product_cat' : 'product_cat';

        if ( ! taxonomy_exists( $taxonomy ) ) {
            return new WP_REST_Response( ['data' => []] );
        }

        // Cache دسته‌بندی‌ها — ۳۰ دقیقه
        $cache_key = 'acc_categories_' . $taxonomy;
        $cached    = get_transient( $cache_key );
        if ( $cached !== false ) return new WP_REST_Response( $cached );

        $terms = get_terms([
            'taxonomy'   => $taxonomy,
            'hide_empty' => false,
            'orderby'    => 'name',
            'order'      => 'ASC',
        ]);

        if ( is_wp_error( $terms ) ) {
            return new WP_REST_Response( ['data' => []] );
        }

        $cats = array_map( function( $term ) {
            $thumb_id  = function_exists('get_term_meta') 
                ? get_term_meta( $term->term_id, 'thumbnail_id', true )
                : null;

            $thumb_url = null;
            if ( $thumb_id ) {
                if ( function_exists( 'wp_get_attachment_image_url' ) ) {
                    $thumb_url = wp_get_attachment_image_url( $thumb_id, 'thumbnail' );
                } elseif ( function_exists( 'wp_get_attachment_url' ) ) {
                    $thumb_url = wp_get_attachment_url( $thumb_id );
                }
            }

            return [
                'id'          => $term->term_id,
                'slug'        => $term->slug,
                'name'        => $term->name,
                'count'       => (int)$term->count,
                'parent'      => (int)$term->parent,
                'description' => $term->description ?? '',
                'image'       => $thumb_url,
            ];
        }, $terms );

        $result = ['data' => $cats];
        set_transient( $cache_key, $result, 30 * MINUTE_IN_SECONDS );
        return new WP_REST_Response( $result );
    }

    /* ══════════════════════════════════════════════════
       WooCommerce helpers
    ══════════════════════════════════════════════════ */
    private static function wc_active(): bool {
        return class_exists( 'WooCommerce' );
    }

    private static function _product_permalink( int $id ): string {
        if ( function_exists( 'get_permalink' ) ) {
            $url = get_permalink( $id );
            if ( $url ) return $url;
        }
        $base = defined( 'ACC_URL' ) ? ACC_URL : '/acc-engine/';
        return rtrim( $base, '/' ) . '/shop.php?product=' . $id;
    }

    private static function _get_wc_products(
        int $page, int $per_page, string $search,
        string $category, string $orderby, string $order
    ): WP_REST_Response {

        $args = [
            'status'      => 'publish',
            'limit'       => $per_page,
            'page'        => $page,
            'orderby'     => $orderby,
            'order'       => $order,
            'paginate'    => true,
        ];

        if ( $search )   $args['s']        = $search;
        if ( $category ) $args['category']  = [ $category ];

        $result   = wc_get_products( $args );
        $products = array_map( [self::class, '_format_wc'], $result->products );

        return new WP_REST_Response([
            'data'        => $products,
            'total'       => (int)$result->total,
            'total_pages' => (int)$result->max_num_pages,
            'page'        => $page,
            'per_page'    => $per_page,
            'source'      => 'woocommerce',
        ]);
    }

    private static function _format_wc( $product ): array {
        $image_id  = $product->get_image_id();
        $image_url = $image_id
            ? wp_get_attachment_image_url( $image_id, 'woocommerce_thumbnail' )
            : wc_placeholder_img_src( 'woocommerce_thumbnail' );

        $gallery = array_map( function( $gid ) {
            return wp_get_attachment_image_url( $gid, 'woocommerce_thumbnail' );
        }, $product->get_gallery_image_ids() );

        $cats = array_map( function( $term ) {
            return [ 'id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug ];
        }, wc_get_product_category_list( $product->get_id(), '|', '', false )
            ? (array)wp_get_post_terms( $product->get_id(), 'product_cat' )
            : [] );

        $rating_count = $product->get_rating_count();
        $avg_rating   = $product->get_average_rating();

        $on_sale    = $product->is_on_sale();
        $in_stock   = $product->is_in_stock();
        $stock_qty  = $product->get_stock_quantity();

        return [
            'id'             => $product->get_id(),
            'name'           => $product->get_name(),
            'slug'           => $product->get_slug(),
            'permalink'      => get_permalink( $product->get_id() ),
            'description'    => wp_strip_all_tags( $product->get_description() ),
            'short_desc'     => wp_strip_all_tags( $product->get_short_description() ),
            'sku'            => $product->get_sku(),
            'price'          => $product->get_price(),
            'regular_price'  => $product->get_regular_price(),
            'sale_price'     => $product->get_sale_price(),
            'price_html'     => $product->get_price_html(),
            'on_sale'        => $on_sale,
            'in_stock'       => $in_stock,
            'stock_qty'      => $stock_qty,
            'stock_status'   => $product->get_stock_status(),
            'image'          => $image_url,
            'gallery'        => $gallery,
            'categories'     => $cats,
            'tags'           => wp_get_post_terms( $product->get_id(), 'product_tag', ['fields' => 'names'] ),
            'rating_count'   => $rating_count,
            'average_rating' => $avg_rating,
            'type'           => $product->get_type(),
            'date'           => $product->get_date_created()?->date('Y-m-d') ?? '',
        ];
    }

    /* ══════════════════════════════════════════════════
       WordPress CPT helpers (بدون WooCommerce)
    ══════════════════════════════════════════════════ */
    private static function _get_wp_products(
        int $page, int $per_page, string $search,
        string $category, string $orderby, string $order
    ): WP_REST_Response {

        // map orderby
        $wp_orderby = match( $orderby ) {
            'price'   => 'meta_value_num',
            'title'   => 'title',
            default   => 'date',
        };

        $args = [
            'post_type'      => 'product',
            'post_status'    => 'publish',
            'posts_per_page' => $per_page,
            'paged'          => $page,
            'orderby'        => $wp_orderby,
            'order'          => $order,
        ];

        if ( $search )   $args['s']               = $search;
        if ( $category ) $args['product_cat']      = $category;
        if ( $orderby === 'price' ) $args['meta_key'] = '_price';

        $query    = new WP_Query( $args );
        $products = array_map( [self::class, '_format_post'], $query->posts );

        return new WP_REST_Response([
            'data'        => $products,
            'total'       => (int)$query->found_posts,
            'total_pages' => (int)$query->max_num_pages,
            'page'        => $page,
            'per_page'    => $per_page,
            'source'      => 'wordpress',
        ]);
    }

        private static function _format_post( WP_Post $post, bool $full = false ): array {
        $image_id  = 0;
        $image_url = null;

        if ( function_exists( 'get_post_thumbnail_id' ) ) {
            $image_id = (int) get_post_thumbnail_id( $post->ID );
        } elseif ( function_exists( 'get_post_meta' ) ) {
            $image_id = (int) get_post_meta( $post->ID, '_thumbnail_id', true );
        }

        if ( $image_id > 0 ) {
            if ( function_exists( 'wp_get_attachment_image_url' ) ) {
                $image_url = wp_get_attachment_image_url( $image_id, 'medium' );
            } elseif ( function_exists( 'wp_get_attachment_url' ) ) {
                $image_url = wp_get_attachment_url( $image_id );
            }
        }

        $price         = function_exists('get_post_meta') ? get_post_meta( $post->ID, '_price', true ) : null;
        $regular_price = function_exists('get_post_meta') ? get_post_meta( $post->ID, '_regular_price', true ) : null;
        $sale_price    = function_exists('get_post_meta') ? get_post_meta( $post->ID, '_sale_price', true ) : null;
        $sku           = function_exists('get_post_meta') ? get_post_meta( $post->ID, '_sku', true ) : null;
        $stock_qty     = function_exists('get_post_meta') ? get_post_meta( $post->ID, '_stock', true ) : null;
        $stock_status  = function_exists('get_post_meta') ? get_post_meta( $post->ID, '_stock_status', true ) : 'instock';

        $raw_cats = function_exists('wp_get_post_terms') 
            ? wp_get_post_terms( $post->ID, 'product_cat' ) 
            : [];

        $cats = array_map( function( $term ) {
            // هندل کردن حالت‌هایی که خروجی به صورت آرایه آرایه‌ها یا آرایه‌ای از اشیاء است
            if ( is_array( $term ) ) {
                return [
                    'id'   => isset($term['term_id']) ? (int)$term['term_id'] : (isset($term['ID']) ? (int)$term['ID'] : 0),
                    'name' => $term['name'] ?? '',
                    'slug' => $term['slug'] ?? '',
                ];
            } elseif ( is_object( $term ) ) {
                return [
                    'id'   => (int)($term->term_id ?? 0),
                    'name' => $term->name ?? '',
                    'slug' => $term->slug ?? '',
                ];
            }
            return [ 'id' => 0, 'name' => '', 'slug' => '' ];
        }, is_array( $raw_cats ) ? $raw_cats : [] );

        // تمیز کردن ایمن متون
        $description = function_exists('wp_strip_all_tags') 
            ? wp_strip_all_tags( $post->post_content ) 
            : strip_tags( $post->post_content );

        $short_desc = function_exists('wp_strip_all_tags') 
            ? wp_strip_all_tags( $post->post_excerpt ) 
            : strip_tags( $post->post_excerpt );

        $data = [
            'id'             => $post->ID,
            'name'           => $post->post_title,
            'slug'           => $post->post_name,
            'permalink'      => self::_product_permalink( $post->ID ),
            'description'    => $description,
            'short_desc'     => $short_desc,
            'sku'            => $sku,
            'price'          => $price,
            'regular_price'  => $regular_price ?: $price,
            'sale_price'     => $sale_price,
            'on_sale'        => ( $sale_price && $sale_price < $regular_price ),
            'in_stock'       => $stock_status !== 'outofstock',
            'stock_qty'      => $stock_qty !== '' ? (int)$stock_qty : null,
            'stock_status'   => $stock_status,
            'image'          => $image_url,
            'gallery'        => [],
            'categories'     => $cats,
            'tags'           => [],
            'rating_count'   => 0,
            'average_rating' => '0',
            'type'           => 'simple',
            'date'           => $post->post_date,
        ];

        // برچسب‌ها
        if ( function_exists('wp_get_post_terms') ) {
            $data['tags'] = wp_get_post_terms( $post->ID, 'product_tag', ['fields' => 'names'] );
        }

        // گالری تصاویر
        if ( $full ) {
            $gallery_meta = function_exists('get_post_meta') 
                ? get_post_meta( $post->ID, '_product_image_gallery', true ) 
                : '';

            $gallery_ids = $gallery_meta ? explode( ',', $gallery_meta ) : [];

            $data['gallery'] = array_values( array_filter( array_map( function( $mid ) {
                $mid = (int) $mid;

                if ( $mid <= 0 ) {
                    return null;
                }

                if ( function_exists( 'wp_get_attachment_image_url' ) ) {
                    return wp_get_attachment_image_url( $mid, 'medium' );
                }

                if ( function_exists( 'wp_get_attachment_url' ) ) {
                    return wp_get_attachment_url( $mid );
                }

                return null;
            }, $gallery_ids ) ) );
        }

        return $data;
    }

}
