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

namespace SAAI\AI_Agents;

use SAAI\Abstracts\Abstract_AI_Agent;
use SAAI\Classes\Plan_Manager;
use SAAI\Factories\Vite_App;
use SAAI\Traits\Singleton_Trait;
use SAAI\Helpers\Helper;
use SAAI\REST\Category_Description_AI as Category_Description_AI_REST;
use SAAI\Classes\Category_Description;

/**
 * Category_Description_AI class.
 *
 * @since 1.0.4
 */
class Category_Description_AI extends Abstract_AI_Agent {

    use Singleton_Trait;

    /**
     * Holds the class instance object
     *
     * @since 1.0.4
     * @var Category_Description_AI $instance object
     */
    protected static $instance;

    /**
     * Constructor.
     *
     * @param mixed $data The prompt.
     */
    public function __construct( $data = null ) {
        $this->endpoint         = 'category-description';
        $this->ai_id            = "$this->endpoint-ai";
        $this->data             = $data;
        $this->default_settings = array(
            'enabled'            => 'no',
            'tones'              => array(),
            'age_focus'          => array(),
            'target_audience'    => array(),
            'description_length' => '',
            'language'           => 'default',
        );
    }

    /**
     * Set the prompt data.
     *
     * @param mixed $data The data prompt to be sent.
     *
     * @return void
     */
    public function set_data( $data ) {
        foreach ( $data as $key => $value ) {
            if ( is_array( $value ) ) {
                $this->data[ $key ] = implode( ', ', $value );
            } else {
                $this->data[ $key ] = $value;
            }
        }
    }

    /**
     * Display the generate AI description button for categories.
     *
     * @param object $term The term object.
     * @return void
     */
    public function display_generate_ai_description_button( $term ) {
        Helper::locate_admin_template( 'category-description-button.php', true );
    }

    /**
     * Enqueue the category description admin scripts.
     *
     * @since 1.0.4
     * @return void
     */
    public function enqueue_category_description_admin_scripts() {
        global $current_screen;

        if ( ! $current_screen || 'edit-product_cat' !== $current_screen->id ) {
            return;
        }

        $category_description = new Vite_App(
            'saai-category-description',
            'src/vanilla/admin/category-description/index.ts',
            array( 'jquery', 'wp-i18n', 'select2' ),
            array_merge(
                array(
                    'category_description_nonce' => wp_create_nonce( 'saai_get_category_description_form' ),
                    'categoryDescriptionRestUrl' => Category_Description_AI_REST::instance()->api_url,
                    'wpNonce'                    => wp_create_nonce( 'wp_rest' ),
                ),
                Plan_Manager::get_credit_usage_l10n()
            ),
            'saaiObj',
            array()
        );
        $category_description->enqueue();
    }

    /**
     * Get the category description form.
     *
     * @return void
     */
    public function ajax_get_category_description_form() {
        if ( ! wp_verify_nonce( $_POST['nonce'], 'saai_get_category_description_form' ) || ! current_user_can( 'manage_woocommerce' ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput
            wp_die( 'Invalid nonce' );
        }

        $term_id  = intval( $_POST['term_id'] ?? 0 );
        $category = new Category_Description( $term_id );

        if ( ! $category instanceof Category_Description ) {
            wp_die( 'Invalid category' );
        }

        $data = $category->get_data();
        extract( $data ); // phpcs:ignore WordPress.PHP.DontExtract.extract_extract

        $template_path_dir = SAAI_PLUGIN_DIR_PATH . 'templates/admin/';

        include $template_path_dir . 'category-description-form/form-header.php';
        include $template_path_dir . 'category-description-form/step-1-get-started.php';
        include $template_path_dir . 'category-description-form/step-2-tone.php';
        include $template_path_dir . 'category-description-form/step-3-common-characteristics.php';
        include $template_path_dir . 'category-description-form/step-4-age-focus.php';
        include $template_path_dir . 'category-description-form/step-5-target-audience.php';
        include $template_path_dir . 'category-description-form/step-6-keywords.php';
        include $template_path_dir . 'category-description-form/step-7-description-length.php';
        include $template_path_dir . 'category-description-form/step-8-language.php';
        include $template_path_dir . 'category-description-form/form-footer.php';
        include $template_path_dir . 'category-description-form/description-preview.php';

        wp_die();
    }

    /**
     * Run hooks related to the AI agent.
     *
     * @return void
     */
    public function run() {
        if ( ! $this->is_enabled() ) {
            return;
        }

        // Hook into product_cat term edit form.
        add_action( 'product_cat_edit_form_fields', array( $this, 'display_generate_ai_description_button' ), 10, 1 );

        // Also hook into the add form for new categories.
        add_action( 'product_cat_add_form_fields', array( $this, 'display_generate_ai_description_button' ), 8, 1 );

        // Enqueue scripts for the admin.
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_category_description_admin_scripts' ) );

        // AJAX handler for getting form.
        add_action( 'wp_ajax_saai_get_category_description_form', array( $this, 'ajax_get_category_description_form' ) );
    }
}
