<?php

namespace Rtc\PlantShopWC\Admin\Modules;

use Rtc\PlantShopWC\Admin\Interfaces\ProductModule;
use Rtc\PlantShopWC\Admin\Models\GeneralSettingsModel;
use WP_Post;
class PlantInstructions implements ProductModule {
    public function slug() : string {
        return 'plant_instructions';
    }

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

    public function vars() : array {
        return array(array('care', __( 'Care Instructions', 'plantshop-wc' )), array('planting', __( 'Planting Instructions', 'plantshop-wc' )));
    }

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

    public function render( WP_Post $product ) : void {
        $vars = self::vars();
        $values = self::get( $product->ID );
        ?>
        <div class="plantshop-wc-fields">
            <?php 
        foreach ( $vars as $var_data ) {
            ?>
                <?php 
            list( $var, $label ) = $var_data;
            $value = ( isset( $values[$var] ) ? $values[$var] : '' );
            ?>
                <div class="plantshop-wc-field">
                    <label for="<?php 
            echo esc_attr( 'plantshop-wc-' . $var );
            ?>">
                        <?php 
            echo esc_html( $label );
            ?>
                    </label>
                    <textarea
                        id="<?php 
            echo esc_attr( 'plantshop-wc-' . $var );
            ?>"
                        class="full big"
                        name="<?php 
            echo esc_attr( 'plantshop-wc_tab[' . $var . ']' );
            ?>"
                    ><?php 
            echo esc_textarea( $value );
            ?></textarea>
                </div>
            <?php 
        }
        ?>
        </div>
        <?php 
    }

    public function save( int $product_id, array $posted ) : void {
        $slug = self::slug();
        $vars = self::vars();
        $existing = self::get( $product_id );
        $data = ( is_array( $existing ) ? $existing : array() );
        foreach ( $vars as $var_data ) {
            $var = $var_data[0];
            if ( !array_key_exists( $var, $posted ) ) {
                continue;
            }
            $raw_value = $posted[$var];
            if ( is_array( $raw_value ) ) {
                $raw_value = '';
            }
            $data[$var] = sanitize_text_field( wp_unslash( $raw_value ) );
        }
        update_post_meta( $product_id, '_plantshop-wc_' . $slug, $data );
    }

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

}
