<?php

if (! defined('ABSPATH')) {
    exit;
} require_once __DIR__ . '/class-puffergo-base-cpt.php';
class PufferGo_Product_CPT extends PufferGo_Base_CPT
{
    public const CPT_SLUG = 'puffergo_product';

    public const TAX_SLUG = 'puffergo_product_cat';

    public const PRODUCT_SLUG_DEFAULT = 'products';

    protected function get_module_key(): string
    {
        return 'product';
    }

    protected function get_config(): array
    {
        return ['module_key' => 'product', 'cpt_slug' => self::CPT_SLUG, 'archive_slug_option' => 'puffergo_product_slug', 'archive_slug_default' => self::PRODUCT_SLUG_DEFAULT, 'archive_slug_label' => __('Product archive base', 'puffergo'), 'menu_icon' => 'dashicons-products', 'menu_position' => 4, 'supports' => ['title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'], 'has_archive' => true, 'singular' => __('Product', 'puffergo'), 'plural' => __('Products', 'puffergo'), 'menu_label' => __('Products', 'puffergo'), 'tax_slug' => self::TAX_SLUG, 'tax_singular' => __('Product Category', 'puffergo'), 'tax_plural' => __('Product Categories', 'puffergo'), 'tax_archive_slug_option' => 'puffergo_product_category_slug', 'tax_archive_slug_default' => 'catalog', 'tax_archive_slug_label' => __('Product category base', 'puffergo'), 'tag_slug' => null, ];
    }

    protected function get_meta_fields(): array
    {
        return ['_puffergo_price' => ['type' => 'string', 'description' => __('Product Price (JSON)', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], ], '_puffergo_moq' => ['type' => 'string', 'description' => __('Minimum Order Quantity (JSON)', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], ], '_puffergo_lead_time' => ['type' => 'string', 'description' => __('Lead Time (JSON)', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], ], '_puffergo_brochure_url' => ['type' => 'string', 'description' => __('Brochure PDF URL', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => 'esc_url_raw', 'auth_callback' => [$this, 'auth_callback'], ], '_puffergo_gallery' => ['type' => 'string', 'description' => __('Product Gallery Items (Images, Videos, URLs)', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], ], '_puffergo_specs' => ['type' => 'string', 'description' => __('Product Specifications', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], 'translate' => ['*.key', '*.value'], ], '_puffergo_contact_form' => ['type' => 'string', 'description' => __('Contact Form Configuration (JSON)', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], 'translate' => ['title', 'subtitle', 'buttonText', 'successMessage', 'fields.*.label', 'fields.*.placeholder'], ], '_puffergo_cta_button' => ['type' => 'string', 'description' => __('CTA Button Configuration (JSON)', 'puffergo'), 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => [$this, 'sanitize_json_field'], 'auth_callback' => [$this, 'auth_callback'], 'translate' => ['text'], ], ];
    }

    protected function register_integrations(): void
    {
        add_filter('rank_math/snippet/rich_snippet_product_entity_types', [$this, 'rank_math_product_schema']);
    }

    protected function register_front_assets(): void
    {
        wp_register_script('puffergo-product-gallery', plugins_url('assets/js/puffergo-product-gallery.js', PUFFERGO_PLUGIN_FILE), [], PUFFERGO_CORE_VERSION, true);
    }

    protected function save_permalink_settings_extra(string $archive_slug): void
    {
        if (! class_exists('WooCommerce')) {
            return;
        } $c = $this->config;
        $tax_option = $c['tax_archive_slug_option'];
        $tax_default = $c['tax_archive_slug_default'];
        $new_tax = isset($_POST[ $tax_option ]) ? sanitize_title(wp_unslash($_POST[ $tax_option ])) : $tax_default;
        $new_tax = ! empty($new_tax) ? $new_tax : $tax_default;
        $woo_permalinks = get_option('woocommerce_permalinks', []);
        $woo_cat_slug = ! empty($woo_permalinks['category_base']) ? untrailingslashit($woo_permalinks['category_base']) : 'product-category';

        if ($new_tax === $woo_cat_slug) {
            add_settings_error('puffergo_permalinks', 'conflict', sprintf(__('"%s" is already used by WooCommerce product categories. Please choose a different slug.', 'puffergo'), esc_html($new_tax)), 'error');
            $this->abort_tax_slug_save();
        } $woo_shop_page_id = wc_get_page_id('shop');

        if ($woo_shop_page_id > 0) {
            $woo_shop_slug = get_post_field('post_name', $woo_shop_page_id);

            if ($archive_slug === $woo_shop_slug) {
                add_settings_error('puffergo_permalinks', 'conflict_shop', sprintf(__('"%s" is already used by WooCommerce shop page. Please choose a different slug.', 'puffergo'), esc_html($archive_slug)), 'error');
                $this->abort_archive_slug_save();
            }
        }
    }

    public function rank_math_product_schema($types)
    {
        $types[ self::CPT_SLUG ] = 'Product';

        return $types;
    }

    public static function get_product_slug(): string
    {
        return get_option('puffergo_product_slug', self::PRODUCT_SLUG_DEFAULT);
    }

    public static function get_category_slug(): string
    {
        return get_option('puffergo_product_category_slug', 'catalog');
    }

    public static function normalize_gallery($gallery_raw): array
    {
        $items = $gallery_raw ? json_decode($gallery_raw, true) : [];

        if (! is_array($items)) {
            return [];
        }

return array_filter($items, function ($item) { return is_array($item) && isset($item['type']); });
    }

    public static function normalize_specs($specs_raw): array
    {
        $specs = $specs_raw ? json_decode($specs_raw, true) : [];

        if (! is_array($specs)) {
            return [];
        }

return array_values(array_filter($specs, function ($s) { return is_array($s) && isset($s['key']) && $s['key'] !== ''; }));
    }

    public static function get_card_image($product_id): array
    {
        $gallery_raw = get_post_meta($product_id, '_puffergo_gallery', true);
        $gallery_items = self::normalize_gallery($gallery_raw);
        $first_item = ! empty($gallery_items) ? reset($gallery_items) : null;
        $image_id = 0;
        $is_video = false;
        $poster_id = 0;
        $video_src = '';

        if ($first_item) {
            $image_id = $first_item['id'] ?? 0;
            $is_video = in_array($first_item['type'], ['video', 'url'], true);

            if ($is_video && ! empty($first_item['poster'])) {
                $poster_id = (int) $first_item['poster'];
            }

if ($first_item['type'] === 'url') {
                $video_src = $first_item['src'] ?? '';
            } elseif ($first_item['type'] === 'video') {
                $video_src = $image_id ? wp_get_attachment_url($image_id) : '';
            }
        }

if (! $image_id && ! $is_video) {
            $image_id = get_post_thumbnail_id($product_id);
        } $display_id = $poster_id ?: $image_id;

        return ['display_id' => $display_id, 'is_video' => $is_video, 'image_id' => $image_id, 'video_src' => $video_src, ];
    }

    public static function get_card_data($product_id, $use_formatter = false): array
    {
        $card = self::get_card_image($product_id);
        $price_raw = get_post_meta($product_id, '_puffergo_price', true);
        $price_data = $price_raw ? json_decode($price_raw, true) : [];

        return ['display_id' => $card['display_id'], 'is_video' => $card['is_video'], 'price_display' => ($use_formatter && $price_data) ? PufferGo_Unit_Formatter::format($price_data, 'currency') : '', 'short_description' => get_post_field('post_excerpt', $product_id), ];
    }
}
