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

namespace SAAI\Automations;

use SAAI\Traits\Singleton_Trait;
use SAAI\AI_Agents\Product_Questions_AI;
use SAAI\Classes\Notification;
use SAAI\Classes\Product_Question;

/**
 * Product_Questions_Automations class.
 *
 * This class handles automated tasks related to product questions.
 *
 * @since 1.0.0
 */
class Product_Questions_Automations {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @since 1.0.0
     * @var Product_Questions_Automations $instance object
     */
    protected static $instance;

    /**
     * Notification type for unpublished questions
     */
    const NOTIFICATION_TYPE_UNPUBLISHED_QUESTION = 'unpublished_question';

    /**
     * Setup action hooks when class is initialized.
     */
    public function __construct() {
        // No initialization hooks needed here.
    }

    /**
     * Hook into post status transitions for product questions.
     *
     * @param string  $new_status The new post status.
     * @param string  $old_status The old post status.
     * @param WP_Post $post       The post object.
     */
    public function handle_question_status_transition( $new_status, $old_status, $post ) {
        // Only process product question post type.
        if ( Product_Question::POST_TYPE !== $post->post_type ) {
            return;
        }

        // Create notification when a new question is pending.
        if ( 'pending' === $new_status && 'pending' !== $old_status ) {
            $this->create_unpublished_question_notification( $post->ID );
        }

        // Clear notification when a question is published or trashed.
        if ( ( 'publish' === $new_status && 'publish' !== $old_status ) ||
            ( 'trash' === $new_status && 'trash' !== $old_status ) ) {
            $this->clear_unpublished_question_notifications( $post->ID );
        }
    }

    /**
     * Create a notification for an unpublished question.
     *
     * @param int         $question_id The question post ID.
     * @param string|null $question_title The question title.
     * @param int         $product_id The product ID.
     *
     * @return int|WP_Error The notification ID or WP_Error.
     */
    public function create_unpublished_question_notification( $question_id, $question_title = null, $product_id = null ) {
        if ( ! $question_title ) {
            $question_title = get_the_title( $question_id );
        }

        if ( ! $product_id ) {
            $product_id = get_post_meta( $question_id, '_product_id', true );
        }

        // Skip if no product ID is found.
        if ( ! $product_id ) {
            return new \WP_Error( 'no_product_id', __( 'No product ID associated with this question.', 'storeagent-ai-for-woocommerce' ) );
        }

        $product = wc_get_product( $product_id );
        if ( ! $product ) {
            return new \WP_Error( 'invalid_product', __( 'Invalid product.', 'storeagent-ai-for-woocommerce' ) );
        }

        // Get the question post to include its answer.
        $question_post   = get_post( $question_id );
        $question_answer = '';
        if ( $question_post ) {
            $question_answer = $question_post->post_content;
        }

        // Format the message with question and answer.
        $message = sprintf(
            /* translators: %1$s: Product name, %2$s: Question */
            __( 'A customer has asked a question about "%1$s":', 'storeagent-ai-for-woocommerce' ),
            $product->get_name()
        );

        $message .= '<p><strong>' . __( 'Question:', 'storeagent-ai-for-woocommerce' ) . '</strong><br>';
        $message .= esc_html( $question_title ) . '</p>';

        if ( ! empty( $question_answer ) ) {
            $message .= '<p><strong>' . __( 'AI-Generated Answer:', 'storeagent-ai-for-woocommerce' ) . '</strong><br>';
            $message .= wp_kses_post( $question_answer ) . '</p>';
        }

        $message .= '<p>' . __( 'Would you like to publish this question and answer to make it visible to customers?', 'storeagent-ai-for-woocommerce' ) . '</p>';

        return Notification::instance()->create_decision_notification(
            __( 'New product question awaiting review', 'storeagent-ai-for-woocommerce' ),
            $message,
            'Product_Questions_AI',
            array(
                'class'  => 'SAAI\AI_Agents\Product_Questions_AI',
                'method' => 'publish_qa',
                'args'   => array(
                    'question_id' => $question_id,
                ),
            ),
            array(
                'class'  => 'SAAI\AI_Agents\Product_Questions_AI',
                'method' => 'discard_qa',
                'args'   => array(
                    'question_id' => $question_id,
                ),
            ),
            $product_id,
            array(
                'notification_type' => self::NOTIFICATION_TYPE_UNPUBLISHED_QUESTION,
                'question_id'       => $question_id,
            )
        );
    }

    /**
     * Clear notifications when a question is published.
     *
     * @param int $question_id The question post ID.
     * @return bool Whether notifications were cleared.
     */
    public function clear_unpublished_question_notifications( $question_id ) {
        $notifications = Notification::instance()->get_all(
            array(
                'extra'  => array(
                    'question_id' => $question_id,
                ),
                'status' => array( 'pending' ),
            )
        );

        if ( empty( $notifications ) ) {
            return false;
        }

        $success = true;
        foreach ( $notifications as $notification ) {
            // Handle both object and array formats.
            $notification_id = is_object( $notification ) ? $notification->id : $notification['id'];
            $result          = Notification::instance()->archive( $notification_id );
            if ( is_wp_error( $result ) ) {
                $success = false;
            }
        }

        return $success;
    }

    /**
     * Create notification when a new question is submitted.
     *
     * @param int    $question_id The question post ID.
     * @param string $question    The question text.
     * @param int    $product_id  The product ID.
     */
    public function create_notification_for_question_submission( $question_id, $question, $product_id ) {
        // Get the Product Questions AI agent instance.
        $product_questions_ai = Product_Questions_AI::instance();

        // Only create notifications if moderation is enabled.
        if ( 'yes' !== $product_questions_ai->get_settings( 'moderateQnA' ) ) {
            return;
        }

        $this->create_unpublished_question_notification( $question_id, $question, $product_id );
    }

    /**
     * Run the automation setup.
     *
     * @return void
     */
    public function run() {
        // Get the Product Questions AI agent instance.
        $product_questions_ai = Product_Questions_AI::instance();

        // Only run automations if the AI agent is enabled.
        if ( ! $product_questions_ai->is_enabled() ) {
            return;
        }

        // Hook into post status transitions.
        add_action( 'transition_post_status', array( $this, 'handle_question_status_transition' ), 10, 3 );

        // Hook into question submissions.
        add_action( 'saai_after_question_submission', array( $this, 'create_notification_for_question_submission' ), 10, 3 );
    }
}
