<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

use WeDevs\Wpuf\Pro\AI_Review\Helper;

/**
 * AI Review Scheduler - Handles background AI review processing
 *
 * @since 4.2.5
 */
class Scheduler {

    /**
     * Action hook for AI review
     */
    const ACTION_REVIEW_POST = 'wpuf_ai_review_post';


    /**
     * Constructor
     *
     * @since 4.2.5
     */
    public function __construct() {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     *
     * @since 4.2.5
     */
    private function init_hooks() {
        // Register action scheduler hooks
        add_action( self::ACTION_REVIEW_POST, [ $this, 'process_single_review' ], 10, 2 );
    }

    /**
     * Schedule a single post review
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param array $form_settings Form settings
     * @param array $meta_vars Meta variables (already extracted from form submission)
     * @param int $delay Delay in seconds (default: 0 for immediate)
     *
     * @return bool Success status
     */
    public function schedule_review( $post_id, $form_settings, $meta_vars = [], $delay = 0 ) {
        // Check if AI review is enabled for this form
        $ai_review_enabled = ! empty( $form_settings['ai_review_enabled'] ) && wpuf_is_checkbox_or_toggle_on( $form_settings['ai_review_enabled'] );

        if ( ! $ai_review_enabled ) {
            return false;
        }

        $prompt = ! empty( $form_settings['ai_review_prompt'] ) ? sanitize_textarea_field( $form_settings['ai_review_prompt'] ) : '';
        if ( empty( $prompt ) ) {
            return false;
        }

        // Validate before scheduling
        $ai_service = new Service();
        $validation = $ai_service->validate_review_request( $post_id, $form_settings );

        if ( ! $validation['valid'] ) {
            // Save failed review if AI service not configured
            if ( strpos( $validation['message'], 'not configured' ) !== false ) {
                Helper::save_failed_review( $post_id, $validation['message'] );
            }
            return false;
        }

        // Store meta_vars temporarily for the background process to use
        // This avoids re-querying the database
        if ( ! empty( $meta_vars ) ) {
            update_post_meta( $post_id, '_wpuf_ai_review_meta_vars', $meta_vars );
        }

        $args = [
            'post_id' => $post_id,
            'prompt'  => $prompt,
        ];

        $action_id = as_schedule_single_action(
            time() + $delay,
            self::ACTION_REVIEW_POST,
            $args,
            'wpuf-ai-review'
        );

        return $action_id !== false;
    }

    /**
     * Process single post review
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @param string $prompt Review prompt
     */
    public function process_single_review( $post_id, $prompt ) {
        // Set status to in_progress when processing starts
        Helper::save_in_progress_review( $post_id );

        // Get comprehensive form data
        $form_data = $this->get_comprehensive_form_data( $post_id );

        if ( ! $form_data ) {
            Helper::save_failed_review( $post_id, 'No form data found for review' );
            return;
        }

        // Check if we have any content to review
        if ( empty( $form_data['content'] ) && empty( $form_data['excerpt'] ) && empty( $form_data['custom_fields'] ) ) {
            Helper::save_failed_review( $post_id, 'Post has no content to review' );
            return;
        }

        $ai_service = new Service();

        try {
            // Format comprehensive data into a single content string
            $formatted_content = $this->format_data_for_review( $form_data );

            // Perform AI review
            $result = $ai_service->review_post(
                $form_data['title'],
                $formatted_content,
                $form_data['excerpt'],
                $prompt
            );

            // Save result
            Helper::save_review_result( $post_id, $result, 'action_scheduler' );

            // Fire success action
            do_action( 'wpuf_ai_review_completed', $post_id, $result );

        } catch ( \Exception $e ) {
            Helper::save_failed_review( $post_id, $e->getMessage() );

            // Fire failure action
            do_action( 'wpuf_ai_review_failed', $post_id, $e->getMessage() );
        }
    }





    /**
     * Format comprehensive form data for AI review
     *
     * @since 4.2.5
     * @param array $form_data Comprehensive form data
     * @return string Formatted content string
     */
    private function format_data_for_review( $form_data ) {
        $content_parts = [];

        // Start with main content
        if ( ! empty( $form_data['content'] ) ) {
            $content_parts[] = $form_data['content'];
        }

        // Add custom fields
        if ( ! empty( $form_data['custom_fields'] ) ) {
            $content_parts[] = "\n\n--- Custom Fields ---";
            foreach ( $form_data['custom_fields'] as $field_name => $field_data ) {
                $content_parts[] = $field_data['label'] . ": " . $field_data['value'];
            }
        }

        // Add taxonomies
        if ( ! empty( $form_data['taxonomies'] ) ) {
            $content_parts[] = "\n\n--- Taxonomies ---";
            foreach ( $form_data['taxonomies'] as $taxonomy_name => $taxonomy_data ) {
                $term_names = array_column( $taxonomy_data['terms'], 'name' );
                $content_parts[] = $taxonomy_data['label'] . ": " . implode( ', ', $term_names );
            }
        }

        // Add integration-specific data (Events Calendar, EDD, WooCommerce, etc.)
        // Values are sanitized to prevent prompt injection from user-submitted meta.
        if ( ! empty( $form_data['integration_data'] ) ) {
            foreach ( $form_data['integration_data'] as $section_label => $fields ) {
                $content_parts[] = "\n\n--- " . sanitize_text_field( $section_label ) . " ---";
                foreach ( $fields as $label => $value ) {
                    $content_parts[] = sanitize_text_field( $label ) . ": " . sanitize_text_field( $value );
                }
            }
        }

        return implode( "\n", $content_parts );
    }

    /**
     * Get comprehensive form data for AI review
     * Reuses data already extracted during form submission to avoid duplicate queries
     *
     * @since 4.2.5
     * @param int $post_id Post ID
     * @return array|false Comprehensive form data or false if not found
     */
    private function get_comprehensive_form_data( $post_id ) {
        // Get the post
        $post = get_post( $post_id );
        if ( ! $post ) {
            return false;
        }

        // Try to get meta_vars that were stored during form submission
        // This avoids re-querying and re-processing
        $meta_vars = get_post_meta( $post_id, '_wpuf_ai_review_meta_vars', true );

        // If meta_vars weren't stored (e.g., for updates or retries), we need to extract them
        if ( empty( $meta_vars ) ) {
            $form_id = get_post_meta( $post_id, '_wpuf_form_id', true );
            if ( ! $form_id ) {
                return false;
            }

            $form = new \WeDevs\Wpuf\Admin\Forms\Form( $form_id );
            $form_fields = $form->get_fields();

            // Extract meta vars from form fields
            list( $post_vars, $taxonomy_vars, $meta_vars ) = Helper::extract_field_types( $form_fields );
        }

        // Build comprehensive data structure
        $form_data = [
            'title' => $post->post_title,
            'content' => $post->post_content,
            'excerpt' => $post->post_excerpt,
            'post_type' => $post->post_type,
            'post_status' => $post->post_status,
            'custom_fields' => [],
            'taxonomies' => [],
        ];

        // Process custom fields (meta vars) - we still need to get values from post meta
        if ( ! empty( $meta_vars ) ) {
            foreach ( $meta_vars as $meta_var ) {
                $field_name = $meta_var['name'];
                $field_value = get_post_meta( $post_id, $field_name, true );

                if ( ! empty( $field_value ) ) {
                    $form_data['custom_fields'][ $field_name ] = [
                        'label' => $meta_var['label'] ?? $field_name,
                        'value' => $field_value,
                        'type' => $meta_var['input_type'] ?? 'text',
                    ];
                }
            }
        }

        // Process taxonomies - get from saved post terms
        $taxonomies = get_object_taxonomies( $post->post_type, 'objects' );
        foreach ( $taxonomies as $taxonomy ) {
            $terms = wp_get_post_terms( $post_id, $taxonomy->name );

            if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
                $form_data['taxonomies'][ $taxonomy->name ] = [
                    'label' => $taxonomy->label,
                    'terms' => array_map( function( $term ) {
                        return [
                            'name' => $term->name,
                            'slug' => $term->slug,
                        ];
                    }, $terms ),
                ];
            }
        }

        /**
         * Filter to add integration-specific data for AI review
         *
         * Allows integrations (Events Calendar, EDD, WooCommerce, etc.) to provide
         * their own field data for the AI to review.
         *
         * @since 4.2.13
         *
         * @param array  $integration_data Integration-specific data, keyed by section label
         * @param int    $post_id          Post ID being reviewed
         * @param string $post_type        Post type slug
         */
        $form_data['integration_data'] = apply_filters(
            'wpuf_ai_review_integration_data',
            [],
            $post_id,
            $post->post_type
        );

        // Clean up temporary meta after use
        delete_post_meta( $post_id, '_wpuf_ai_review_meta_vars' );

        return $form_data;
    }




}
