<?php
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Admin Forms & Content Handler
 *
 * Handles forms and content studio AJAX requests.
 *
 * @package    Kitsune_AI_Platform
 * @subpackage Kitsune_AI_Platform/admin
 */
class Kitsune_AI_Platform_Admin_Forms_Content extends Kitsune_AI_Platform_Admin_Ajax_Base {

    /**
     * Register AJAX hooks.
     */
    public function register_hooks() {
        add_action('wp_ajax_kitsune_ai_platform_get_forms', array($this, 'ajax_get_forms'));
        add_action('wp_ajax_kitsune_ai_platform_get_form_templates', array($this, 'ajax_get_form_templates'));
        add_action('wp_ajax_kitsune_ai_platform_create_form', array($this, 'ajax_create_form'));
        add_action('wp_ajax_kitsune_ai_platform_update_form', array($this, 'ajax_update_form'));
        add_action('wp_ajax_kitsune_ai_platform_delete_form', array($this, 'ajax_delete_form'));
        add_action('wp_ajax_kitsune_ai_platform_get_form_submissions', array($this, 'ajax_get_form_submissions'));
        add_action('wp_ajax_kitsune_ai_platform_get_form_settings', array($this, 'ajax_get_form_settings'));
        add_action('wp_ajax_kitsune_ai_platform_save_form_settings', array($this, 'ajax_save_form_settings'));
        add_action('wp_ajax_kitsune_ai_platform_generate_content', array($this, 'ajax_generate_content'));
        add_action('wp_ajax_kitsune_ai_platform_save_generated_content', array($this, 'ajax_save_generated_content'));
        add_action('wp_ajax_kitsune_ai_platform_generate_image', array($this, 'ajax_generate_image'));
        add_action('wp_ajax_kitsune_ai_platform_save_generated_image', array($this, 'ajax_save_generated_image'));
        add_action('wp_ajax_kitsune_ai_platform_bulk_generate_content', array($this, 'ajax_bulk_generate_content'));
        add_action('wp_ajax_kitsune_ai_platform_get_wp_posts', array($this, 'ajax_get_wp_posts'));
        add_action('kitsune_ai_platform_process_bulk_item', array($this, 'handle_bulk_item_cron'), 10, 2);
    }

    /**
     * AJAX: Get WP Posts for Enhancer
     */
    public function ajax_get_wp_posts() {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return;
        }

        $params = $this->get_post_payload('params', array());
        if (!$params) {
            $params = map_deep(wp_unslash($_GET), 'sanitize_text_field');
        }

        $post_type = sanitize_key($params['post_type'] ?? 'post');
        $search = sanitize_text_field($params['search'] ?? '');
        $page = max(1, intval($params['page'] ?? 1));
        $per_page = 20;

        $args = array(
            'post_type' => $post_type,
            's' => $search,
            'posts_per_page' => $per_page,
            'paged' => $page,
            'post_status' => array('publish', 'draft', 'pending'),
        );

