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

namespace SAAI\Automations;

use SAAI\Traits\Singleton_Trait;
use SAAI\AI_Agents\Review_Moderation_AI;
use SAAI\Classes\Notification;
use WP_Error;

/**
 * Review_Moderation_Automations class.
 *
 * Handles automated tasks related to review moderation.
 * Listens for new product reviews and creates notifications for flagged reviews.
 *
 * @since 1.1.4
 */
class Review_Moderation_Automations {

    use Singleton_Trait;

    /**
     * Holds the class instance object.
     *
     * @since 1.1.4
     * @var Review_Moderation_Automations $instance object.
     */
    protected static $instance;

    /**
     * Constructor.
     *
     * @since 1.1.4
     */
    public function __construct() {
        // No initialization hooks needed here.
    }

    /**
     * Handle new review submission.
     *
     * Validates the comment is a product review and schedules AI moderation.
     *
     * @since 1.1.4
     * @param int        $comment_id       The comment ID.
     * @param int|string $comment_approved The approval status (1, 0, 'spam').
     * @param array      $commentdata      The comment data.
     * @return void
     */
    public function on_new_review( $comment_id, $comment_approved, $commentdata ) {
        // Only process product reviews.
        if ( ! Review_Moderation_AI::is_product_review_data( $commentdata ) ) {
            return;
        }

        // Schedule AI moderation.
        Review_Moderation_AI::instance()->schedule_moderation( $comment_id );
    }

    /**
     * Create a notification for a flagged review.
     *
     * Creates a TYPE_DECISION notification with Accept/Reject actions for the admin.
     *
     * @since 1.1.4
     * @param int   $comment_id The comment ID.
     * @param array $result     The AI moderation result.
     * @return int|WP_Error The notification ID or WP_Error.
     */
    public function create_flagged_review_notification( $comment_id, $result ) {
        $comment = get_comment( $comment_id );
        if ( ! $comment ) {
            return new WP_Error( 'comment_not_found', __( 'Comment not found.', 'storeagent-ai-for-woocommerce' ) );
        }

        $product_id   = (int) $comment->comment_post_ID;
        $product      = wc_get_product( $product_id );
        $product_name = $product instanceof \WC_Product ? $product->get_name() : __( 'Unknown Product', 'storeagent-ai-for-woocommerce' );
        $rating       = (int) get_comment_meta( $comment_id, 'rating', true );

        // Build notification message.
        $message = sprintf(
            /* translators: %s: Product name. */
            __( 'A product review for "%s" has been flagged for manual review:', 'storeagent-ai-for-woocommerce' ),
            $product_name
        );

        // Add rating.
        if ( $rating > 0 ) {
            $message .= '<p><strong>' . __( 'Rating:', 'storeagent-ai-for-woocommerce' ) . '</strong> ';
            $message .= str_repeat( '★', $rating ) . str_repeat( '☆', 5 - $rating );
            $message .= '</p>';
        }

        // Add review excerpt.
        $review_excerpt = wp_trim_words( $comment->comment_content, 30, '...' );
        $message       .= '<p><strong>' . __( 'Review:', 'storeagent-ai-for-woocommerce' ) . '</strong><br>';
        $message       .= esc_html( $review_excerpt ) . '</p>';

        // Add reviewer info.
        $message .= '<p><strong>' . __( 'Reviewer:', 'storeagent-ai-for-woocommerce' ) . '</strong> ';
        $message .= esc_html( $comment->comment_author ) . '</p>';

        // Add AI analysis details.
        if ( is_array( $result ) ) {
            if ( isset( $result['confidence_score'] ) ) {
                $confidence = Review_Moderation_AI::normalize_confidence_score( $result['confidence_score'] );

                $message .= '<p><strong>' . __( 'Confidence Score:', 'storeagent-ai-for-woocommerce' ) . '</strong> ';
                $message .= $confidence . '%</p>';
            }

            if ( ! empty( $result['flags'] ) && is_array( $result['flags'] ) ) {
                $message .= '<p><strong>' . __( 'Flags:', 'storeagent-ai-for-woocommerce' ) . '</strong> ';
                $message .= esc_html( implode( ', ', $result['flags'] ) ) . '</p>';
            }

            if ( ! empty( $result['reasons'] ) && is_array( $result['reasons'] ) ) {
                $message .= '<p><strong>' . __( 'Reasons:', 'storeagent-ai-for-woocommerce' ) . '</strong></p><ul>';
                foreach ( $result['reasons'] as $reason ) {
                    $message .= '<li>' . esc_html( $reason ) . '</li>';
                }
                $message .= '</ul>';
            }

            if ( isset( $result['admin_summary'] ) ) {
                $message .= '<p><strong>' . __( 'AI Summary:', 'storeagent-ai-for-woocommerce' ) . '</strong><br>';
                $message .= esc_html( $result['admin_summary'] ) . '</p>';
            }
        }

        return Notification::instance()->create_decision_notification(
            __( 'Product review flagged for moderation', 'storeagent-ai-for-woocommerce' ),
            $message,
            'Review_Moderation_AI',
            array(
                'class'  => 'SAAI\AI_Agents\Review_Moderation_AI',
                'method' => 'approve_review',
                'args'   => array(
                    'comment_id' => $comment_id,
                ),
            ),
            array(
                'class'  => 'SAAI\AI_Agents\Review_Moderation_AI',
                'method' => 'reject_review',
                'args'   => array(
                    'comment_id' => $comment_id,
                ),
            ),
            $product_id,
            array(
                'notification_type' => 'flagged_review',
                'comment_id'        => $comment_id,
            )
        );
    }

    /**
     * Run the automation setup.
     *
     * @since 1.1.4
     * @return void
     */
    public function run() {
        // Get the Review Moderation AI agent instance.
        $agent = Review_Moderation_AI::instance();

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

        // Hook into new review submissions.
        add_action( 'comment_post', array( $this, 'on_new_review' ), 10, 3 );

        // Hook into flagged reviews to create notifications.
        add_action( 'saai_review_moderation_flagged', array( $this, 'create_flagged_review_notification' ), 10, 2 );
    }
}
