<?php

namespace Rtc\PlantShopWC\Admin\Modules;

use Rtc\PlantShopWC\Admin\Interfaces\ProductModule;
use WP_Post;

class MarketPrice implements ProductModule {


    public function slug(): string {
        return 'market_price';
    }

    public function label(): string {
        return __( 'Market price', 'plantshop-wc' );
    }

    public function vars(): array {
        return array(
            array( 'market_price', __( 'Market price', 'plantshop-wc' ) ),
        );
    }

    public function quick_edit_enabled(): bool {
        return false;
    }

    public function render( WP_Post $product ): void {
        $values          = $this->get( $product->ID );
        $value           = isset( $values['market_price'] ) ? $values['market_price'] : '';
        $currency_symbol = function_exists( 'get_woocommerce_currency_symbol' ) ? (string) get_woocommerce_currency_symbol() : '';
        $field_label     = $currency_symbol !== ''
            ? sprintf(
                /* translators: %s: WooCommerce currency symbol/code. */
                __( 'Market price (%s)', 'plantshop-wc' ),
                $currency_symbol
            )
            : __( 'Market price', 'plantshop-wc' );
        ?>
        <div class="plantshop-wc-fields">
            <div class="plantshop-wc-field">
                <label for="<?php echo esc_attr( 'plantshop-wc-market-price-' . $product->ID ); ?>">
                    <?php echo esc_html( $field_label ); ?>
                </label>
                <input
                    type="text"
                    id="<?php echo esc_attr( 'plantshop-wc-market-price-' . $product->ID ); ?>"
                    class="half"
                    name="plantshop-wc_tab[market_price]"
                    inputmode="decimal"
                    value="<?php echo esc_attr( $value ); ?>"
                />
            </div>
        </div>
        <?php
    }

    public function save( int $product_id, array $posted ): void {
        $raw_value = isset( $posted['market_price'] ) ? $posted['market_price'] : '';
        if ( is_array( $raw_value ) ) {
            $raw_value = '';
        }

        $normalized = str_replace( ',', '.', sanitize_text_field( wp_unslash( $raw_value ) ) );
        update_post_meta(
            $product_id,
            '_plantshop-wc_' . $this->slug(),
            array(
                'market_price' => $normalized,
            )
        );
    }

    public function get( $product_id ): array {
        $stored = get_post_meta( $product_id, '_plantshop-wc_' . $this->slug(), true );
        return is_array( $stored ) ? $stored : array();
    }
}