        $query = new WP_Query($args);
        $posts = array();

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $post = get_post();
                $posts[] = array(
                    'id' => $post->ID,
                    'title' => $post->post_title,
                    'content' => $post->post_content,
                    'type' => $post->post_type,
                    'status' => $post->post_status,
                    'date' => $post->post_date,
                    'edit_link' => get_edit_post_link($post->ID, 'raw'),
                );
            }
            wp_reset_postdata();
        }

        wp_send_json_success(array(
            'posts' => $posts,
            'total' => $query->found_posts,
            'page' => $page,
            'per_page' => $per_page,
        ));
    }

    /**
     * AJAX: Bulk Generate Content
     */
    public function ajax_bulk_generate_content() {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return;
        }

        $items    = isset($_POST['items'])    ? map_deep(wp_unslash((array)$_POST['items']),    'sanitize_text_field') : array();
        $settings = isset($_POST['settings']) ? map_deep(wp_unslash((array)$_POST['settings']), 'sanitize_text_field') : array();

        if (empty($items)) {
            wp_send_json_error(array('message' => __('No items to process', 'kitsune-ai-platform')));
            return;
        }

        // Schedule each item with a slight delay to spread load
        $delay = 5; // seconds
        foreach ($items as $index => $item) {
            $scheduled_time = time() + ($index * $delay);
            wp_schedule_single_event($scheduled_time, 'kitsune_ai_platform_process_bulk_item', array($item, $settings));
        }

        wp_send_json_success(array(
            'message' => sprintf(__('Scheduled %d items for background generation', 'kitsune-ai-platform'), count($items)),
            'count' => count($items)
        ));
    }

    /**
     * Cron Handler: Process single bulk item
     */
    public function handle_bulk_item_cron($item, $settings) {
        $topic = sanitize_text_field($item['topic'] ?? '');
        if (empty($topic)) return;

        $keywords = sanitize_text_field($item['keywords'] ?? '');
        $post_type = sanitize_key($item['post_type'] ?? $settings['postType'] ?? 'post');
        $status = sanitize_key($settings['status'] ?? 'draft');
        $length = intval($settings['length'] ?? 1000);
        $style = sanitize_textarea_field($settings['style'] ?? '');

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/class-kitsune-ai-platform-api.php';
        $api = new Kitsune_AI_Platform_API();

        $default_models = get_option('kitsune_ai_platform_default_models', array());
        $model = $this->extract_model_id($default_models['content'] ?? '');

        $prompt = sprintf(__('Write an approximately %d-word article.', 'kitsune-ai-platform'), $length) . "\n";
        $prompt .= sprintf(__('Topic: %s', 'kitsune-ai-platform'), $topic) . "\n";
        if (!empty($keywords)) {
            $prompt .= sprintf(__('Keywords: %s', 'kitsune-ai-platform'), $keywords) . "\n";
        }
        if (!empty($style)) {
            $prompt .= sprintf(__('Style: %s', 'kitsune-ai-platform'), $style) . "\n";
        }
        $prompt .= __('Return HTML content with headings and paragraphs. Do not include a title heading.', 'kitsune-ai-platform');

        $response = $api->chatRAG(array(
            'model' => $model,
            'messages' => array(
                array('role' => 'system', 'content' => __('You are an expert content writer.', 'kitsune-ai-platform')),
                array('role' => 'user', 'content' => $prompt),
            ),
            'temperature' => 0.7,
            'max_tokens' => min(4000, max(256, intval($length * 1.25))),
            'feature' => 'bulk_content',
        ));

        if (empty($response['success'])) return;

        $content_body = wp_kses_post($response['data']['content'] ?? '');
        if ($content_body === '') return;

        $post_data = array(
            'post_title'    => $topic,
            'post_content'  => $content_body,
            'post_status'   => $status,
            'post_type'     => $post_type,
            'post_author'   => get_current_user_id() ?: 1 // Fallback to admin if no user context
        );

        $post_id = wp_insert_post($post_data);

        if (!is_wp_error($post_id) && !empty($keywords)) {
            wp_set_post_tags($post_id, $keywords);
        }
    }

    /**
     * AJAX: Get Forms
     */
    public function ajax_get_forms() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        // Model loaded via Autoloader
        $model = new Kitsune_AI_Platform_Form_Model();

        $page = isset($_GET['page']) ? max(1, intval(wp_unslash($_GET['page']))) : 1;
        $per_page = isset($_GET['per_page']) ? min(100, max(1, intval(wp_unslash($_GET['per_page'])))) : 20;
        $search = isset($_GET['search']) ? sanitize_text_field(wp_unslash($_GET['search'])) : '';
        $offset = ($page - 1) * $per_page;

        $forms = $model->get_all($per_page, $offset, $search);
        $total = $model->count_all($search);

        wp_send_json_success(array(
            'forms' => $forms,
            'total' => $total,
            'page' => $page,
            'per_page' => $per_page
        ));
    }

    /**
     * AJAX: Create Form
     */
    public function ajax_create_form() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        $data = $this->get_post_payload('data', array());
        if (!$data) {
            $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }
        $data = apply_filters('kitsune_ai_platform_before_create_form_data', $data);
        if (!is_array($data)) {
            wp_send_json_error(array('message' => __('Invalid form data', 'kitsune-ai-platform')));
            return;
        }

        // Model loaded via Autoloader
        $model = new Kitsune_AI_Platform_Form_Model();

        $result = $model->create($data);

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        } else {
            $form = $model->get_by_id($result);

            do_action('kitsune_ai_platform_form_created', $result, $data, $form);
            Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                Kitsune_AI_Platform_Webhook_Events::FORM_CREATED,
                array(
                    'form_id' => (int) $result,
                    'form' => $form,
                    'data' => $data,
                    'actor_id' => get_current_user_id(),
                )
            );

            $response_data = array(
                'message' => __('Form created successfully', 'kitsune-ai-platform'),
                'form' => $form,
            );

            $response_data = apply_filters('kitsune_ai_platform_create_form_response', $response_data, $result, $data, $form);
            wp_send_json_success($response_data);
        }
    }

    /**
     * AJAX: Update Form
     */
    public function ajax_update_form() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
         if (!$id) {
            $data = $this->get_post_payload('data', array());
            if (!$data) {
                $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
            }
            $id = isset($data['id']) ? intval($data['id']) : 0;
        }

        if (!$id) {
            wp_send_json_error(array('message' => __('ID required', 'kitsune-ai-platform')));
            return;
        }

        $data = $this->get_post_payload('data', array());
        if (!$data) {
            $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }
        $data = apply_filters('kitsune_ai_platform_before_update_form_data', $data, $id);
        if (!is_array($data)) {
            wp_send_json_error(array('message' => __('Invalid form data', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-form-model.php';
        $model = new Kitsune_AI_Platform_Form_Model();

        $result = $model->update($id, $data);

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        } else {
            $form = $model->get_by_id($id);

            do_action('kitsune_ai_platform_form_updated', $id, $data, $form);
            Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                Kitsune_AI_Platform_Webhook_Events::FORM_UPDATED,
                array(
                    'form_id' => (int) $id,
                    'form' => $form,
                    'data' => $data,
                    'actor_id' => get_current_user_id(),
                )
            );

            $response_data = array(
                'message' => __('Form updated successfully', 'kitsune-ai-platform'),
                'form' => $form,
            );

            $response_data = apply_filters('kitsune_ai_platform_update_form_response', $response_data, $id, $data, $form);
            wp_send_json_success($response_data);
        }
    }

    /**
     * AJAX: Delete Form
     */
    public function ajax_delete_form() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
        if (!$id) {
            wp_send_json_error(array('message' => __('ID required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/models/class-kitsune-ai-platform-form-model.php';
        $model = new Kitsune_AI_Platform_Form_Model();
        $form = $model->get_by_id($id);
        $result = $model->delete($id);

        if ($result) {
            do_action('kitsune_ai_platform_form_deleted', $id, $form);
            Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
                Kitsune_AI_Platform_Webhook_Events::FORM_DELETED,
                array(
                    'form_id' => (int) $id,
                    'form' => $form,
                    'actor_id' => get_current_user_id(),
                )
            );

            $response_data = array('message' => __('Form deleted successfully', 'kitsune-ai-platform'));
            $response_data = apply_filters('kitsune_ai_platform_delete_form_response', $response_data, $id, $form);
            wp_send_json_success($response_data);
        } else {
            wp_send_json_error(array('message' => __('Failed to delete form', 'kitsune-ai-platform')));
        }
    }

    /**
     * AJAX: Get Form Submissions
     */
    public function ajax_get_form_submissions() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        $form_id = isset($_GET['form_id']) ? intval($_GET['form_id']) : 0;
        // form_id = 0 means all forms

        $model = new Kitsune_AI_Platform_Form_Model();

        $page = isset($_GET['page']) ? max(1, intval(wp_unslash($_GET['page']))) : 1;
        $per_page = isset($_GET['per_page']) ? min(100, max(1, intval(wp_unslash($_GET['per_page'])))) : 20;
        $offset = ($page - 1) * $per_page;

        $submissions = $model->get_submissions($form_id, $per_page, $offset);
        $total = $model->count_submissions($form_id);

        wp_send_json_success(array(
            'submissions' => $submissions,
            'total' => $total,
            'page' => $page,
            'per_page' => $per_page
        ));
    }

    /**
     * AJAX: Get global form settings
     */
    public function ajax_get_form_settings() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        $defaults = array(
            'emailNotification'   => false,
            'recipientEmail'      => get_option('admin_email', ''),
            'confirmationType'    => 'message',
            'confirmationMessage' => __('Thank you for your submission! We will get back to you shortly.', 'kitsune-ai-platform'),
            'redirectUrl'         => '',
        );

        $saved    = get_option('kitsune_ai_platform_form_settings', array());
        $settings = wp_parse_args($saved, $defaults);

        wp_send_json_success(array('settings' => $settings));
    }

    /**
     * AJAX: Save global form settings
     */
    public function ajax_save_form_settings() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        $raw      = isset($_POST['settings']) ? wp_unslash($_POST['settings']) : '';
        $incoming = array();
        if (is_array($raw)) {
            $incoming = $raw;
        } elseif (is_string($raw) && $raw !== '') {
            $decoded = json_decode($raw, true);
            if (is_array($decoded)) {
                $incoming = $decoded;
            }
        }

        $settings = array(
            'emailNotification'   => !empty($incoming['emailNotification']),
            'recipientEmail'      => sanitize_email($incoming['recipientEmail'] ?? ''),
            'confirmationType'    => in_array($incoming['confirmationType'] ?? '', array('message', 'redirect'), true)
                                        ? $incoming['confirmationType']
                                        : 'message',
            'confirmationMessage' => sanitize_textarea_field($incoming['confirmationMessage'] ?? ''),
            'redirectUrl'         => esc_url_raw($incoming['redirectUrl'] ?? ''),
        );

        update_option('kitsune_ai_platform_form_settings', $settings);

        wp_send_json_success(array(
            'message'  => __('Form settings saved successfully', 'kitsune-ai-platform'),
            'settings' => $settings,
        ));
    }

    /**
     * AJAX: Generate Content
     */
    public function ajax_generate_content() {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return;
        }

        $params = $this->get_post_payload('params', array());
        if (!$params) {
            $params = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }
        $params = apply_filters('kitsune_ai_platform_before_generate_content_params', $params);
        if (!is_array($params)) {
            $params = array();
        }

        $topic = sanitize_text_field($params['topic'] ?? '');
        $description = sanitize_textarea_field($params['description'] ?? '');
        $style_instruction = sanitize_textarea_field($params['styleInstruction'] ?? ($params['style_instruction'] ?? __('Generate professional, polished content.', 'kitsune-ai-platform')));
        $length = intval($params['length'] ?? 1000);

        if (empty($topic)) {
            wp_send_json_error(array('message' => __('Topic is required', 'kitsune-ai-platform')));
            return;
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/class-kitsune-ai-platform-api.php';
        $api = new Kitsune_AI_Platform_API();

        $default_models = get_option('kitsune_ai_platform_default_models', array());
        $model = $this->extract_model_id($default_models['content'] ?? '');

        $max_tokens = min(4000, max(256, intval($length * 1.25)));

        /* translators: %d: Approximate target word count. */
        /* translators: %d: word count */
        $prompt = sprintf(__('Write an approximately %d-word article.', 'kitsune-ai-platform'), $length) . "\n";
        /* translators: %s: Article topic. */
        /* translators: %s: topic string */
        $prompt .= sprintf(__('Topic: %s', 'kitsune-ai-platform'), $topic) . "\n";
        if (!empty($description)) {
            /* translators: %s: Article description/context. */
            /* translators: %s: description string */
            $prompt .= sprintf(__('Description: %s', 'kitsune-ai-platform'), $description) . "\n";
        }
        if (!empty($style_instruction)) {
            /* translators: %s: Writing style instruction. */
            /* translators: %s: style instruction string */
            $prompt .= sprintf(__('Style: %s', 'kitsune-ai-platform'), $style_instruction) . "\n";
        }
        $prompt .= __('Return HTML content with headings and paragraphs. Do not include a title heading.', 'kitsune-ai-platform');
        $prompt = apply_filters('kitsune_ai_platform_content_generation_prompt', $prompt, $params);

        $response = $api->chatRAG(array(
            'model' => $model,
            'messages' => array(
                array('role' => 'system', 'content' => __('You are an expert content writer.', 'kitsune-ai-platform')),
                array('role' => 'user', 'content' => $prompt),
            ),
            'temperature' => 0.7,
            'max_tokens' => $max_tokens,
            'feature' => 'content',
            'rag' => array(
                'enabled' => false,
            ),
        ));

        if (empty($response['success'])) {
            wp_send_json_error(array('message' => $response['message'] ?? __('Failed to generate content', 'kitsune-ai-platform')));
            return;
        }

        $content_body = wp_kses_post($response['data']['content'] ?? '');
        if ($content_body === '') {
            wp_send_json_error(array('message' => __('Empty response from AI provider', 'kitsune-ai-platform')));
            return;
        }

        $tokens_used = $response['data']['tokens'] ?? $length;

        $response_data = array(
            'title' => $topic,
            'generated_content' => $content_body,
            'tags' => array(),
            'categories' => array(),
            'tokens' => $tokens_used,
            'model' => $response['data']['model'] ?? $model,
            'provider' => $response['data']['provider'] ?? ''
        );

        do_action('kitsune_ai_platform_content_generated', $response_data, $params, $response);
        Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
            Kitsune_AI_Platform_Webhook_Events::CONTENT_GENERATED,
            array(
                'title' => $topic,
                'generated_content' => $content_body,
                'tokens' => $tokens_used,
                'model' => $response_data['model'],
                'provider' => $response_data['provider'],
                'params' => $params,
                'actor_id' => get_current_user_id(),
            )
        );

        $response_data = apply_filters('kitsune_ai_platform_generate_content_response', $response_data, $params, $response);
        wp_send_json_success($response_data);
    }

    /**
     * AJAX: Save Generated Content as Draft Post
     */
    public function ajax_save_generated_content() {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return;
        }

        $data = $this->get_post_payload('data', array());
        if (!$data) {
            $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }
        $data = apply_filters('kitsune_ai_platform_before_save_generated_content_data', $data);
        if (!is_array($data)) {
            wp_send_json_error(array('message' => __('Invalid content data', 'kitsune-ai-platform')));
            return;
        }
        
        $title = sanitize_text_field($data['title'] ?? 'Untitled');
        $content = wp_kses_post($data['content'] ?? '');
        $tags = isset($data['tags']) ? array_map('sanitize_text_field', (array)$data['tags']) : array();
        $categories = isset($data['categories']) ? array_map('sanitize_text_field', (array)$data['categories']) : array();
        $post_type = sanitize_key($data['post_type'] ?? 'post');
        if (!in_array($post_type, array('post', 'page'), true)) {
            $post_type = 'post';
        }
        
        $post_data = array(
            'post_title'    => $title,
            'post_content'  => $content,
            'post_status'   => 'draft',
            'post_type'     => $post_type,
            'post_author'   => get_current_user_id()
        );
        $filtered_post_data = apply_filters('kitsune_ai_platform_before_save_generated_content_post_data', $post_data, $data);
        if (is_array($filtered_post_data) && !empty($filtered_post_data)) {
            $post_data = $filtered_post_data;
        }

        $post_id = wp_insert_post($post_data, true);

        if (is_wp_error($post_id)) {
            wp_send_json_error(array('message' => $post_id->get_error_message()));
            return;
        }

        // Set Categories
        if (!empty($categories)) {
            $cat_ids = array();
            foreach ($categories as $cat_name) {
                // Check if exists
                $term = term_exists($cat_name, 'category');
                if ($term) {
                    $cat_ids[] = is_array($term) ? $term['term_id'] : $term;
                } else {
                    // Create new
                    $new_term = wp_insert_term($cat_name, 'category');
                    if (!is_wp_error($new_term)) {
                        $cat_ids[] = $new_term['term_id'];
                    }
                }
            }
            if (!empty($cat_ids)) {
                wp_set_post_categories($post_id, $cat_ids);
            }
        }

        // Set Tags
        if (!empty($tags)) {
            wp_set_post_tags($post_id, $tags);
        }

        $response_data = array(
            'message' => __('Draft saved successfully', 'kitsune-ai-platform'),
            'post_id' => $post_id,
            'edit_link' => get_edit_post_link($post_id, 'raw'),
            'post_type' => $post_type
        );

        do_action('kitsune_ai_platform_content_saved', $post_id, $post_data, $data, $response_data);
        Kitsune_AI_Platform_Webhook_Dispatcher::dispatch(
            Kitsune_AI_Platform_Webhook_Events::CONTENT_SAVED,
            array(
                'post_id' => (int) $post_id,
                'post_type' => $post_type,
                'title' => $title,
                'edit_link' => $response_data['edit_link'],
                'tags' => $tags,
                'categories' => $categories,
                'actor_id' => get_current_user_id(),
            )
        );

        $response_data = apply_filters('kitsune_ai_platform_save_generated_content_response', $response_data, $post_id, $post_data, $data);
        wp_send_json_success($response_data);
    }

    /**
     * AJAX: Generate Image
     */
    public function ajax_generate_image() {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        if (!current_user_can('edit_posts')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return;
        }

        $data = $this->get_post_payload('data', array());
        if (!$data) {
            $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }

        $prompt       = sanitize_text_field($data['prompt'] ?? '');
        $prompt_style = sanitize_text_field($data['prompt_style'] ?? ''); // UI style preset (Photorealistic, Digital Art, etc.)
        $style        = sanitize_text_field($data['style'] ?? '');        // API-level style param (e.g. vivid/natural for dall-e-3)
        $quality      = sanitize_text_field($data['quality'] ?? 'standard'); // dall-e-3 quality: standard|hd
        $aspect_ratio = sanitize_text_field($data['aspect_ratio'] ?? '16:9');
        $variations   = min(4, max(1, intval($data['variations'] ?? 1)));

        if ($prompt === '') {
            wp_send_json_error(array('message' => __('Prompt is required', 'kitsune-ai-platform')));
            return;
        }

        // Append prompt style preset to the prompt so the model follows it.
        if ($prompt_style !== '') {
            $prompt = $prompt . ', ' . $prompt_style . ' style';
        }

        require_once KITSUNE_AI_PLATFORM_PLUGIN_DIR . 'includes/class-kitsune-ai-platform-api.php';
        $api = new Kitsune_AI_Platform_API();

        // Use model from frontend if provided; fall back to the saved default.
        $frontend_model = sanitize_text_field($data['model'] ?? '');
        if ($frontend_model !== '') {
            $model = $this->extract_model_id($frontend_model);
        } else {
            $default_models = get_option('kitsune_ai_platform_default_models', array());
            $model = $this->extract_model_id($default_models['imageGen'] ?? '');
        }

        $images = array();
        for ($i = 0; $i < $variations; $i++) {
            $response = $api->generate_image($prompt, array(
                'model'        => $model,
                'style'        => $style,
                'quality'      => $quality,
                'aspect_ratio' => $aspect_ratio,
                'feature'      => 'image'
            ));

            if (empty($response['success'])) {
                wp_send_json_error(array('message' => $response['message'] ?? __('Image generation failed', 'kitsune-ai-platform')));
                return;
            }

            $image_url = $response['data']['url'] ?? '';
            if ($image_url === '') {
                wp_send_json_error(array('message' => __('Image generation failed', 'kitsune-ai-platform')));
                return;
            }

            $images[] = array(
                'id' => uniqid('ai_img_', true),
                'url' => esc_url_raw($image_url),
                'prompt' => $prompt,
                'style' => $style,
                'aspect_ratio' => $aspect_ratio,
                'model' => $response['data']['model'] ?? $model,
                'provider' => $response['data']['provider'] ?? '',
                'filename' => sanitize_file_name('ai-image-' . ($i + 1) . '.png'),
            );
        }

        wp_send_json_success(array(
            'images' => $images,
            'variations' => $variations
        ));
    }

    /**
     * AJAX: Save Generated Image as Attachment
     */
    public function ajax_save_generated_image() {
        check_ajax_referer('kitsune_ai_platform_nonce', 'nonce');

        if (!current_user_can('upload_files')) {
            wp_send_json_error(array('message' => __('Permission denied', 'kitsune-ai-platform')));
            return;
        }

        $data = $this->get_post_payload('data', array());
        if (!$data) {
            $data = map_deep(wp_unslash($_POST), 'sanitize_text_field');
        }

        $url = esc_url_raw($data['url'] ?? '');
        $title = sanitize_text_field($data['title'] ?? '');

        if (empty($url)) {
            wp_send_json_error(array('message' => __('Image URL is required', 'kitsune-ai-platform')));
            return;
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp = download_url($url);
        if (is_wp_error($tmp)) {
            wp_send_json_error(array('message' => $tmp->get_error_message()));
            return;
        }

        $parsed_path = parse_url($url, PHP_URL_PATH);
        $basename = is_string($parsed_path) ? basename($parsed_path) : '';
        if ($basename === '') {
            $basename = 'ai-generated-image.png';
        }

        $file_array = array(
            'name' => sanitize_file_name($basename),
            'tmp_name' => $tmp
        );

        $attachment_id = media_handle_sideload($file_array, 0, $title);

        if (is_wp_error($attachment_id)) {
            if (isset($tmp) && file_exists($tmp)) {
                if (!unlink($tmp) && defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('AI Platform: Failed to delete temporary image file: ' . $tmp);
                }
            }
            wp_send_json_error(array('message' => $attachment_id->get_error_message()));
            return;
        }

        wp_send_json_success(array(
            'message' => __('Image saved successfully', 'kitsune-ai-platform'),
            'attachment_id' => $attachment_id,
            'url' => wp_get_attachment_url($attachment_id)
        ));
    }

    /**
     * Extract model ID from provider/model payloads.
     *
     * @param mixed $value
     * @return string
     */
    private function extract_model_id($value) {
        if (is_array($value)) {
            return sanitize_text_field($value['model'] ?? '');
        }

        $value = is_string($value) ? trim($value) : '';
        if ($value === '') {
            return '';
        }

        $parts = explode(':', $value, 2);
        return sanitize_text_field(count($parts) === 2 ? $parts[1] : $value);
    }

    /**
     * AJAX: Get Form Templates
     */
    public function ajax_get_form_templates() {
        if (!$this->verify_admin_request('content')) {
            return;
        }

        // Define some basic templates
        $templates = array(
            array(
                'id' => 'contact_form',
                'name' => __('Smart Contact Form', 'kitsune-ai-platform'),
                'description' => __('A contact form that uses AI to categorize inquiries.', 'kitsune-ai-platform'),
                'fields' => json_encode(array(
                    array('type' => 'text', 'label' => __('Name', 'kitsune-ai-platform'), 'required' => true),
                    array('type' => 'email', 'label' => __('Email', 'kitsune-ai-platform'), 'required' => true),
                    array('type' => 'textarea', 'label' => __('Message', 'kitsune-ai-platform'), 'required' => true)
                )),
                'settings' => json_encode(array(
                    'ai_analysis' => true,
                    'ai_response' => false
                ))
            ),
            array(
                'id' => 'feedback_form',
                'name' => __('Feedback Form', 'kitsune-ai-platform'),
                'description' => __('Collect user feedback with sentiment analysis.', 'kitsune-ai-platform'),
                'fields' => json_encode(array(
                    array('type' => 'text', 'label' => __('Name', 'kitsune-ai-platform'), 'required' => false),
                    array('type' => 'rating', 'label' => __('Rating', 'kitsune-ai-platform'), 'required' => true),
                    array('type' => 'textarea', 'label' => __('Comments', 'kitsune-ai-platform'), 'required' => true)
                )),
                'settings' => json_encode(array(
                    'ai_analysis' => true,
                    'sentiment_analysis' => true
                ))
            ),
            array(
                'id' => 'lead_gen',
                'name' => __('Lead Generation', 'kitsune-ai-platform'),
                'description' => __('Capture leads and qualify them with AI.', 'kitsune-ai-platform'),
                'fields' => json_encode(array(
                    array('type' => 'text', 'label' => __('Company Name', 'kitsune-ai-platform'), 'required' => true),
                    array('type' => 'text', 'label' => __('Contact Person', 'kitsune-ai-platform'), 'required' => true),
                    array('type' => 'email', 'label' => __('Email', 'kitsune-ai-platform'), 'required' => true),
                    array('type' => 'select', 'label' => __('Budget', 'kitsune-ai-platform'), 'options' => array(__('< $1k', 'kitsune-ai-platform'), __('$1k - $5k', 'kitsune-ai-platform'), __('> $5k', 'kitsune-ai-platform')), 'required' => true)
                )),
                'settings' => json_encode(array(
                    'ai_qualification' => true,
                    'notification' => true
                ))
            )
        );

        wp_send_json_success(array('templates' => $templates));
    }

}
