<?php

/**
 * AI Magic Prompt Manager
 *
 * Manages custom prompts, templates, and prompt customization
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.8
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */

/**
 * Prompt Manager Class
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 * @author     AI Magic <info@insya.com>
 */
class AI_Magic_Prompt_Manager
{
    /**
     * Available prompt variables
     *
     * @var array
     */
    private static $variables = array(
        'title' => array(
            'label' => 'Title/Topic',
            'description' => 'Main topic or title of the content',
            'default' => ''
        ),
        'language' => array(
            'label' => 'Language',
            'description' => 'Content language (e.g., English, Turkish)',
            'default' => 'English'
        ),
        'style' => array(
            'label' => 'Writing Style',
            'description' => 'Style of writing (informative, creative, persuasive)',
            'default' => 'informative'
        ),
        'tone' => array(
            'label' => 'Tone',
            'description' => 'Tone of voice (professional, casual, friendly)',
            'default' => 'professional'
        ),
        'word_count' => array(
            'label' => 'Word Count',
            'description' => 'Target word count',
            'default' => '500'
        ),
        'keywords' => array(
            'label' => 'Keywords',
            'description' => 'SEO focus keywords',
            'default' => ''
        ),
        'audience' => array(
            'label' => 'Target Audience',
            'description' => 'Who is the content for',
            'default' => 'general audience'
        ),
        'purpose' => array(
            'label' => 'Purpose',
            'description' => 'Goal of the content',
            'default' => 'inform and educate'
        ),
        'format' => array(
            'label' => 'Format',
            'description' => 'Content format (blog post, listicle, guide)',
            'default' => 'blog post'
        ),
        'instructions' => array(
            'label' => 'Custom Instructions',
            'description' => 'Additional instructions',
            'default' => ''
        )
    );

