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

namespace SAAI\Classes;

use SAAI\AI_Agents\Product_Questions_AI;
use WP_Post;

/**
 * Product_Question class.
 *
 * @since 1.0.0
 */
class Product_Question {

    /**
     * The post type.
     *
     * @var string
     */
    public const POST_TYPE = 'product-question';

    /**
     * The original text.
     *
     * @var string
     */
    private $original_question = '';

    /**
     * The post object of product-question post type.
     *
     * @var WP_Post|null
     */
    private $post;

    /**
     * The dirty flag.
     *
     * @var bool
     */
    private $is_dirty = false;

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

    /**
     * Constructor.
     *
     * @param int  $product_id    The product ID.
     * @param null $question_post The question post object.
     */
    public function __construct( $product_id, $question_post = null ) {

        if ( is_object( $question_post ) || is_a( $question_post, WP_Post::class ) ) {
            $this->post = get_post( $question_post );
            $this->post = self::POST_TYPE === $this->post->post_type ? $this->post : null;
        } else {
            $this->post     = new WP_Post(
                (object) array(
                    'post_type'   => self::POST_TYPE,
                    'post_status' => Product_Questions_AI::instance()->get_settings( 'moderateQnA' ) === 'yes' ? 'pending' : 'publish',
                )
            );
            $this->is_dirty = true;
        }
        $this->product_id = $product_id;
    }

    /**
     * Get class property.
     *
     * @param string $name The name of the property.
     *
     * @return array|mixed|null
     */
    public function __get( $name ) {

        return $this->post->$name ?? null;
    }

    /**
     * Set class property.
     *
     * @param string $name  The name of the property.
     * @param mixed  $value The value of the property.
     *
     * @return void
     */
    public function __set( $name, $value ) {

        switch ( $name ) {
            case 'question':
                $this->post->post_title = $value;
                $this->is_dirty         = true;
                break;
            case 'answer':
                $this->post->post_content = $value;
                $this->is_dirty           = true;
                break;
            case 'original_question':
                $this->original_question = $value;
                $this->is_dirty          = true;
                break;
            default:
                if ( property_exists( $this->post, $name ) ) {
                    $this->post->$name = $value;
                    $this->is_dirty    = true;
                }
        }
    }

    /**
     * Save the question.
     *
     * @since 1.0.0
     * @return $this
     */
    public function save() {

        $post_data = array(
            'ID'           => $this->post->ID ?? 0,
            'post_title'   => $this->post->post_title ?? __( 'New Question', 'storeagent-ai-for-woocommerce' ),
            'post_content' => $this->post->post_content ?? '',
            'post_type'    => self::POST_TYPE,
            'post_status'  => $this->post->post_status ?? 'publish',
        );

        if ( isset( $this->post->ID ) && $this->post->ID ) {
            $this->post->ID = wp_update_post( $post_data );
        } else {
            $this->post->ID = wp_insert_post( $post_data );
        }

        update_post_meta( $this->post->ID, '_original_question', $this->original_question );
        update_post_meta( $this->post->ID, '_product_id', $this->product_id );
        $this->is_dirty = false;

        return $this;
    }

    /**
     * Get the questions and answers for the product.
     *
     * @param string $product_id The product ID.
     * @param int    $page       The page number.
     * @param int    $per_page   The number of questions per page.
     *
     * @since 1.0.0
     * @return array{
     *     id: int,
     *     question: string,
     *     answer: string,
     * }
     */
    public static function get_questions( $product_id, $page = 1, $per_page = -1 ) {

        $args = array(
            'post_type'      => self::POST_TYPE,
            'posts_per_page' => $per_page,
            'paged'          => $page,
            'fields'         => 'ids',
            'meta_query'     => array(
                array(
                    'key'     => '_product_id',
                    'value'   => $product_id,
                    'compare' => '=',
                ),
            ),
        );

        $posts     = get_posts( $args );
        $questions = array();
        foreach ( $posts as $post_id ) {
            $questions[] = array(
                'id'       => $post_id,
                'question' => get_the_title( $post_id ),
                'answer'   => get_the_content( null, false, $post_id ),
            );
        }

        return $questions;
    }

    /**
     * Get the count of questions for the product.
     *
     * @param int $product_id The product ID.
     *
     * @since 1.0.1
     * @return int The count of questions for the given product.
     */
    public static function get_questions_count( $product_id = null ) {

        $args = array(
            'post_type'      => self::POST_TYPE,
            'posts_per_page' => -1,
            'fields'         => 'ids',
        );

        if ( $product_id ) {
            $args['meta_query'][] = array(
                'key'     => '_product_id',
                'value'   => $product_id,
                'compare' => '=',
            );
        }

        $query = new \WP_Query( $args );

        return $query->found_posts;
    }
}
