<?php
/**
 * Author: Rymera Web Co.
 *
 * @package SAAI\Classes
 */

namespace SAAI\Classes;

use SAAI\AI_Agents\Product_Description_AI;

/**
 * Product_Description class.
 *
 * @since 1.0.2
 */
class Product_Description {

    const META_KEY = '_saai_product_description_form_data';

    /**
     * The product ID.
     *
     * @var int
     */
    private $product_id;

    /**
     * The product.
     *
     * @var \WC_Product
     */
    private $product;

    /**
     * The data.
     *
     * @var array
     */
    private $data = array();

    /**
     * Constructor.
     *
     * @param \WC_Product|int $product The product object.
     */
    public function __construct( $product = null ) {
        if ( $product ) {
            $product          = $product instanceof \WC_Product ? $product : wc_get_product( $product );
            $this->product_id = $product->get_id();
            $this->product    = $product;
        }

        if ( $this->product_id ) {
            $this->load_data();
        }
    }

    /**
     * Load the data.
     *
     * @since 1.0.2
     */
    public function load_data() {
        $product = $this->get_product();

        if ( is_wp_error( $product ) ) {
            return;
        }

        $this->data = wp_parse_args( $product->get_meta( self::META_KEY ), self::get_default_data() );

        $product_name = $product->get_name();
        $product_name = 'AUTO-DRAFT' === $product_name ? '' : $product_name;

        // If the product name is not set, set it to the product title.
        if ( ! $this->data['product_name'] && $product_name ) {
            $this->data['product_name'] = $product_name;
        }

        // If need_product_name is not set, set as 'no' if the product name is set, otherwise set as 'yes'.
        if ( ! $this->data['need_product_name'] ) {
            $this->data['need_product_name'] = $product_name ? 'no' : 'yes';
        }
    }

    /**
     * Get the product.
     *
     * @since 1.0.2
     *
     * @return \WC_Product
     */
    public function get_product() {
        if ( ! $this->product ) {
            $temp_product = wc_get_product( $this->product_id );

            if ( ! $temp_product ) {
                return new \WP_Error( 'product_not_found', 'Product not found', array( 'status' => 404 ) );
            }

            $this->product = $temp_product;
        }

        return $this->product;
    }

    /**
     * Get the default data.
     *
     * @since 1.0.2
     *
     * @return array
     */
    public static function get_default_data() {
        $ai_agent_settings = Product_Description_AI::instance()->get_settings();

        $defaults = array(
            'need_product_name'         => '',
            'product_name'              => '',
            'tones'                     => $ai_agent_settings['tones'] ?? array(),
            'interesting_facts'         => $ai_agent_settings['interesting_facts'] ?? array(),
            'age_focus'                 => $ai_agent_settings['age_focus'] ?? array(),
            'target_audiences'          => $ai_agent_settings['target_audience'] ?? array(), // Note the key difference.
            'refund_guarantee'          => $ai_agent_settings['refund_guarantee'] ?? '',
            'keywords'                  => array(),
            'sizes'                     => array(),
            'ingredients'               => array(),
            'description_length'        => $ai_agent_settings['description_length'] ?? '',
            'main_desc_length_check'    => $ai_agent_settings['main_desc_length_check'] ?? 'yes',  // Enable main description length checks by default.
            'main_desc_check_frequency' => $ai_agent_settings['main_desc_check_frequency'] ?? 12, // Default check every 12 hours.
            'main_desc_min_word_count'  => $ai_agent_settings['main_desc_min_word_count'] ?? 10, // Default minimum word count.
            'main_desc_max_word_count'  => $ai_agent_settings['main_desc_max_word_count'] ?? 30, // Default maximum word count.
            'language'                  => $ai_agent_settings['language'] ?? 'default',
        );

        return $defaults;
    }

    /**
     * Get the data.
     *
     * @since 1.0.2
     *
     * @return array
     */
    public function get_data() {
        if ( ! is_array( $this->data ) || empty( $this->data ) ) {
            return self::get_default_data();
        }

        return $this->data;
    }

    /**
     * Set the data.
     *
     * @since 1.0.2
     *
     * @param array $data The data.
     */
    public function set_data( $data ) {
        $existing_data = $this->get_data();
        $this->data    = wp_parse_args( $data, $existing_data );
    }

    /**
     * Save the data.
     *
     * @since 1.0.2
     */
    public function save() {
        $product = $this->get_product();

        if ( is_wp_error( $product ) ) {
            return $product;
        }

        $product->update_meta_data( self::META_KEY, $this->data );
        $product->save();
    }

    /**
     * Sanitize the data.
     *
     * @since 1.0.2
     *
     * @param array $data The data.
     * @return array
     */
    public static function sanitize_data( $data ) {
        $sanitized = array();

        foreach ( $data as $key => $value ) {
            switch ( $key ) {
                case 'tones':
                case 'interesting_facts':
                case 'age_focus':
                case 'target_audiences':
                case 'keywords':
                case 'sizes':
                case 'ingredients':
                    $sanitized[ $key ] = array_map( 'sanitize_text_field', $value );
                    break;
                default:
                    $sanitized[ $key ] = sanitize_text_field( $value );
            }
        }

        return $sanitized;
    }
}
