<?php

if (!defined('ABSPATH')) {
    exit;
}

class ThiaAjaxHandler {
    private $api;
    
    public function __construct() {
        $this->api = new ThiaAPIHandler();
        add_action('wp_ajax_thia_ai_action', array($this, 'handle_request'));
    }
    
    public function handle_request() {
        global $wpdb;
        
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'thia_nonce' ) ) {
        wp_send_json_error( 'Security check failed' );
        return;
        }
        
        // Check if array index exists, unslash, and sanitize
        $action = isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) : '';
        $text = isset($_POST['content']) ? wp_kses_post(wp_unslash($_POST['content'])) : '';
        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';

        $table_settings = $wpdb->prefix . 'thiaide_content_settings';
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $language = $wpdb->get_var( "SELECT language FROM `" . esc_sql( $table_settings ) . "` WHERE id = 1" );

        if (empty($language)) {
            wp_send_json_error('Please select a language in Thia AI settings first');
            return;
        }
        
        if ($action === 'generate' && empty($title)) {
            wp_send_json_error('Product title is required');
            return;
        }
        
        if ($action !== 'generate' && empty($text)) {
            wp_send_json_error('Content is required');
            return;
        }
        
        $style = get_option('thia_ai_site_style', 'professional');
        $length = get_option('thia_ai_content_length', 'medium');
        
        $prompt = '';
        
        switch ($action) {
            case 'generate':
                $prompt = "Write a product description in {$language} language based on this title: '{$title}'. 
                Use HTML formatting - add paragraphs, headings (h2, h3), bullet points where appropriate. 
                IMPORTANT: Use ONLY valid HTML tags. Return only the description, no extra text, no explanations.";
                break;
                
            case 'grammar':
                $prompt = "Fix all grammar and spelling errors in this text. 
                The text is in {$language} language.
                CRITICAL RULES:
                - Keep ALL HTML tags exactly as they are
                - Keep ALL images, links, and formatting
                - ONLY fix grammar and spelling mistakes in the text content
                - Do NOT remove, add, or change any HTML tags or attributes
                - Return only the corrected text with original HTML structure preserved
                
                Text to fix:\n\n{$text}";
                break;
                
            case 'format':
                $prompt = "Format this text with proper HTML tags while keeping all existing content.
                The text is in {$language} language.
                CRITICAL RULES:
                - Keep ALL images, links, and media intact
                - Keep ALL existing HTML tags
                - ONLY add missing paragraphs (<p>), headings (<h2>, <h3>), and bullet points (<ul>, <li>) where appropriate
                - Do NOT remove any content or existing formatting
                - Return only the formatted text with preserved HTML structure
                
                Text to format:\n\n{$text}";
                break;
                
            case 'readability':
                $prompt = "Improve the readability of this text but preserve ALL formatting and media.
                The text is in {$language} language.
                CRITICAL RULES:
                - DO NOT remove or alter ANY images, photos, or graphics
                - DO NOT remove or alter ANY HTML tags, links, or formatting
                - Keep ALL media content exactly as it is
                - ONLY improve the text flow, sentence structure, and word choice
                - Keep the same meaning and all original information
                - Preserve all paragraph breaks and headings
                - Return only the improved text with original HTML and media preserved
                
                Text to improve:\n\n{$text}";
                break;
                
            case 'translate':
                $target_language = $language;
                $prompt = "Translate this text to {$target_language} language.
                CRITICAL RULES:
                - Keep ALL HTML tags exactly as they are
                - Keep ALL images, links, and media intact
                - Keep ALL formatting, headings, lists, and structure
                - ONLY translate the text content between HTML tags
                - Do NOT translate URLs, alt text, or HTML attributes
                - Preserve all spacing, line breaks, and HTML structure
                - Return only the translated text with original HTML and media preserved
                
                Text to translate:\n\n{$text}";
                break;
                
            default:
                wp_send_json_error('Unknown action');
                return;
        }
        
        $result = $this->api->call($prompt);
        
        if (isset($result['error'])) {
            wp_send_json_error($result['error']);
        } else {
            wp_send_json_success($result['text']);
        }
    }
}