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

namespace SAAI\Automations;

use SAAI\Traits\Singleton_Trait;
use SAAI\AI_Agents\Product_Summaries_AI;
use SAAI\Classes\Notification;

/**
 * Product_Summaries_Automations class.
 *
 * This class handles automated tasks related to product summaries.
 *
 * @since 1.0.0
 */
class Product_Summaries_Automations {

    use Singleton_Trait;

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

    /**
     * Action hook for the missing short description check.
     */
    const MISSING_SHORT_DESCRIPTION_CHECK_ACTION = 'saai_check_missing_short_descriptions';

    /**
     * Batch size for processing products.
     */
    const BATCH_SIZE = 50;

    /**
     * Maximum notifications to create per batch run.
     */
    const MAX_NOTIFICATIONS_PER_RUN = 5;

    /**
     * Setup action hooks when class is initialized.
     */
    public function __construct() {
        // Register Action Scheduler hooks.
        add_action( self::MISSING_SHORT_DESCRIPTION_CHECK_ACTION, array( $this, 'handle_missing_short_description_check' ) );
    }

    /**
     * Schedule the missing short description check.
     *
     * @param array $settings The settings to use for scheduling.
     * @return void
     */
    public function schedule_missing_short_description_check( $settings ) {
        // Only schedule if the product summaries AI is enabled and the automation is enabled.
        $product_summaries_ai = Product_Summaries_AI::instance();
        if ( ! $product_summaries_ai->is_enabled() ) {
            return;
        }

        // Only schedule if the feature is enabled.
        if ( 'yes' !== $settings['missing_desc_check'] ) {
            // If the setting is disabled, unschedule any existing tasks.
            $this->unschedule_missing_short_description_check();
            return;
        }

        // Get frequency setting (hours).
        $frequency = intval( $settings['missing_desc_frequency'] );
        if ( $frequency < 1 ) {
            $frequency = 12; // Default to 12 hours.
        }

        // If the action is already scheduled, don't schedule it again.
        if ( as_next_scheduled_action( self::MISSING_SHORT_DESCRIPTION_CHECK_ACTION ) ) {
            return;
        } else {
            // Schedule the action to run at the specified interval.
            as_schedule_recurring_action(
                time(), // Start now.
                $frequency * HOUR_IN_SECONDS, // Convert hours to seconds.
                self::MISSING_SHORT_DESCRIPTION_CHECK_ACTION
            );
        }
    }

    /**
     * Unschedule the missing short description check.
     *
     * @return void
     */
    public function unschedule_missing_short_description_check() {
        as_unschedule_all_actions( self::MISSING_SHORT_DESCRIPTION_CHECK_ACTION );
    }

    /**
     * Handles the scheduled missing short description check.
     *
     * This method is called by the scheduled cron job to check for products
     * with missing short descriptions that could be improved with AI.
     *
     * @return void
     */
    public function handle_missing_short_description_check() {
        // Get the Product Summaries AI agent settings.
        $product_summaries_ai = Product_Summaries_AI::instance();
        $settings             = $product_summaries_ai->get_settings();

        // Only proceed if missing short description check is enabled.
        if ( 'yes' !== $settings['missing_desc_check'] ) {
            return;
        }

        // Get products - using random ordering to diversify which products are checked each run.
        $args = array(
            'status'  => 'publish',
            'limit'   => self::BATCH_SIZE, // Process in batches to prevent timeouts.
            'orderby' => 'rand', // Random ordering.
        );

        $products = wc_get_products( $args );

        if ( empty( $products ) ) {
            return;
        }

        $notification_count  = 0;
        $total_product_count = count( $products );
        foreach ( $products as $product ) {
            // Stop processing if we've hit the maximum allowed notifications for this run.
            if ( $notification_count >= self::MAX_NOTIFICATIONS_PER_RUN ) {
                break;
            }

            $product_id        = $product->get_id();
            $short_description = $product->get_short_description();

            // Only process products with missing short descriptions.
            if ( ! empty( $short_description ) ) {
                continue;
            }

            // Only process products that have a description.
            if ( empty( $product->get_description() ) ) {
                continue;
            }

            // Check if we already have a notification for this product.
            $existing_notification = Notification::instance()->get_all(
                array(
                    'product_id'        => $product_id,
                    'notification_type' => 'missing_short_description',
                    'status'            => array( 'pending' ),
                    'agent'             => 'Product_Summaries_AI',
                )
            );
            if ( ! empty( $existing_notification ) ) {
                continue;
            }

            // Create decision notification for this product with direct callbacks.
            $notification_id = Notification::instance()->create_decision_notification(
                sprintf(
                    /* translators: %s: Product name */
                    __( 'Missing short description', 'storeagent-ai-for-woocommerce' )
                ),
                sprintf(
                    /* translators: %s: Product name */
                    __( 'The product "%s" is missing a short description. Click Accept and StoreAgent will generate one to improve your product page and SEO.', 'storeagent-ai-for-woocommerce' ),
                    $product->get_name()
                ),
                'Product_Summaries_AI',
                array(
                    'class'  => 'SAAI\AI_Agents\Product_Summaries_AI',
                    'method' => 'generate_product_short_description',
                    'args'   => array(
                        'product_id' => $product_id,
                    ),
                ),
                array(
                    'class'  => 'SAAI\AI_Agents\Product_Summaries_AI',
                    'method' => 'dismiss_missing_description_notification',
                    'args'   => array(
                        'product_id' => $product_id,
                    ),
                ),
                $product_id,
                array( 'notification_type' => 'missing_short_description' )
            );
            if ( $notification_id ) {
                ++$notification_count;
            }
        }
    }

    /**
     * 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
        // Always unschedule first to ensure any frequency changes will take effect.
        $this->unschedule_missing_short_description_check();

        // Schedule the missing short description check.
        $this->schedule_missing_short_description_check( $settings );

        return $response;
    }

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

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

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