<?php

namespace WeDevs\Wpuf\Pro\AI_Review;

/**
 * AI Review Form Settings
 *
 * Adds AI Review settings to the form builder
 *
 * @since 4.2.5
 */
class Form_Settings {

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

    /**
     * Initialize hooks
     *
     * @since 4.2.5
     */
    public function init_hooks() {
        // Add AI Review to the menu titles (sidebar)
        add_filter( 'wpuf_post_form_builder_setting_menu_titles', [ $this, 'add_ai_review_menu_title' ], 6 );
        add_filter( 'wpuf_post_form_builder_setting_menu_contents', [ $this, 'form_settings_ai_review' ] );

        // Enqueue script for dynamic prompt placeholders on the form builder page
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_prompt_placeholder_script' ] );
    }

    /**
     * Add AI Review to menu titles
     *
     * This adds "AI Review" to the sidebar menu, positioned right before "Post Expiration"
     *
     * @since 4.2.5
     *
     * @param array $settings
     * @return array
     */
    public function add_ai_review_menu_title( $settings ) {
        // Create AI Review menu item
        $ai_review = [
            'ai_review' => [
                'label' => __( 'AI Review', 'wpuf-pro' ),
                'icon'  => '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" class="custom-stroke">
                            <path d="M9.99902 1.66675L12.574 7.38342L18.7407 8.22508L14.3657 12.4834L15.1407 18.6251L9.99902 15.8084L4.85736 18.6251L5.63236 12.4834L1.25736 8.22508L7.42402 7.38342L9.99902 1.66675Z" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                          </svg>',
            ],
        ];

        return array_merge( $settings, $ai_review );
    }

    /**
     * Add AI Review settings
     *
     * @since 4.2.5
     *
     * @param array $fields Existing form fields
     *
     * @return array Modified form fields with AI Review settings
     */
    public function form_settings_ai_review( $fields ) {
        $fields['post_settings']['ai_review']['ai_review_enabled'] = [
            'label'     => __( 'Review Submitted Posts by AI', 'wpuf-pro' ),
            'type'      => 'toggle',
            'help_text' => __( 'Enable AI-powered review of posts submitted via this form', 'wpuf-pro' ),
            'name'      => 'wpuf_settings[ai_review_enabled]',
        ];

        $fields['post_settings']['ai_review']['ai_review_prompt'] = [
            'label'       => __( 'Review Criterion', 'wpuf-pro' ),
            'type'        => 'textarea',
            'help_text'   => __( 'Define the criteria for AI to evaluate posts. Be specific about what makes a good post. (Maximum 500 characters)', 'wpuf-pro' ),
            'placeholder' => __( 'Example: Evaluate posts based on content quality, relevance, grammar, and originality.', 'wpuf-pro' ),
            'name'        => 'wpuf_settings[ai_review_prompt]',
            'maxlength'   => 500,
            'long_help'   => '<div class="wpuf-ai-review-help wpuf-bg-blue-50 wpuf-border-l-4 wpuf-border-blue-500 wpuf-p-4 wpuf-my-4">
                                <p class="wpuf-font-semibold wpuf-mb-2 wpuf-mt-0">' . __( 'How AI Review Works:', 'wpuf-pro' ) . '</p>
                                <ul class="wpuf-list-disc wpuf-ml-5 wpuf-space-y-1 wpuf-text-sm">
                                    <li>' . __( 'AI automatically reviews each post submitted via this form', 'wpuf-pro' ) . '</li>
                                    <li>' . __( 'Review results appear in the Posts table with color indicators:', 'wpuf-pro' ) . '
                                        <ul class="wpuf-ml-4 wpuf-mt-1">
                                            <li>🟢 <strong>' . __( 'Full Match', 'wpuf-pro' ) . '</strong> - ' . __( 'Meets all criteria', 'wpuf-pro' ) . '</li>
                                            <li>🟡 <strong>' . __( 'Medium Match', 'wpuf-pro' ) . '</strong> - ' . __( 'Partially meets criteria', 'wpuf-pro' ) . '</li>
                                            <li>🔴 <strong>' . __( 'No Match', 'wpuf-pro' ) . '</strong> - ' . __( 'Does not meet criteria', 'wpuf-pro' ) . '</li>
                                        </ul>
                                    </li>
                                    <li>' . __( 'Reviews run once per post and are stored permanently', 'wpuf-pro' ) . '</li>
                                    <li>' . __( 'Requires global AI settings to be configured (OpenAI or Anthropic API key)', 'wpuf-pro' ) . '</li>
                                </ul>
                            </div>',
        ];

        return $fields;
    }

    /**
     * Get default prompt suggestions per post type
     *
     * @since 4.2.13
     *
     * @return array Associative array of post type slug to suggested prompt text
     */
    public function get_default_prompts() {
        $prompts = [
            'post'         => __( 'Evaluate posts based on content quality, relevance, grammar, and originality.', 'wpuf-pro' ),
            'tribe_events' => __( 'Evaluate event submissions: check if dates are valid, event description is clear, venue/organizer info is complete, and pricing is appropriate.', 'wpuf-pro' ),
            'download'     => __( 'Evaluate digital product submissions: check if product description is adequate, pricing is set, downloadable files are provided, and product categorization is correct.', 'wpuf-pro' ),
            'product'      => __( 'Evaluate product submissions: check if product description is adequate, pricing is set correctly, product images are provided, and categorization is appropriate.', 'wpuf-pro' ),
        ];

        /**
         * Filter the default AI review prompt suggestions per post type
         *
         * @since 4.2.13
         *
         * @param array $prompts Associative array of post type slug to suggested prompt text
         */
        return apply_filters( 'wpuf_ai_review_default_prompts', $prompts );
    }

    /**
     * Enqueue script for dynamic prompt placeholder based on post type
     *
     * Updates the AI review prompt textarea placeholder when the post type
     * dropdown changes in the form builder.
     *
     * @since 4.2.13
     *
     * @return void
     */
    public function enqueue_prompt_placeholder_script() {
        $screen = get_current_screen();

        if ( ! $screen || $screen->id !== 'user-frontend_page_wpuf-post-forms' ) {
            return;
        }

        wp_enqueue_script(
            'wpuf-ai-review-form-settings',
            WPUF_PRO_ASSET_URI . '/js/wpuf-ai-review-form-settings.js',
            [ 'jquery' ],
            WPUF_PRO_VERSION,
            true
        );

        wp_localize_script(
            'wpuf-ai-review-form-settings',
            'wpufAIReviewFormSettings',
            [
                'promptSuggestions' => $this->get_default_prompts(),
                'defaultPrompt'    => __( 'Example: Evaluate posts based on content quality, relevance, grammar, and originality.', 'wpuf-pro' ),
            ]
        );
    }
}
