<?php

namespace Rtc\PlantShopWC\Admin\Models;

use Rtc\PlantShopWC\Admin\Modules\BotanicalName;
use Rtc\PlantShopWC\Admin\Modules\MarketPrice;
use Rtc\PlantShopWC\Admin\Modules\PlantPassport;
use Rtc\PlantShopWC\Admin\Modules\Plot;
use WC_Order_Item_Product;
use WC_Product;
use WP_Query;
class GeneralSettingsModel {
    public static function get_option_key() : string {
        return 'plantshop-wc_settings';
    }

    public function get_settings() : array {
        $data['disabled_cats'] = array(
            'callback'    => 'render_disabled_cats',
            'label'       => __( 'Excluded categories', 'plantshop-wc' ),
            'description' => __( 'Exclude categories from plugin.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => self::get_product_categories(),
        );
        $data['enable_equivalent_replacement'] = array(
            'callback'    => 'render_toggle',
            'label'       => __( 'Equivalent replacement', 'plantshop-wc' ),
            'description' => __( 'Enable customers to consent to equivalent replacements during checkout. ', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        // URL to an information page about equivalent replacements shown on checkout.
        $data['equivalent_replacement_info_url'] = array(
            'callback'    => 'render_equivalent_replacement_info_url',
            'label'       => __( 'Equivalent replacement info link', 'plantshop-wc' ),
            'description' => __( 'Optional. If set, a "Learn more" link will be shown next to the equivalent replacement consent on checkout.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        $data['botanical_name_replacement'] = array(
            'callback'    => 'render_toggle',
            'label'       => __( 'Botanical Name', 'plantshop-wc' ),
            'description' => __( 'Globally switch Product Title with Botanical Name.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        $data['enable_frontend_bed_sorting'] = array(
            'callback'    => 'render_toggle',
            'label'       => __( 'Frontend bed sorting', 'plantshop-wc' ),
            'description' => __( 'Sort cart and checkout line items by bed number in the frontend.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        $data['show_frontend_bed_number'] = array(
            'callback'    => 'render_toggle',
            'label'       => __( 'Frontend bed number display', 'plantshop-wc' ),
            'description' => __( 'Show the bed number on frontend cart and checkout line items.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        // Shipping periods feature toggle
        $data['enable_shipping_periods'] = array(
            'callback'    => 'render_toggle',
            'label'       => __( 'Shipping periods', 'plantshop-wc' ),
            'description' => __( 'Enable customers to choose a shipping week during checkout. Configure allowed weeks below.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        // Shipping week ranges configuration
        $data['shipping_week_ranges'] = array(
            'callback'    => 'render_shipping_week_ranges',
            'label'       => __( 'Allowed shipping weeks', 'plantshop-wc' ),
            'description' => __( 'Define allowed shipping weeks. One entry per line. Examples: "W12", "W12-W16". You can mix single weeks and ranges.', 'plantshop-wc' ),
            'class'       => 'setting',
            'data'        => '',
        );
        return $data;
    }

    public function get_product_categories() : array {
        $terms = get_terms( array(
            'taxonomy'   => 'product_cat',
            'hide_empty' => false,
        ) );
        return ( is_wp_error( $terms ) ? array() : $terms );
    }

    public static function search_products( string $term, int $limit = 10 ) : array {
        $args = array(
            'post_type'      => 'product',
            'post_status'    => 'publish',
            's'              => $term,
            'posts_per_page' => $limit,
            'orderby'        => 'relevance',
        );
        $q = new WP_Query($args);
        $items = array();
        foreach ( $q->posts as $product ) {
            $items[] = array(
                'id'    => (int) $product->ID,
                'title' => html_entity_decode( get_the_title( $product ), ENT_NOQUOTES, 'UTF-8' ),
            );
        }
        return $items;
    }

    public static function is_product_included( WC_Product|WC_Order_Item_Product|int $product ) : bool {
        if ( $product instanceof WC_Order_Item_Product ) {
            $product_id = $product->get_product_id();
        } elseif ( $product instanceof WC_Product ) {
            $product_id = $product->get_id();
        } elseif ( is_int( $product ) ) {
            $product_id = $product;
        } else {
            return false;
        }
        $product = ( $product instanceof WC_Product ? $product : wc_get_product( $product_id ) );
        if ( !$product ) {
            return false;
        }
        $option = get_option( 'plantshop-wc_settings', array() );
        $product_cat_ids = wp_get_post_terms( $product->get_id(), 'product_cat', array(
            'fields' => 'ids',
        ) );
        $enabled_cats = $option['disabled_cats'];
        return empty( array_intersect( $enabled_cats ?? array(), $product_cat_ids ?? array() ) );
    }

    public static function get_product_print_data( int $product_id, string $label_type ) : array {
        $product = wc_get_product( $product_id );
        if ( !$product || $product->get_status() !== 'publish' ) {
            return array();
        }
        $parent_product_id = $product->get_parent_id( 'edit' );
        $parent_product = wc_get_product( $parent_product_id );
        $symbol = html_entity_decode( get_woocommerce_currency_symbol(), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
        $parts = self::resolve_botanical_parts__premium_only( $product_id, $parent_product_id );
        $title = self::get_botanical_name_from_product_id( $product_id, $parent_product_id );
        $sku = $product->get_sku() ?? $parent_product?->get_sku() ?? '';
        $price = $product->get_price() ?? $parent_product?->get_price() ?? '';
        $market_price_data = ( new MarketPrice() )->get( $product_id );
        $parent_market_price_data = ( new MarketPrice() )->get( $parent_product_id );
        $market_price = $market_price_data['market_price'] ?? $parent_market_price_data['market_price'] ?? '';
        $product_ean = self::resolve_product_ean__premium_only( $product, $parent_product );
        $data = array(
            'title'        => $title,
            'price'        => self::format_money_value__premium_only( (string) $price, $symbol ),
            'market_price' => self::format_money_value__premium_only( (string) $market_price, $symbol ),
            'sku'          => ( $sku !== '' ? $sku : (string) $product_id ),
            'product_ean'  => $product_ean,
            'genus'        => $parts['genus'],
            'species'      => $parts['species'],
            'variety'      => $parts['variety'],
        );
        $data['vernacular'] = $parts['vernacular'];
        $data['subtitle'] = self::build_product_subtitle__premium_only( $parts['species'], $parts['variety'] );
        $data['category'] = self::resolve_product_category_term__premium_only( $product_id );
        $data['url'] = get_permalink( $product_id );
        $data['product_url'] = $data['url'];
        $plot_data = ( new Plot() )->get( $product_id );
        $parent_plot_data = ( new Plot() )->get( $parent_product_id );
        $data['description'] = $plot_data['plot_description'] ?? $parent_plot_data['plot_description'] ?? '';
        $data['bed'] = $plot_data['bed_number'] ?? $parent_plot_data['bed_number'] ?? '';
        $data = array_merge( $data, self::resolve_traceability_data__premium_only( $product_id, $parent_product_id ) );
        if ( $label_type === 'packing-list' ) {
            $data['title'] = self::resolve_packing_list_title__premium_only( $data['title'], $product, $parent_product );
        }
        $data['origin_country'] = self::resolve_origin_country_fallback__premium_only( (string) $data['origin_country'], (string) ($product->get_meta( 'origin_country' ) ?? $parent_product?->get_meta( 'origin_country' ) ?? '') );
        return $data;
    }

    public static function get_botanical_name_from_product_id( int $product_id, int $parent_product_id = 0 ) : string {
        if ( $product_id <= 0 ) {
            return '';
        }
        if ( $parent_product_id <= 0 ) {
            $parent_product_id = (int) wp_get_post_parent_id( $product_id );
            if ( $parent_product_id <= 0 && function_exists( 'wc_get_product' ) ) {
                $product = wc_get_product( $product_id );
                if ( $product ) {
                    $parent_product_id = (int) $product->get_parent_id( 'edit' );
                }
            }
        }
        $parts = self::resolve_botanical_parts__premium_only( $product_id, $parent_product_id );
        return self::build_product_title_with_parts__premium_only(
            $product_id,
            (string) $parts['genus'],
            (string) $parts['species'],
            (string) $parts['variety']
        );
    }

}
