<?php
/**
 * Template Manager for BoostBot.
 *
 * Manages pre-built templates for AI responses.
 * Templates allow the AI to return structured data that gets rendered
 * as beautiful, consistent UI components.
 *
 * @package BoostBot
 * @since 1.1.0
 */

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class BoostBot_Template_Manager
 *
 * Registry and manager for all available templates.
 *
 * @since 1.1.0
 */
class BoostBot_Template_Manager {

    /**
     * Singleton instance.
     *
     * @var BoostBot_Template_Manager|null
     */
    private static $instance = null;

    /**
     * Templates directory path.
     *
     * @var string
     */
    const TEMPLATES_DIR = BOOSTBOT_PLUGIN_DIR . 'includes/templates/views/';

    /**
     * Available templates registry.
     *
     * Each template has:
     * - name: Display name
     * - description: What the template does
     * - schema: Field definitions with type and required flag
     * - requires_addon: Optional add-on requirement (e.g., 'woocommerce_bundles')
     *
     * @var array
     */
    private $templates = [
        // =====================================================================
        // CATEGORY 1: Basic Templates (Free/Pro)
        // =====================================================================
        
        'contact-card' => [
            'name'        => 'Contact Card',
            'description' => 'Display contact details in a styled card',
            'category'    => 'basic',
            'schema'      => [
                'name'       => [ 'type' => 'string', 'required' => true ],
                'role'       => [ 'type' => 'string', 'required' => false ],
                'department' => [ 'type' => 'string', 'required' => false ],
                'email'      => [ 'type' => 'email', 'required' => false ],
                'phone'      => [ 'type' => 'tel', 'required' => false ],
                'image'      => [ 'type' => 'url', 'required' => false ],
                'address'    => [ 'type' => 'string', 'required' => false ],
            ],
        ],

        'department-card' => [
            'name'        => 'Department Card',
            'description' => 'Display a department and its contacts',
            'category'    => 'basic',
            'schema'      => [
                'name'     => [ 'type' => 'string', 'required' => true ],
                'email'    => [ 'type' => 'email', 'required' => false ],
                'phone'    => [ 'type' => 'tel', 'required' => false ],
                'contacts' => [ 'type' => 'array', 'required' => false ],
            ],
        ],

        'faq-card' => [
            'name'        => 'FAQ Item',
            'description' => 'Display a single FAQ',
            'category'    => 'basic',
            'schema'      => [
                'question' => [ 'type' => 'string', 'required' => true ],
                'answer'   => [ 'type' => 'string', 'required' => true ],
                'links'    => [ 'type' => 'array', 'required' => false ],
            ],
        ],

        'video-embed' => [
            'name'        => 'Video Embed',
            'description' => 'Embed a YouTube/Vimeo video',
            'category'    => 'basic',
            'schema'      => [
                'url'       => [ 'type' => 'url', 'required' => true ],
                'title'     => [ 'type' => 'string', 'required' => false ],
                'thumbnail' => [ 'type' => 'url', 'required' => false ],
            ],
        ],

        // =====================================================================
        // CATEGORY 2: Products & Sales (Free/Pro)
        // =====================================================================

        'product-card' => [
            'name'        => 'Product Card',
            'description' => 'Display a single WooCommerce product',
            'category'    => 'products',
            'schema'      => [
                'id'          => [ 'type' => 'integer', 'required' => true ],
                'name'        => [ 'type' => 'string', 'required' => true ],
                'price'       => [ 'type' => 'number', 'required' => true ],
                'sale_price'  => [ 'type' => 'number', 'required' => false ],
                'image'       => [ 'type' => 'url', 'required' => false ],
                'rating'      => [ 'type' => 'number', 'required' => false ],
                'description' => [ 'type' => 'string', 'required' => false ],
                'permalink'   => [ 'type' => 'url', 'required' => false ],
                'in_stock'    => [ 'type' => 'boolean', 'required' => false ],
            ],
        ],

        'product-mini' => [
            'name'        => 'Compact Product',
            'description' => 'Image + name + price only',
            'category'    => 'products',
            'schema'      => [
                'id'             => [ 'type' => 'integer', 'required' => true ],
                'name'           => [ 'type' => 'string', 'required' => true ],
                'price'          => [ 'type' => 'number', 'required' => true ],
                'original_price' => [ 'type' => 'number', 'required' => false ],
                'image'          => [ 'type' => 'url', 'required' => false ],
                'rating'         => [ 'type' => 'number', 'required' => false ],
            ],
        ],

        'products-grid' => [
            'name'        => 'Products Grid',
            'description' => 'Display multiple products in a grid',
            'category'    => 'products',
            'schema'      => [
                'title'    => [ 'type' => 'string', 'required' => false ],
                'products' => [ 'type' => 'array', 'required' => true ],
                'columns'  => [ 'type' => 'integer', 'required' => false ],
            ],
        ],

        'coupon-card' => [
            'name'        => 'Coupon Card',
            'description' => 'Display a discount coupon',
            'category'    => 'products',
            'schema'      => [
                'code'        => [ 'type' => 'string', 'required' => true ],
                'discount'    => [ 'type' => 'string', 'required' => true ],
                'description' => [ 'type' => 'string', 'required' => false ],
                'expires'     => [ 'type' => 'string', 'required' => false ],
            ],
        ],

        // =====================================================================
        // CATEGORY 3: Services & Pricing (Free/Pro)
        // =====================================================================

        'service-card' => [
            'name'        => 'Service Card',
            'description' => 'Display a service with description and price',
            'category'    => 'services',
            'schema'      => [
                'icon'         => [ 'type' => 'string', 'required' => false ],
                'title'        => [ 'type' => 'string', 'required' => true ],
                'description'  => [ 'type' => 'string', 'required' => false ],
                'features'     => [ 'type' => 'array', 'required' => false ],
                'price'        => [ 'type' => 'number', 'required' => false ],
                'price_suffix' => [ 'type' => 'string', 'required' => false ],
                'buttons'      => [ 'type' => 'array', 'required' => false ],
            ],
        ],

        'pricing-table' => [
            'name'        => 'Pricing Table',
            'description' => 'Display 2-4 pricing packages',
            'category'    => 'services',
            'schema'      => [
                'title'           => [ 'type' => 'string', 'required' => false ],
                'packages'        => [ 'type' => 'array', 'required' => true ],
                'highlight_index' => [ 'type' => 'integer', 'required' => false ],
            ],
        ],

        'pricing-card' => [
            'name'        => 'Pricing Package Card',
            'description' => 'A single package with features list',
            'category'    => 'services',
            'schema'      => [
                'name'           => [ 'type' => 'string', 'required' => true ],
                'subtitle'       => [ 'type' => 'string', 'required' => false ],
                'features'       => [ 'type' => 'array', 'required' => true ],
                'price'          => [ 'type' => 'number', 'required' => true ],
                'price_suffix'   => [ 'type' => 'string', 'required' => false ],
                'is_highlighted' => [ 'type' => 'boolean', 'required' => false ],
                'button'         => [ 'type' => 'object', 'required' => false ],
            ],
        ],

        'feature-list' => [
            'name'        => 'Feature List',
            'description' => 'List of features with checkmarks',
            'category'    => 'services',
            'schema'      => [
                'features' => [ 'type' => 'array', 'required' => true ],
            ],
        ],

        // =====================================================================
        // CATEGORY 4: Bundle Builder (Requires woocommerce_bundles add-on)
        // =====================================================================

        'bundle-card' => [
            'name'           => 'Bundle Card',
            'description'    => 'Display a custom product bundle',
            'category'       => 'bundles',
            'requires_addon' => 'woocommerce_bundles',
            'schema'         => [
                'bundle_id'       => [ 'type' => 'integer', 'required' => false ],
                'title'           => [ 'type' => 'string', 'required' => false ],
                'products'        => [ 'type' => 'array', 'required' => true ],
                'total_price'     => [ 'type' => 'number', 'required' => true ],
                'original_price'  => [ 'type' => 'number', 'required' => false ],
                'savings'         => [ 'type' => 'number', 'required' => false ],
                'savings_percent' => [ 'type' => 'number', 'required' => false ],
                'coupon'          => [ 'type' => 'object', 'required' => false ],
                'allow_customize' => [ 'type' => 'boolean', 'required' => false ],
                'add_to_cart_url' => [ 'type' => 'url', 'required' => false ],
            ],
        ],

        'bundle-discovery' => [
            'name'           => 'Discovery Step',
            'description'    => 'A step in bundle info gathering',
            'category'       => 'bundles',
            'requires_addon' => 'woocommerce_bundles',
            'schema'         => [
                'step_id'      => [ 'type' => 'string', 'required' => true ],
                'title'        => [ 'type' => 'string', 'required' => true ],
                'subtitle'     => [ 'type' => 'string', 'required' => false ],
                'type'         => [ 'type' => 'string', 'required' => true ],
                'options'      => [ 'type' => 'array', 'required' => false ],
                'current_step' => [ 'type' => 'integer', 'required' => true ],
                'total_steps'  => [ 'type' => 'integer', 'required' => true ],
            ],
        ],

        'bundle-product-item' => [
            'name'           => 'Bundle Product Item',
            'description'    => 'Single product inside a bundle',
            'category'       => 'bundles',
            'requires_addon' => 'woocommerce_bundles',
            'schema'         => [
                'id'             => [ 'type' => 'integer', 'required' => true ],
                'name'           => [ 'type' => 'string', 'required' => true ],
                'price'          => [ 'type' => 'number', 'required' => true ],
                'original_price' => [ 'type' => 'number', 'required' => false ],
                'image'          => [ 'type' => 'url', 'required' => false ],
                'rating'         => [ 'type' => 'number', 'required' => false ],
                'permalink'      => [ 'type' => 'url', 'required' => false ],
            ],
        ],

        'bundle-summary' => [
            'name'           => 'Bundle Price Summary',
            'description'    => 'Original price, bundle price, savings breakdown',
            'category'       => 'bundles',
            'requires_addon' => 'woocommerce_bundles',
            'schema'         => [
                'original_price'  => [ 'type' => 'number', 'required' => true ],
                'total_price'     => [ 'type' => 'number', 'required' => true ],
                'savings'         => [ 'type' => 'number', 'required' => false ],
                'savings_percent' => [ 'type' => 'number', 'required' => false ],
                'coupon'          => [ 'type' => 'object', 'required' => false ],
            ],
        ],

        'bundle-savings-badge' => [
            'name'           => 'Savings Badge',
            'description'    => 'Display savings amount/percentage',
            'category'       => 'bundles',
            'requires_addon' => 'woocommerce_bundles',
            'schema'         => [
                'savings'         => [ 'type' => 'number', 'required' => true ],
                'savings_percent' => [ 'type' => 'number', 'required' => false ],
                'animated'        => [ 'type' => 'boolean', 'required' => false ],
            ],
        ],

        'bundle-actions' => [
            'name'           => 'Bundle Action Buttons',
            'description'    => 'Add to cart, customize buttons',
            'category'       => 'bundles',
            'requires_addon' => 'woocommerce_bundles',
            'schema'         => [
                'add_to_cart_url'  => [ 'type' => 'url', 'required' => true ],
                'add_to_cart_text' => [ 'type' => 'string', 'required' => false ],
                'show_customize'   => [ 'type' => 'boolean', 'required' => false ],
                'customize_text'   => [ 'type' => 'string', 'required' => false ],
            ],
        ],

        // =====================================================================
        // CATEGORY 5: Buttons & Actions (Free/Pro)
        // =====================================================================

        'cta-button' => [
            'name'        => 'Call to Action Button',
            'description' => 'Styled CTA button',
            'category'    => 'buttons',
            'schema'      => [
                'text'       => [ 'type' => 'string', 'required' => true ],
                'url'        => [ 'type' => 'url', 'required' => true ],
                'icon'       => [ 'type' => 'string', 'required' => false ],
                'variant'    => [ 'type' => 'string', 'required' => false ],
                'size'       => [ 'type' => 'string', 'required' => false ],
                'full_width' => [ 'type' => 'boolean', 'required' => false ],
                'new_tab'    => [ 'type' => 'boolean', 'required' => false ],
            ],
        ],

        'button-group' => [
            'name'        => 'Button Group',
            'description' => '2-4 buttons in a row',
            'category'    => 'buttons',
            'schema'      => [
                'buttons'   => [ 'type' => 'array', 'required' => true ],
                'alignment' => [ 'type' => 'string', 'required' => false ],
                'direction' => [ 'type' => 'string', 'required' => false ],
            ],
        ],

        'whatsapp-button' => [
            'name'        => 'WhatsApp Button',
            'description' => 'Green WhatsApp button',
            'category'    => 'buttons',
            'schema'      => [
                'phone'   => [ 'type' => 'tel', 'required' => true ],
                'message' => [ 'type' => 'string', 'required' => false ],
                'text'    => [ 'type' => 'string', 'required' => false ],
            ],
        ],

        // =====================================================================
        // CATEGORY 6: Utility Templates
        // =====================================================================

        'upgrade-required' => [
            'name'        => 'Upgrade Message',
            'description' => 'Message that feature requires upgrade',
            'category'    => 'utility',
            'schema'      => [
                'feature'     => [ 'type' => 'string', 'required' => true ],
                'addon_name'  => [ 'type' => 'string', 'required' => false ],
                'addon_price' => [ 'type' => 'number', 'required' => false ],
            ],
        ],
    ];