    /**
     * Default prompt templates
     *
     * @var array
     */
    private static $default_prompts = array(
        'blog_post' => array(
            'name' => 'Blog Post',
            'category' => 'content',
            'description' => 'Generate a comprehensive blog post',
            'prompt' => 'Write a comprehensive blog post about "{{title}}" in {{language}}.

Requirements:
- Word count: approximately {{word_count}} words
- Writing style: {{style}}
- Tone: {{tone}}
- Target audience: {{audience}}

Structure:
1. Engaging introduction that hooks the reader
2. Main body with clear sections and subheadings (use H2, H3 tags)
3. Include practical examples and actionable tips
4. Conclusion with key takeaways

{{#if keywords}}
SEO Keywords to include: {{keywords}}
{{/if}}

{{#if instructions}}
Additional instructions: {{instructions}}
{{/if}}

Format the output as HTML with proper heading tags (<h2>, <h3>), paragraphs (<p>), and lists (<ul>, <ol>) where appropriate.'
        ),
        'product_description' => array(
            'name' => 'Product Description',
            'category' => 'ecommerce',
            'description' => 'Create compelling product descriptions',
            'prompt' => 'Write a compelling product description for "{{title}}" in {{language}}.

Requirements:
- Style: {{style}}
- Tone: {{tone}}
- Length: {{word_count}} words

Include:
1. Attention-grabbing headline
2. Key features and benefits (focus on benefits)
3. Technical specifications (if applicable)
4. Use cases and who it\'s for
5. Call-to-action

{{#if keywords}}
SEO Keywords: {{keywords}}
{{/if}}

{{#if instructions}}
Additional requirements: {{instructions}}
{{/if}}

Format as HTML.'
        ),
        'how_to_guide' => array(
            'name' => 'How-To Guide',
            'category' => 'tutorial',
            'description' => 'Create step-by-step tutorials',
            'prompt' => 'Create a detailed how-to guide on "{{title}}" in {{language}}.

Requirements:
- Target word count: {{word_count}} words
- Style: {{style}}
- Tone: {{tone}}
- Audience: {{audience}}

Structure:
1. Introduction - explain what readers will learn
2. Prerequisites/Requirements (if any)
3. Step-by-step instructions with clear numbering
4. Tips and best practices
5. Common mistakes to avoid
6. Conclusion

{{#if keywords}}
Include these keywords: {{keywords}}
{{/if}}

{{#if instructions}}
Special instructions: {{instructions}}
{{/if}}

Format with proper HTML: headings, ordered lists for steps, unordered lists for tips.'
        ),
        'listicle' => array(
            'name' => 'Listicle',
            'category' => 'content',
            'description' => 'Generate list-based articles',
            'prompt' => 'Write a listicle article titled "{{title}}" in {{language}}.

Requirements:
- Create a numbered list article with 10-15 items
- Style: {{style}}
- Tone: {{tone}}
- Word count per item: ~50-100 words
- Total: approximately {{word_count}} words

For each item include:
1. A catchy subheading
2. Detailed explanation
3. Practical tip or example

Include:
- Engaging introduction
- Strong conclusion summarizing key points

{{#if keywords}}
SEO Keywords: {{keywords}}
{{/if}}

{{#if instructions}}
Additional notes: {{instructions}}
{{/if}}

Format as HTML with proper structure.'
        ),
        'meta_description' => array(
            'name' => 'Meta Description',
            'category' => 'seo',
            'description' => 'Generate SEO meta descriptions',
            'prompt' => 'Write a compelling SEO meta description for: "{{title}}"

Requirements:
- Length: 150-160 characters
- Language: {{language}}
- Tone: {{tone}}
- Include a call-to-action
- Be engaging and encourage clicks

{{#if keywords}}
Include these keywords naturally: {{keywords}}
{{/if}}

Return only the meta description text, no additional formatting.'
        ),
        'social_media' => array(
            'name' => 'Social Media Post',
            'category' => 'social',
            'description' => 'Create social media content',
            'prompt' => 'Create social media content about "{{title}}" in {{language}}.

Platform-specific versions:
1. Twitter/X (280 characters max)
2. LinkedIn (professional, 1-3 paragraphs)
3. Facebook (engaging, conversational)
4. Instagram caption (with emoji, hashtags)

Tone: {{tone}}
Style: {{style}}

{{#if keywords}}
Include hashtags related to: {{keywords}}
{{/if}}

{{#if instructions}}
Additional notes: {{instructions}}
{{/if}}'
        ),
        'email_newsletter' => array(
            'name' => 'Email Newsletter',
            'category' => 'email',
            'description' => 'Create email newsletter content',
            'prompt' => 'Write an email newsletter about "{{title}}" in {{language}}.

Requirements:
- Subject line (compelling, under 50 characters)
- Preview text (40-90 characters)
- Body content
- Word count: approximately {{word_count}} words
- Style: {{style}}
- Tone: {{tone}}

Structure:
1. Catchy subject line
2. Engaging opener
3. Main content with value
4. Clear call-to-action
5. Sign-off

{{#if instructions}}
Additional requirements: {{instructions}}
{{/if}}

Format appropriately for email.'
        ),
        'landing_page' => array(
            'name' => 'Landing Page',
            'category' => 'page',
            'description' => 'Create landing page copy',
            'prompt' => 'Write landing page copy for "{{title}}" in {{language}}.

Requirements:
- Style: {{style}} and persuasive
- Tone: {{tone}}
- Target audience: {{audience}}
- Purpose: {{purpose}}

Sections:
1. Hero headline and subheadline
2. Problem statement (pain points)
3. Solution (how you help)
4. Features and benefits (3-5 items)
5. Social proof placeholder
6. FAQ section (3-5 questions)
7. Final CTA

{{#if keywords}}
SEO Keywords: {{keywords}}
{{/if}}

{{#if instructions}}
Special instructions: {{instructions}}
{{/if}}

Format as HTML with clear section structure.'
        ),
        'about_page' => array(
            'name' => 'About Page',
            'category' => 'page',
            'description' => 'Create about page content',
            'prompt' => 'Write an About page for "{{title}}" in {{language}}.

Requirements:
- Style: {{style}}
- Tone: {{tone}}
- Word count: approximately {{word_count}} words

Include sections:
1. Introduction/Mission statement
2. Our story
3. What we do
4. Our values
5. Team section placeholder
6. Why choose us

{{#if instructions}}
Additional information: {{instructions}}
{{/if}}

Format as HTML with proper structure.'
        ),
        'faq_page' => array(
            'name' => 'FAQ Page',
            'category' => 'page',
            'description' => 'Generate FAQ content',
            'prompt' => 'Create FAQ content for "{{title}}" in {{language}}.

Requirements:
- Generate 10-15 relevant questions and answers
- Style: {{style}}
- Tone: {{tone}}
- Make answers comprehensive but concise

Categories to cover:
1. General questions
2. Product/Service specific
3. Pricing/Plans (if applicable)
4. Support/Help

{{#if keywords}}
Related topics: {{keywords}}
{{/if}}

{{#if instructions}}
Focus areas: {{instructions}}
{{/if}}

Format as HTML using definition lists or accordion-friendly structure.'
        )
    );

    /**
     * Get available variables
     *
     * @since    1.0.8
     * @return   array    List of variables
     */
    public static function get_variables()
    {
        return self::$variables;
    }

    /**
     * Get default prompts
     *
     * @since    1.0.8
     * @return   array    List of default prompts
     */
    public static function get_default_prompts()
    {
        return self::$default_prompts;
    }

    /**
     * Get prompt by key
     *
     * @since    1.0.8
     * @param    string    $key    Prompt key
     * @return   array|null        Prompt data or null
     */
    public static function get_prompt($key)
    {
        return isset(self::$default_prompts[$key]) ? self::$default_prompts[$key] : null;
    }

    /**
     * Get prompts by category
     *
     * @since    1.0.8
     * @param    string    $category    Category name
     * @return   array                  List of prompts in category
     */
    public static function get_prompts_by_category($category)
    {
        $prompts = array();
        foreach (self::$default_prompts as $key => $prompt) {
            if ($prompt['category'] === $category) {
                $prompts[$key] = $prompt;
            }
        }
        return $prompts;
    }

    /**
     * Get prompt categories
     *
     * @since    1.0.8
     * @return   array    List of categories
     */
    public static function get_categories()
    {
        return array(
            'content' => __('Content Creation', 'ai_magic'),
            'ecommerce' => __('E-commerce', 'ai_magic'),
            'tutorial' => __('Tutorials & Guides', 'ai_magic'),
            'seo' => __('SEO', 'ai_magic'),
            'social' => __('Social Media', 'ai_magic'),
            'email' => __('Email Marketing', 'ai_magic'),
            'page' => __('Page Templates', 'ai_magic'),
            'custom' => __('Custom', 'ai_magic')
        );
    }

    /**
     * Process prompt with variables
     *
     * @since    1.0.8
     * @param    string    $prompt      Prompt template
     * @param    array     $values      Variable values
     * @return   string                 Processed prompt
     */
    public static function process_prompt($prompt, $values)
    {
        // Replace simple variables
        foreach ($values as $key => $value) {
            $prompt = str_replace('{{' . $key . '}}', $value, $prompt);
        }

        // Handle conditional blocks {{#if variable}}...{{/if}}
        $prompt = preg_replace_callback(
            '/\{\{#if\s+(\w+)\}\}(.*?)\{\{\/if\}\}/s',
            function ($matches) use ($values) {
                $variable = $matches[1];
                $content = $matches[2];
                
                if (!empty($values[$variable])) {
                    return $content;
                }
                return '';
            },
            $prompt
        );

        // Clean up any remaining empty variable placeholders
        $prompt = preg_replace('/\{\{[^}]+\}\}/', '', $prompt);

        return trim($prompt);
    }

    /**
     * Save custom prompt to database
     *
     * @since    1.0.8
     * @param    array     $data    Prompt data
     * @return   int|false          Prompt ID or false on failure
     */
    public static function save_custom_prompt($data)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_prompts';

        $current_time = current_time('mysql');

        if (!empty($data['id'])) {
            // Update existing
            $result = $wpdb->update(
                $table,
                array(
                    'name' => sanitize_text_field($data['name']),
                    'description' => sanitize_textarea_field($data['description']),
                    'prompt' => $data['prompt'],
                    'variables' => isset($data['variables']) ? wp_json_encode($data['variables']) : '[]',
                    'category' => sanitize_text_field($data['category']),
                    'updated_at' => $current_time
                ),
                array('id' => absint($data['id'])),
                array('%s', '%s', '%s', '%s', '%s', '%s'),
                array('%d')
            );

            return $result !== false ? absint($data['id']) : false;
        } else {
            // Insert new
            $result = $wpdb->insert(
                $table,
                array(
                    'user_id' => get_current_user_id(),
                    'name' => sanitize_text_field($data['name']),
                    'description' => sanitize_textarea_field($data['description']),
                    'prompt' => $data['prompt'],
                    'variables' => isset($data['variables']) ? wp_json_encode($data['variables']) : '[]',
                    'category' => sanitize_text_field($data['category']),
                    'usage_count' => 0,
                    'created_at' => $current_time,
                    'updated_at' => $current_time
                ),
                array('%d', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s')
            );

            return $result ? $wpdb->insert_id : false;
        }
    }

    /**
     * Get custom prompts for current user
     *
     * @since    1.0.8
     * @param    string    $category    Optional category filter
     * @return   array                  List of custom prompts
     */
    public static function get_custom_prompts($category = '')
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_prompts';
        $user_id = get_current_user_id();

        if (!empty($category)) {
            $prompts = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table WHERE user_id = %d AND category = %s ORDER BY usage_count DESC, name ASC",
                $user_id,
                $category
            ));
        } else {
            $prompts = $wpdb->get_results($wpdb->prepare(
                "SELECT * FROM $table WHERE user_id = %d ORDER BY usage_count DESC, name ASC",
                $user_id
            ));
        }

        return $prompts;
    }

    /**
     * Delete custom prompt
     *
     * @since    1.0.8
     * @param    int       $prompt_id    Prompt ID
     * @return   bool                    Success status
     */
    public static function delete_custom_prompt($prompt_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_prompts';

        return $wpdb->delete(
            $table,
            array(
                'id' => absint($prompt_id),
                'user_id' => get_current_user_id()
            ),
            array('%d', '%d')
        ) !== false;
    }

    /**
     * Increment usage count for a prompt
     *
     * @since    1.0.8
     * @param    int       $prompt_id    Prompt ID
     * @return   bool                    Success status
     */
    public static function increment_usage($prompt_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_prompts';

        return $wpdb->query($wpdb->prepare(
            "UPDATE $table SET usage_count = usage_count + 1 WHERE id = %d",
            absint($prompt_id)
        )) !== false;
    }

    /**
     * Build final prompt from template and options
     *
     * @since    1.0.8
     * @param    string    $template_key    Template key or custom prompt ID
     * @param    array     $options         Options including variable values
     * @return   string                     Final processed prompt
     */
    public static function build_prompt($template_key, $options = array())
    {
        // Check if it's a default template
        if (isset(self::$default_prompts[$template_key])) {
            $prompt_template = self::$default_prompts[$template_key]['prompt'];
        } else {
            // Try to get from database
            global $wpdb;
            $table = $wpdb->prefix . 'ai_magic_prompts';
            $prompt = $wpdb->get_var($wpdb->prepare(
                "SELECT prompt FROM $table WHERE id = %d",
                absint($template_key)
            ));

            if ($prompt) {
                $prompt_template = $prompt;
                self::increment_usage(absint($template_key));
            } else {
                // Return basic prompt if nothing found
                $prompt_template = 'Write content about "{{title}}" in {{language}}. Style: {{style}}, Tone: {{tone}}.';
            }
        }

        // Merge with defaults
        $defaults = array();
        foreach (self::$variables as $key => $var) {
            $defaults[$key] = $var['default'];
        }
        $values = wp_parse_args($options, $defaults);

        return self::process_prompt($prompt_template, $values);
    }
}
