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

namespace SAAI\Automations;

use SAAI\Traits\Singleton_Trait;
use SAAI\AI_Agents\Review_Summaries_AI;
use SAAI\Classes\Notification;
use SAAI\Classes\Review_Summary;

/**
 * Review_Summaries_Automations class.
 *
 * This class handles automated tasks related to review summaries.
 *
 * @since 1.0.0
 */
class Review_Summaries_Automations {

    use Singleton_Trait;

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

    /**
     * Low rating threshold for triggering notifications.
     *
     * @var float
     */
    public const LOW_RATING_THRESHOLD = 2.5;

    /**
     * Setup action hooks when class is initialized.
     */
    public function __construct() {
        // Nothing to initialize at construction time.
    }

    /**
     * Create a notification if the product has a low average rating.
     *
     * @param array  $review_summary The review summary data.
     * @param string $product_name   The product name.
     * @param int    $product_id     The product ID.
     *
     * @return void|WP_Error
     */
    public function create_low_rating_notification( $review_summary, $product_name, $product_id ) {
        // Check if average rating exists and is below threshold.
        if ( empty( $review_summary['average_rating'] ) || ! is_numeric( $review_summary['average_rating'] ) ) {
            return;
        }

        $average_rating = (float) $review_summary['average_rating'];

        // Only create notification if rating is below threshold.
        if ( self::LOW_RATING_THRESHOLD < $average_rating ) {
            return;
        }

        // Check if there's already an active notification for this product.
        $notification = Notification::instance();

        // Get existing non-archived notifications for this product.
        $existing_notifications = $notification->get_all(
            array(
                'archived'   => 0,
                'product_id' => $product_id,
                'agent'      => 'review_summaries_ai',
            )
        );

        // If there are existing notifications, don't create a new one.
        if ( ! empty( $existing_notifications ) ) {
            return;
        }

        // Also check for recently archived notifications (within 2 weeks).
        $two_weeks_ago = gmdate( 'Y-m-d H:i:s', strtotime( '-2 weeks' ) );

        // Get archived notifications for this product from the last two weeks.
        $recent_archived_notifications = $notification->get_all(
            array(
                'archived'   => 1,
                'product_id' => $product_id,
                'agent'      => 'review_summaries_ai',
                'date_after' => $two_weeks_ago,
                'date_field' => 'updated_at',
            )
        );

        // If there are recently archived notifications, don't create a new one.
        if ( ! empty( $recent_archived_notifications ) ) {
            return;
        }

        // Format key takeaways for notification.
        $key_takeaways_formatted = '';
        $negative_takeaways      = array();

        foreach ( $review_summary['key_takeaways'] as $takeaway ) {
            // Prioritize negative takeaways in the notification.
            if ( isset( $takeaway['sentiment'] ) && 'negative' === $takeaway['sentiment'] ) {
                $negative_takeaways[] = '• ' . $takeaway['content'];
            }
        }

        // If we have negative takeaways, use those, otherwise include all.
        if ( ! empty( $negative_takeaways ) ) {
            $key_takeaways_formatted = implode( "\n", $negative_takeaways );
        } else {
            $formatted_takeaways = array();
            foreach ( $review_summary['key_takeaways'] as $takeaway ) {
                $formatted_takeaways[] = '• ' . $takeaway['content'];
            }
            $key_takeaways_formatted = implode( "\n", $formatted_takeaways );
        }

        // Create notification title and message.
        $title = sprintf(
            // translators: %1$s is the product name, %2$.1f is the average rating value (formatted to 1 decimal place).
            __( 'Low product rating detected', 'storeagent-ai-for-woocommerce' )
        );

        // Build message with HTML outside the translated strings.
        $message  = '<p>';
        $message .= sprintf(
            // translators: %1$s is the product name, %2$.1f is the average rating value, %3$d is the total number of reviews.
            __( 'The product "%1$s" has received a low average rating of %2$.1f out of 5 based on %3$d reviews.', 'storeagent-ai-for-woocommerce' ),
            $product_name,
            $average_rating,
            $review_summary['total_reviews']
        );
        $message .= '</p><p><strong>' . __( 'Summary:', 'storeagent-ai-for-woocommerce' ) . '</strong><br>';
        $message .= $review_summary['summary'];
        $message .= '</p><p><strong>' . __( 'Key Issues:', 'storeagent-ai-for-woocommerce' ) . '</strong><br>';
        $message .= $key_takeaways_formatted;
        $message .= '</p>';

        // Create a warning notification.
        return $notification->create_warning_notification(
            $title,
            $message,
            'review_summaries_ai',
            $product_id,
            array(
                'average_rating' => $average_rating,
                'total_reviews'  => $review_summary['total_reviews'],
                'key_takeaways'  => $review_summary['key_takeaways'],
                'summary'        => $review_summary['summary'],
            ),
            // Add a custom action to open the product in admin.
            array(
                array(
                    'label'  => __( 'Open Product', 'storeagent-ai-for-woocommerce' ),
                    'action' => 'open_product',
                    'url'    => admin_url( 'post.php?post=' . $product_id . '&action=edit' ),
                    'target' => '_blank',
                ),
            )
        );
    }

    /**
     * Handle settings saved via REST API.
     *
     * @param array           $response     The response data.
     * @param array           $settings     The new settings.
     * @param array           $old_settings The old settings.
     * @param WP_REST_Request $request      The request object.
     *
     * @return array The response data.
     */
    public function handle_rest_settings_save( $response, $settings, $old_settings, $request ) { // phpcs:ignore
        // Process any settings changes that might affect automations.
        return $response;
    }

    /**
     * Run the automation setup.
     *
     * @return void
     */
    public function run() {
        // Get the Review Summaries AI agent instance.
        $review_summaries_ai = Review_Summaries_AI::instance();

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

        // Hook directly into review summary generation to check for low ratings.
        add_action( 'saai_after_review_summary_generation', array( $this, 'create_low_rating_notification' ), 10, 3 );

        // Hook into REST API settings save response.
        add_filter( 'saai_rest_review-summaries-ai_settings_save_response', array( $this, 'handle_rest_settings_save' ), 10, 4 );
    }
}