    /**
     * Get singleton instance.
     *
     * @return BoostBot_Template_Manager
     */
    public static function get_instance(): self {
        if ( self::$instance === null ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Get all registered templates.
     *
     * @param bool $include_restricted Include templates that require add-ons user doesn't have.
     * @return array
     */
    public function get_templates( bool $include_restricted = true ): array {
        if ( $include_restricted ) {
            return $this->templates;
        }

        // Filter out templates the user doesn't have access to
        $license = new BoostBot_License_Manager();
        
        return array_filter( $this->templates, function( $template ) use ( $license ) {
            if ( empty( $template['requires_addon'] ) ) {
                return true;
            }
            return $license->has_addon( $template['requires_addon'] );
        });
    }

    /**
     * Get a single template by ID.
     *
     * @param string $template_id The template identifier.
     * @return array|null Template data or null if not found.
     */
    public function get_template( string $template_id ): ?array {
        return $this->templates[ $template_id ] ?? null;
    }

    /**
     * Check if a template exists.
     *
     * @param string $template_id The template identifier.
     * @return bool
     */
    public function template_exists( string $template_id ): bool {
        return isset( $this->templates[ $template_id ] );
    }

    /**
     * Check if user has access to a template.
     *
     * @param string $template_id The template identifier.
     * @return bool
     */
    public function user_has_access( string $template_id ): bool {
        $template = $this->get_template( $template_id );
        
        if ( ! $template ) {
            return false;
        }

        if ( empty( $template['requires_addon'] ) ) {
            return true;
        }

        $license = new BoostBot_License_Manager();
        return $license->has_addon( $template['requires_addon'] );
    }

    /**
     * Render a template with data.
     *
     * @param string $template_id The template identifier.
     * @param array  $data        The data to pass to the template.
     * @return string Rendered HTML.
     */
    public function render( string $template_id, array $data ): string {
        $template = $this->get_template( $template_id );

        if ( ! $template ) {
            return '<!-- Unknown template: ' . esc_html( $template_id ) . ' -->';
        }

        // Check access for add-on templates
        if ( ! $this->user_has_access( $template_id ) ) {
            $renderer = new BoostBot_Template_Renderer();
            return $renderer->render( 'upgrade-required', [
                'feature'     => $template['name'],
                'addon_name'  => $template['requires_addon'] ?? '',
                'addon_price' => 20, // Default add-on price
            ]);
        }

        // Validate data against schema
        $validated = $this->validate_data( $data, $template['schema'] );

        // Render using the renderer
        $renderer = new BoostBot_Template_Renderer();
        return $renderer->render( $template_id, $validated );
    }

    /**
     * Validate data against a template schema.
     *
     * @param array $data   The data to validate.
     * @param array $schema The template schema.
     * @return array Validated and sanitized data.
     */
    private function validate_data( array $data, array $schema ): array {
        $validated = [];

        foreach ( $schema as $field => $rules ) {
            $value = $data[ $field ] ?? null;

            // Skip missing optional fields
            if ( $value === null && empty( $rules['required'] ) ) {
                continue;
            }

            // Type-based sanitization
            if ( $value !== null ) {
                switch ( $rules['type'] ) {
                    case 'integer':
                        $validated[ $field ] = intval( $value );
                        break;
                    case 'number':
                        $validated[ $field ] = floatval( $value );
                        break;
                    case 'boolean':
                        $validated[ $field ] = (bool) $value;
                        break;
                    case 'array':
                        $validated[ $field ] = is_array( $value ) ? $value : [];
                        break;
                    case 'object':
                        $validated[ $field ] = is_array( $value ) ? $value : [];
                        break;
                    case 'email':
                        $validated[ $field ] = sanitize_email( $value );
                        break;
                    case 'url':
                        $validated[ $field ] = esc_url_raw( $value );
                        break;
                    case 'tel':
                        $validated[ $field ] = preg_replace( '/[^0-9+\-\s]/', '', $value );
                        break;
                    default:
                        $validated[ $field ] = sanitize_text_field( $value );
                }
            }
        }

        return $validated;
    }

    /**
     * Get AI instructions for using templates.
     *
     * This is added to the system prompt to teach the AI how to use templates.
     *
     * @return string Instructions in markdown format.
     */
    public function get_ai_instructions(): string {
        $license = new BoostBot_License_Manager();
        
        $instructions = "\n\n## 📦 Available Templates\n\n";
        $instructions .= "You can display rich, styled content using pre-built templates.\n";
        $instructions .= "To use a template, output the following format:\n\n";
        $instructions .= "```\n{template:TEMPLATE_ID|JSON_DATA}\n```\n\n";
        $instructions .= "**Important Rules:**\n";
        $instructions .= "- NEVER generate HTML or CSS yourself\n";
        $instructions .= "- Always use templates for structured content\n";
        $instructions .= "- JSON must be valid and properly escaped\n\n";
        $instructions .= "### Available Templates:\n\n";

        // Group by category
        $by_category = [];
        foreach ( $this->templates as $id => $template ) {
            // Skip templates user doesn't have access to
            if ( ! empty( $template['requires_addon'] ) && ! $license->has_addon( $template['requires_addon'] ) ) {
                continue;
            }

            $category = $template['category'] ?? 'other';
            if ( ! isset( $by_category[ $category ] ) ) {
                $by_category[ $category ] = [];
            }
            $by_category[ $category ][ $id ] = $template;
        }

        // Category names
        $category_names = [
            'basic'    => 'Basic',
            'products' => 'Products & Sales',
            'services' => 'Services & Pricing',
            'bundles'  => 'Bundle Builder',
            'buttons'  => 'Buttons & Actions',
            'utility'  => 'Utility',
        ];

        foreach ( $by_category as $category => $templates ) {
            $cat_name = $category_names[ $category ] ?? ucfirst( $category );
            $instructions .= "#### {$cat_name}\n";

            foreach ( $templates as $id => $template ) {
                $required_fields = [];
                foreach ( $template['schema'] as $field => $rules ) {
                    if ( ! empty( $rules['required'] ) ) {
                        $required_fields[] = $field;
                    }
                }

                $instructions .= "- `{$id}`: {$template['description']}\n";
                if ( ! empty( $required_fields ) ) {
                    $instructions .= "  - Required: " . implode( ', ', $required_fields ) . "\n";
                }
            }
            $instructions .= "\n";
        }

        // Add examples
        $instructions .= "### Examples:\n\n";
        $instructions .= "**Contact Card:**\n";
        $instructions .= "```\n{template:contact-card|{\"name\":\"John Smith\",\"role\":\"Sales Manager\",\"phone\":\"555-123-4567\",\"email\":\"john@example.com\"}}\n```\n\n";
        $instructions .= "**Product Card:**\n";
        $instructions .= "```\n{template:product-card|{\"id\":123,\"name\":\"Example Product\",\"price\":99.90,\"image\":\"https://...\"}}\n```\n\n";

        return $instructions;
    }

    /**
     * Get templates by category.
     *
     * @param string $category The category name.
     * @return array Templates in the category.
     */
    public function get_templates_by_category( string $category ): array {
        return array_filter( $this->templates, function( $template ) use ( $category ) {
            return ( $template['category'] ?? '' ) === $category;
        });
    }
}
