<?php

/**
 * Content templates management for AI Magic plugin
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.7
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */

/**
 * Manages content templates
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 * @author     AI Magic <info@insya.com>
 */
class Ai_Magic_Templates
{
    /**
     * Get all templates
     *
     * @since    1.0.7
     * @param    string    $category  Optional category filter
     * @return   array                Array of template objects
     */
    public static function get_templates($category = '')
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_templates';

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

        return $templates;
    }

    /**
     * Get template by ID
     *
     * @since    1.0.7
     * @param    int    $template_id  Template ID
     * @return   object|null          Template object or null
     */
    public static function get_template($template_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_templates';

        return $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table WHERE id = %d",
            $template_id
        ));
    }

    /**
     * Create new template
     *
     * @since    1.0.7
     * @param    array    $data  Template data
     * @return   int|false       Template ID or false on failure
     */
    public static function create_template($data)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_templates';

        $current_time = current_time('mysql');

        $result = $wpdb->insert(
            $table,
            array(
                'name' => sanitize_text_field($data['name']),
                'description' => sanitize_textarea_field($data['description']),
                'category' => sanitize_text_field($data['category']),
                'prompt_template' => $data['prompt_template'],
                'variables' => isset($data['variables']) ? wp_json_encode($data['variables']) : '[]',
                'is_default' => 0,
                'user_id' => get_current_user_id(),
                'created_at' => $current_time,
                'updated_at' => $current_time
            ),
            array('%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s')
        );

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

    /**
     * Update template
     *
     * @since    1.0.7
     * @param    int      $template_id  Template ID
     * @param    array    $data         Template data
     * @return   bool                   Success status
     */
    public static function update_template($template_id, $data)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_templates';

        $current_time = current_time('mysql');

        $result = $wpdb->update(
            $table,
            array(
                'name' => sanitize_text_field($data['name']),
                'description' => sanitize_textarea_field($data['description']),
                'category' => sanitize_text_field($data['category']),
                'prompt_template' => $data['prompt_template'],
                'variables' => isset($data['variables']) ? wp_json_encode($data['variables']) : '[]',
                'updated_at' => $current_time
            ),
            array('id' => $template_id),
            array('%s', '%s', '%s', '%s', '%s', '%s'),
            array('%d')
        );

        return $result !== false;
    }

    /**
     * Delete template
     *
     * @since    1.0.7
     * @param    int     $template_id  Template ID
     * @return   bool                  Success status
     */
    public static function delete_template($template_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_templates';

        // Don't allow deleting default templates
        $template = self::get_template($template_id);
        if ($template && $template->is_default == 1) {
            return false;
        }

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

    /**
     * Process template with variables
     *
     * @since    1.0.7
     * @param    int      $template_id  Template ID
     * @param    array    $variables    Variable values
     * @return   string|false           Processed prompt or false
     */
    public static function process_template($template_id, $variables)
    {
        $template = self::get_template($template_id);
        if (!$template) {
            return false;
        }

        $prompt = $template->prompt_template;

        // Replace variables in template
        foreach ($variables as $key => $value) {
            $prompt = str_replace('{{' . $key . '}}', $value, $prompt);
        }

        return $prompt;
    }

    /**
     * Get template categories
     *
     * @since    1.0.7
     * @return   array    Array of categories
     */
    public static function get_categories()
    {
        return array(
            'blog' => __('Blog Posts', 'ai_magic'),
            'tutorial' => __('Tutorials & Guides', 'ai_magic'),
            'review' => __('Reviews', 'ai_magic'),
            'ecommerce' => __('E-commerce', 'ai_magic'),
            'social' => __('Social Media', 'ai_magic'),
            'email' => __('Email Marketing', 'ai_magic'),
            'page' => __('Page Templates', 'ai_magic'),
            'custom' => __('Custom', 'ai_magic')
        );
    }

    /**
     * Get page-specific templates
     *
     * @since    1.0.8
     * @return   array    Array of page templates
     */
    public static function get_page_templates()
    {
        return array(
            'landing_page' => array(
                'name' => __('Landing Page', 'ai_magic'),
                'description' => __('High-converting landing page with hero, features, and CTA', 'ai_magic'),
                'prompt_template' => 'Create a high-converting landing page for "{{title}}". Include:
1. Compelling hero section with headline and subheadline
2. Problem/pain points section
3. Solution overview
4. Key features and benefits (3-5 items with icons)
5. Social proof section placeholder
6. FAQ section (3-5 questions)
7. Strong call-to-action

Style: {{style}}
Tone: {{tone}}
Language: {{language}}

Format as clean HTML with proper semantic structure.',
                'variables' => array('title', 'style', 'tone', 'language')
            ),
            'about_page' => array(
                'name' => __('About Us', 'ai_magic'),
                'description' => __('Company/personal about page with story and values', 'ai_magic'),
                'prompt_template' => 'Write an engaging About page for "{{title}}". Include:
1. Introduction/Mission statement
2. Our story section
3. What we do
4. Our values (3-5 core values)
5. Team section placeholder
6. Why choose us

Word count: approximately {{word_count}} words
Style: {{style}}
Tone: {{tone}}
Language: {{language}}

Format as HTML with clear sections.',
                'variables' => array('title', 'word_count', 'style', 'tone', 'language')
            ),
            'contact_page' => array(
                'name' => __('Contact Page', 'ai_magic'),
                'description' => __('Contact page with form and information', 'ai_magic'),
                'prompt_template' => 'Create content for a Contact page for "{{title}}". Include:
1. Welcoming introduction
2. Contact form fields suggestion
3. Contact information section (placeholder for address, phone, email)
4. Business hours section
5. FAQ about contacting (2-3 items)
6. Map section placeholder

Tone: {{tone}}
Language: {{language}}

Format as HTML.',
                'variables' => array('title', 'tone', 'language')
            ),
            'services_page' => array(
                'name' => __('Services Page', 'ai_magic'),
                'description' => __('Services overview with descriptions and benefits', 'ai_magic'),
                'prompt_template' => 'Create a Services page for "{{title}}". Include:
1. Services overview introduction
2. 4-6 service descriptions with:
   - Service name
   - Brief description
   - Key benefits
   - Call-to-action
3. Why choose our services
4. Process section (how we work)
5. Contact CTA

Style: {{style}}
Tone: {{tone}}
Language: {{language}}

Format as structured HTML.',
                'variables' => array('title', 'style', 'tone', 'language')
            ),
            'faq_page' => array(
                'name' => __('FAQ Page', 'ai_magic'),
                'description' => __('Frequently asked questions with answers', 'ai_magic'),
                'prompt_template' => 'Create a comprehensive FAQ page for "{{title}}". Generate 10-15 relevant questions and answers organized by category:
1. General Questions
2. Product/Service Specific
3. Pricing & Plans
4. Support & Help

Each answer should be concise but helpful.

Tone: {{tone}}
Language: {{language}}

Format as HTML with proper heading structure for accordion/expandable sections.',
                'variables' => array('title', 'tone', 'language')
            ),
            'privacy_policy' => array(
                'name' => __('Privacy Policy', 'ai_magic'),
                'description' => __('Privacy policy template for websites', 'ai_magic'),
                'prompt_template' => 'Create a privacy policy page for "{{title}}". Include standard sections:
1. Introduction
2. Information we collect
3. How we use your information
4. Cookies and tracking
5. Data sharing and disclosure
6. Data security
7. Your rights
8. Contact information
9. Policy updates

Note: This is a template and should be reviewed by legal counsel.

Language: {{language}}

Format as HTML with clear sections.',
                'variables' => array('title', 'language')
            ),
            'terms_conditions' => array(
                'name' => __('Terms & Conditions', 'ai_magic'),
                'description' => __('Terms of service template', 'ai_magic'),
                'prompt_template' => 'Create a terms and conditions page for "{{title}}". Include standard sections:
1. Agreement to Terms
2. Use of Service
3. User Accounts
4. Intellectual Property
5. Prohibited Activities
6. Limitation of Liability
7. Governing Law
8. Changes to Terms
9. Contact Information

Note: This is a template and should be reviewed by legal counsel.

Language: {{language}}

Format as HTML with clear numbered sections.',
                'variables' => array('title', 'language')
            ),
            'portfolio_page' => array(
                'name' => __('Portfolio Page', 'ai_magic'),
                'description' => __('Portfolio/work showcase page', 'ai_magic'),
                'prompt_template' => 'Create content for a Portfolio/Work page for "{{title}}". Include:
1. Introduction about your work
2. Portfolio categories/filters suggestion
3. Project card template with:
   - Project title
   - Brief description
   - Technologies/tools used
   - Results/impact
4. Client testimonials section placeholder
5. Call-to-action for new projects

Style: {{style}}
Tone: {{tone}}
Language: {{language}}

Format as HTML.',
                'variables' => array('title', 'style', 'tone', 'language')
            ),
            'pricing_page' => array(
                'name' => __('Pricing Page', 'ai_magic'),
                'description' => __('Pricing table and plan comparison', 'ai_magic'),
                'prompt_template' => 'Create a pricing page for "{{title}}". Include:
1. Pricing page headline and subheadline
2. 3 pricing tiers (Basic, Pro, Enterprise) with:
   - Price
   - Features list
   - Best for description
   - CTA button text
3. Feature comparison table
4. FAQ about pricing (3-5 questions)
5. Money-back guarantee or trust badges section
6. Enterprise/custom pricing CTA

Tone: {{tone}}
Language: {{language}}

Format as structured HTML suitable for a pricing layout.',
                'variables' => array('title', 'tone', 'language')
            )
        );
    }

    /**
     * Insert page templates to database
     *
     * @since    1.0.8
     */
    public static function insert_page_templates()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'ai_magic_templates';

        $page_templates = self::get_page_templates();
        $current_time = current_time('mysql');

        foreach ($page_templates as $key => $template) {
            // Check if template already exists
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $table WHERE name = %s AND category = 'page' AND is_default = 1",
                $template['name']
            ));

            if ($exists > 0) {
                continue;
            }

            $wpdb->insert(
                $table,
                array(
                    'name' => $template['name'],
                    'description' => $template['description'],
                    'category' => 'page',
                    'prompt_template' => $template['prompt_template'],
                    'variables' => wp_json_encode($template['variables']),
                    'is_default' => 1,
                    'user_id' => null,
                    'created_at' => $current_time,
                    'updated_at' => $current_time
                ),
                array('%s', '%s', '%s', '%s', '%s', '%d', '%d', '%s', '%s')
            );
        }
    }
}
