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

/**
 * VMO Template Handler v1.0.0
 * Handles template generation and GPT Image 1.5 image creation
 * Updated: DALL-E deprecated, using GPT Image 1 (state-of-the-art)
 */

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

class VMO_Template_Handler {
    
    private $templates_dir;
    private $image_api_url = 'https://api.openai.com/v1/images/generations';
    
    public function __construct() {
        $this->templates_dir = VMO_AI_BUILDER_DIR . 'templates/website-templates/';
        
        // AJAX handlers
        add_action('wp_ajax_vmo_generate_template', array($this, 'handle_generate_template'));
        add_action('wp_ajax_vmo_get_template_preview', array($this, 'handle_get_template_preview'));
    }
    
    /**
     * Handle template generation AJAX request
     */
    public function handle_generate_template() {
        check_ajax_referer('vmo_builder_nonce', 'security');
        
        if (!current_user_can('edit_posts')) {
            wp_send_json_error(['message' => 'Insufficient permissions']);
        }
        
        $template_id = sanitize_text_field(wp_unslash($_POST['template_id']));
        $category = sanitize_text_field(wp_unslash($_POST['category']));
        $token_cost = intval($_POST['token_cost']);
        
        $user_id = get_current_user_id();
        $current_balance = (int) get_user_meta($user_id, 'vmo_token_balance', true);
        
        // Check token balance
        if ($current_balance < $token_cost) {
            wp_send_json_error(['message' => 'Insufficient tokens']);
        }
        
        // Generate template
        $result = $this->generate_template($template_id, $category, $user_id);
        
        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }
        
        // Deduct tokens
        $new_balance = $current_balance - $token_cost;
        update_user_meta($user_id, 'vmo_token_balance', $new_balance);
        
        wp_send_json_success([
            'blocks' => $result['blocks'],
            'new_balance' => $new_balance,
            'message' => 'Template generated successfully'
        ]);
    }
    
    /**
     * Handle template preview AJAX request
     */
    public function handle_get_template_preview() {
        check_ajax_referer('vmo_builder_nonce', 'security');
        
        $template_id = sanitize_text_field($_POST['template_id'] ?? '');
        $category = sanitize_text_field($_POST['category'] ?? '');

        if (empty($template_id)) {
            wp_send_json_error(['message' => 'Template ID is required']);
        }

        // Sanitize: strip path traversal characters, allow only alphanumeric + hyphens + underscores
        $safe_id = preg_replace('/[^a-zA-Z0-9_-]/', '', $template_id);
        if ($safe_id !== $template_id) {
            wp_send_json_error(['message' => 'Invalid template ID']);
        }

        // Verify file exists on disk before returning URL
        $preview_path = VMO_AI_BUILDER_DIR . 'assets/templates/previews/' . $safe_id . '.html';
        if (file_exists($preview_path)) {
            wp_send_json_success([
                'preview_url' => VMO_AI_BUILDER_URL . 'assets/templates/previews/' . $safe_id . '.html',
                'category' => $category,
            ]);
        }

        // Fallback: try to generate a preview from template data
        $template_data = $this->get_template_data($safe_id, $category);
        if ($template_data) {
            wp_send_json_success([
                'preview_html' => $template_data['html'] ?? '',
                'template_name' => $template_data['name'] ?? $safe_id,
                'category' => $category,
            ]);
        }

        wp_send_json_error(['message' => 'Template preview not found']);
    }
    
    /**
     * Generate template content
     */
    private function generate_template($template_id, $category, $user_id) {
        $template_data = $this->get_template_data($template_id, $category);
        
        if (!$template_data) {
            return new WP_Error('template_not_found', 'Template not found');
        }
        
        // Generate content blocks based on template
        $blocks = [];
        
        foreach ($template_data['sections'] as $section) {
            $block_html = $this->generate_section_html($section, $template_data);
            
            if ($block_html) {
                $blocks[] = [
                    'type' => $section['type'],
                    'html' => $block_html,
                    'id' => 'block-' . uniqid()
                ];
            }
        }
        
        return ['blocks' => $blocks];
    }
    
    /**
     * Get template configuration data
     */
    private function get_template_data($template_id, $category) {
        $templates = [
            'modern-restaurant' => [
                'title' => 'Modern Restaurant',
                'color_scheme' => ['#1a1a1a', '#ff6b6b', '#ffffff', '#f8f9fa'],
                'fonts' => ['Playfair Display', 'Open Sans'],
                'sections' => [
                    [
                        'type' => 'hero',
                        'title' => 'Exceptional Dining Experience',
                        'subtitle' => 'Fresh ingredients, innovative cuisine, unforgettable moments',
                        'cta' => 'Reserve Your Table',
                        'background_type' => 'image',
                        'image_prompt' => 'modern restaurant interior with warm lighting, elegant dining setup, professional food photography style'
                    ],
                    [
                        'type' => 'about',
                        'title' => 'Our Story',
                        'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
                        'image_prompt' => 'professional chef preparing food in modern kitchen, warm lighting, culinary arts'
                    ],
                    [
                        'type' => 'menu',
                        'title' => 'Featured Menu',
                        'items' => [
                            ['name' => 'Signature Dish', 'price' => '$28', 'description' => 'Lorem ipsum dolor sit amet'],
                            ['name' => 'Chef Special', 'price' => '$32', 'description' => 'Consectetur adipiscing elit'],
                            ['name' => 'Seasonal Favorite', 'price' => '$24', 'description' => 'Sed do eiusmod tempor']
                        ]
                    ],
                    [
                        'type' => 'contact',
                        'title' => 'Visit Us',
                        'address' => '123 Culinary Street, Food District, FC 12345',
                        'phone' => '(555) 123-4567',
                        'hours' => 'Mon-Sun: 5:00 PM - 11:00 PM'
                    ]
                ]
            ],
            'coffee-shop' => [
                'title' => 'Coffee Shop',
                'color_scheme' => ['#8B4513', '#D2B48C', '#F5F5DC', '#2F1B14'],
                'fonts' => ['Merriweather', 'Lato'],
                'sections' => [
                    [
                        'type' => 'hero',
                        'title' => 'Perfectly Brewed Coffee',
                        'subtitle' => 'Artisan coffee, cozy atmosphere, community gathering place',
                        'cta' => 'Order Online',
                        'background_type' => 'image',
                        'image_prompt' => 'cozy coffee shop interior with wooden furniture, warm lighting, coffee beans and equipment'
                    ],
                    [
                        'type' => 'menu',
                        'title' => 'Coffee & Treats',
                        'items' => [
                            ['name' => 'Signature Latte', 'price' => '$4.50', 'description' => 'House blend with steamed milk'],
                            ['name' => 'Artisan Cappuccino', 'price' => '$3.75', 'description' => 'Rich espresso with foam art'],
                            ['name' => 'Fresh Pastry', 'price' => '$2.25', 'description' => 'Daily baked selection']
                        ]
                    ]
                ]
            ],
            'corporate-modern' => [
                'title' => 'Corporate Modern',
                'color_scheme' => ['#2c3e50', '#3498db', '#ffffff', '#ecf0f1'],
                'fonts' => ['Roboto', 'Open Sans'],
                'sections' => [
                    [
                        'type' => 'hero',
                        'title' => 'Leading Business Solutions',
                        'subtitle' => 'Professional services, innovative strategies, measurable results',
                        'cta' => 'Get Started',
                        'background_type' => 'image',
                        'image_prompt' => 'modern office building exterior, professional business environment, corporate architecture'
                    ],
                    [
                        'type' => 'services',
                        'title' => 'Our Services',
                        'items' => [
                            ['title' => 'Consulting', 'description' => 'Strategic business consultation'],
                            ['title' => 'Development', 'description' => 'Custom solution development'],
                            ['title' => 'Support', 'description' => '24/7 professional support']
                        ]
                    ]
                ]
            ],
            'design-agency' => [
                'title' => 'Design Agency',
                'color_scheme' => ['#000000', '#ff3366', '#ffffff', '#f0f0f0'],
                'fonts' => ['Montserrat', 'Source Sans Pro'],
                'sections' => [
                    [
                        'type' => 'hero',
                        'title' => 'Creative Design Studio',
                        'subtitle' => 'Bold ideas, stunning visuals, unforgettable brands',
                        'cta' => 'View Portfolio',
                        'background_type' => 'image',
                        'image_prompt' => 'modern creative studio workspace with design tools, computers, and artistic elements'
                    ],
                    [
                        'type' => 'portfolio',
                        'title' => 'Featured Work',
                        'items' => [
                            ['title' => 'Brand Identity', 'category' => 'Branding'],
                            ['title' => 'Web Design', 'category' => 'Digital'],
                            ['title' => 'Print Design', 'category' => 'Print']
                        ]
                    ]
                ]
            ]
        ];
        
        return isset($templates[$template_id]) ? $templates[$template_id] : null;
    }
    
    /**
     * Generate HTML for a template section
     */
    private function generate_section_html($section, $template_data) {
        $html = '';
        $colors = $template_data['color_scheme'];
        $fonts = $template_data['fonts'];
        
        switch ($section['type']) {
            case 'hero':
                $html = $this->generate_hero_section($section, $colors, $fonts);
                break;
            case 'about':
                $html = $this->generate_about_section($section, $colors, $fonts);
                break;
            case 'menu':
                $html = $this->generate_menu_section($section, $colors, $fonts);
                break;
            case 'services':
                $html = $this->generate_services_section($section, $colors, $fonts);
                break;
            case 'portfolio':
                $html = $this->generate_portfolio_section($section, $colors, $fonts);
                break;
            case 'contact':
                $html = $this->generate_contact_section($section, $colors, $fonts);
                break;
        }
        
        return $html;
    }
    
    /**
     * Generate hero section HTML
     */
    private function generate_hero_section($section, $colors, $fonts) {
        $background_image = $this->generate_dalle_image($section['image_prompt']);
        
        $html = '<section style="
            background: linear-gradient(rgba(0,0,0,0.4), rgba(0,0,0,0.4)), url(' . $background_image . ');
            background-size: cover;
            background-position: center;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
            color: white;
            font-family: ' . $fonts[0] . ', serif;
        ">
            <div style="max-width: 800px; padding: 0 20px;">
                <h1 style="
                    font-size: 3.5rem;
                    margin-bottom: 1rem;
                    font-weight: 700;
                    text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
                ">' . $section['title'] . '</h1>
                <p style="
                    font-size: 1.3rem;
                    margin-bottom: 2rem;
                    font-family: ' . $fonts[1] . ', sans-serif;
                    opacity: 0.9;
                ">' . $section['subtitle'] . '</p>
                <button style="
                    background: ' . $colors[1] . ';
                    color: white;
                    padding: 15px 30px;
                    border: none;
                    border-radius: 5px;
                    font-size: 1.1rem;
                    font-weight: 600;
                    cursor: pointer;
                    transition: transform 0.3s ease;
                " onmouseover="this.style.transform=\'scale(1.05)\'" onmouseout="this.style.transform=\'scale(1)\'">' . $section['cta'] . '</button>
            </div>
        </section>';
        
        return $html;
    }
    
    /**
     * Generate about section HTML
     */
    private function generate_about_section($section, $colors, $fonts) {
        $image = $this->generate_dalle_image($section['image_prompt']);
        
        $html = '<section style="
            padding: 80px 20px;
            background: ' . $colors[3] . ';
            font-family: ' . $fonts[1] . ', sans-serif;
        ">
            <div style="max-width: 1200px; margin: 0 auto; display: grid; grid-template-columns: 1fr 1fr; gap: 60px; align-items: center;">
                <div>
                    <h2 style="
                        font-size: 2.5rem;
                        color: ' . $colors[0] . ';
                        margin-bottom: 1.5rem;
                        font-family: ' . $fonts[0] . ', serif;
                    ">' . $section['title'] . '</h2>
                    <p style="
                        font-size: 1.1rem;
                        line-height: 1.6;
                        color: ' . $colors[0] . ';
                        margin-bottom: 1rem;
                    ">' . $section['content'] . '</p>
                    <p style="
                        font-size: 1.1rem;
                        line-height: 1.6;
                        color: ' . $colors[0] . ';
                    ">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p>
                </div>
                <div>
                    <img src="' . $image . '" alt="About Us" style="
                        width: 100%;
                        height: 400px;
                        object-fit: cover;
                        border-radius: 10px;
                        box-shadow: 0 10px 30px rgba(0,0,0,0.1);
                    " data-media-id="about-image-' . uniqid() . '" data-type="image" class="vmo-media-placeholder">
                </div>
            </div>
        </section>';
        
        return $html;
    }
    
    /**
     * Generate menu section HTML
     */
    private function generate_menu_section($section, $colors, $fonts) {
        $html = '<section style="
            padding: 80px 20px;
            background: ' . $colors[2] . ';
            font-family: ' . $fonts[1] . ', sans-serif;
        ">
            <div style="max-width: 1000px; margin: 0 auto; text-align: center;">
                <h2 style="
                    font-size: 2.5rem;
                    color: ' . $colors[0] . ';
                    margin-bottom: 3rem;
                    font-family: ' . $fonts[0] . ', serif;
                ">' . $section['title'] . '</h2>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 30px;">';
        
        foreach ($section['items'] as $item) {
            $html .= '<div style="
                background: ' . $colors[3] . ';
                padding: 30px;
                border-radius: 10px;
                text-align: left;
                box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                transition: transform 0.3s ease;
            " onmouseover="this.style.transform=\'translateY(-5px)\'" onmouseout="this.style.transform=\'translateY(0)\'">
                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 10px;">
                    <h3 style="
                        font-size: 1.3rem;
                        color: ' . $colors[0] . ';
                        margin: 0;
                        font-weight: 600;
                    ">' . $item['name'] . '</h3>
                    <span style="
                        font-size: 1.2rem;
                        color: ' . $colors[1] . ';
                        font-weight: 700;
                    ">' . $item['price'] . '</span>
                </div>
                <p style="
                    color: ' . $colors[0] . ';
                    margin: 0;
                    opacity: 0.8;
                    line-height: 1.5;
                ">' . $item['description'] . '</p>
            </div>';
        }
        
        $html .= '</div></div></section>';
        
        return $html;
    }
    
    /**
     * Generate services section HTML
     */
    private function generate_services_section($section, $colors, $fonts) {
        $html = '<section style="
            padding: 80px 20px;
            background: ' . $colors[2] . ';
            font-family: ' . $fonts[1] . ', sans-serif;
        ">
            <div style="max-width: 1200px; margin: 0 auto; text-align: center;">
                <h2 style="
                    font-size: 2.5rem;
                    color: ' . $colors[0] . ';
                    margin-bottom: 3rem;
                    font-family: ' . $fonts[0] . ', serif;
                ">' . $section['title'] . '</h2>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 40px;">';
        
        foreach ($section['items'] as $item) {
            $html .= '<div style="
                text-align: center;
                padding: 40px 20px;
            ">
                <div style="
                    width: 80px;
                    height: 80px;
                    background: ' . $colors[1] . ';
                    border-radius: 50%;
                    margin: 0 auto 20px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 2rem;
                ">💼</div>
                <h3 style="
                    font-size: 1.4rem;
                    color: ' . $colors[0] . ';
                    margin-bottom: 15px;
                    font-weight: 600;
                ">' . $item['title'] . '</h3>
                <p style="
                    color: ' . $colors[0] . ';
                    opacity: 0.8;
                    line-height: 1.6;
                ">' . $item['description'] . '</p>
            </div>';
        }
        
        $html .= '</div></div></section>';
        
        return $html;
    }
    
    /**
     * Generate portfolio section HTML
     */
    private function generate_portfolio_section($section, $colors, $fonts) {
        $html = '<section style="
            padding: 80px 20px;
            background: ' . $colors[0] . ';
            font-family: ' . $fonts[1] . ', sans-serif;
        ">
            <div style="max-width: 1200px; margin: 0 auto; text-align: center;">
                <h2 style="
                    font-size: 2.5rem;
                    color: ' . $colors[2] . ';
                    margin-bottom: 3rem;
                    font-family: ' . $fonts[0] . ', serif;
                ">' . $section['title'] . '</h2>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 30px;">';
        
        foreach ($section['items'] as $item) {
            $portfolio_image = $this->generate_dalle_image('professional design portfolio sample, modern ' . strtolower($item['category']) . ' design, clean and creative');
            
            $html .= '<div style="
                background: ' . $colors[2] . ';
                border-radius: 10px;
                overflow: hidden;
                transition: transform 0.3s ease;
            " onmouseover="this.style.transform=\'translateY(-10px)\'" onmouseout="this.style.transform=\'translateY(0)\'">
                <img src="' . $portfolio_image . '" alt="' . $item['title'] . '" style="
                    width: 100%;
                    height: 250px;
                    object-fit: cover;
                " data-media-id="portfolio-' . uniqid() . '" data-type="image" class="vmo-media-placeholder">
                <div style="padding: 25px;">
                    <h3 style="
                        font-size: 1.3rem;
                        color: ' . $colors[0] . ';
                        margin-bottom: 10px;
                        font-weight: 600;
                    ">' . $item['title'] . '</h3>
                    <span style="
                        color: ' . $colors[1] . ';
                        font-weight: 500;
                        text-transform: uppercase;
                        font-size: 0.9rem;
                        letter-spacing: 1px;
                    ">' . $item['category'] . '</span>
                </div>
            </div>';
        }
        
        $html .= '</div></div></section>';
        
        return $html;
    }
    
    /**
     * Generate contact section HTML
     */
    private function generate_contact_section($section, $colors, $fonts) {
        $html = '<section style="
            padding: 80px 20px;
            background: ' . $colors[0] . ';
            color: ' . $colors[2] . ';
            font-family: ' . $fonts[1] . ', sans-serif;
        ">
            <div style="max-width: 800px; margin: 0 auto; text-align: center;">
                <h2 style="
                    font-size: 2.5rem;
                    margin-bottom: 3rem;
                    font-family: ' . $fonts[0] . ', serif;
                ">' . $section['title'] . '</h2>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 40px; text-align: left;">
                    <div>
                        <h3 style="color: ' . $colors[1] . '; margin-bottom: 15px;">📍 Address</h3>
                        <p style="line-height: 1.6;">' . $section['address'] . '</p>
                    </div>
                    <div>
                        <h3 style="color: ' . $colors[1] . '; margin-bottom: 15px;">📞 Phone</h3>
                        <p style="line-height: 1.6;">' . $section['phone'] . '</p>
                    </div>
                    <div>
                        <h3 style="color: ' . $colors[1] . '; margin-bottom: 15px;">🕒 Hours</h3>
                        <p style="line-height: 1.6;">' . $section['hours'] . '</p>
                    </div>
                </div>
            </div>
        </section>';
        
        return $html;
    }
    
    /**
     * Generate image using GPT Image 1 (replaces deprecated DALL-E)
     * Supports transparent backgrounds for overlay effects
     * 
     * @param string $prompt The image generation prompt
     * @param array $options Optional settings (transparent, size, quality)
     * @return string Image URL or base64 data
     */
    private function generate_dalle_image($prompt, $options = array()) {
        return $this->generate_gpt_image($prompt, $options);
    }
    
    /**
     * Generate image using GPT Image 1
     * State-of-the-art image generation with transparent background support
     * 
     * @param string $prompt The image generation prompt
     * @param array $options Optional settings
     * @return string Image URL or base64 data
     */
    private function generate_gpt_image($prompt, $options = array()) {
        $api_key = get_option('vmo_openai_api_key');
        
        if (empty($api_key)) {
            return VMO_AI_BUILDER_URL . 'assets/placeholder-image.jpg';
        }
        
        // Default options
        $defaults = array(
            'transparent' => false,
            'size' => '1536x1024',      // Landscape default
            'quality' => 'high',         // high, medium, low
            'output_format' => 'png'     // png, webp, jpeg
        );
        $options = wp_parse_args($options, $defaults);
        
        // Build request body
        $body = array(
            'model' => 'gpt-image-1',
            'prompt' => $prompt . ', high quality, professional photography, clean composition',
            'n' => 1,
            'size' => $options['size'],
            'quality' => $options['quality'],
            'output_format' => $options['output_format']
        );
        
        // Add transparency if requested (requires png or webp)
        if ($options['transparent']) {
            $body['background'] = 'transparent';
            if ($options['output_format'] === 'jpeg') {
                $body['output_format'] = 'png';
            }
        }
        
        // ✅ TOKEN DEDUCTION v8.1.0: Charge for GPT Image generation
        $user_id = get_current_user_id();
        if (function_exists('vmo_deduct_tokens')) {
            if (!vmo_deduct_tokens($user_id, 960, 'gpt_image', 'Template image generation')) {
                return VMO_AI_BUILDER_URL . 'assets/placeholder-image.jpg';
            }
        }
        
        $args = array(
            'method' => 'POST',
            'timeout' => 120, // GPT Image can take longer
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json'
            ),
            'body' => json_encode($body)
        );
        
        $response = wp_remote_post($this->image_api_url, $args);
        
        if (is_wp_error($response)) {
            error_log('VMO GPT Image Error: ' . $response->get_error_message());
            return VMO_AI_BUILDER_URL . 'assets/placeholder-image.jpg';
        }
        
        $response_body = wp_remote_retrieve_body($response);
        $data = json_decode($response_body, true);
        
        // GPT Image 1.5 returns base64 encoded images
        if (isset($data['data'][0]['b64_json'])) {
            // Save to media library and return URL
            return $this->save_base64_image($data['data'][0]['b64_json'], $options['output_format']);
        }
        
        // Fallback for URL response
        if (isset($data['data'][0]['url'])) {
            return $data['data'][0]['url'];
        }
        
        error_log('VMO GPT Image Error: ' . $response_body);
        return VMO_AI_BUILDER_URL . 'assets/placeholder-image.jpg';
    }
    
    /**
     * Generate transparent overlay image (particles, clouds, smoke, etc.)
     * 
     * @param string $type Overlay type (clouds, particles, smoke, ripples)
     * @param string $style Visual style
     * @return string Image URL with transparent background
     */
    public function generate_overlay_image($type, $style = 'realistic') {
        $prompts = array(
            'clouds' => 'Wispy realistic clouds with soft edges, isolated on transparent background, fluffy cumulus clouds, photorealistic, seamless edges, ' . $style,
            'particles' => 'Floating glowing particles, magical dust specks, light orbs scattered randomly, isolated on transparent background, ' . $style,
            'smoke' => 'Wisps of translucent smoke curling gracefully, ethereal mist, isolated on transparent background, ' . $style,
            'sparkles' => 'Glittering sparkles and light flares, magical shimmer effect, isolated on transparent background, ' . $style,
            'fog' => 'Soft atmospheric fog layer, misty ground effect, isolated on transparent background, ' . $style,
            'bubbles' => 'Translucent soap bubbles floating, iridescent spheres, isolated on transparent background, ' . $style,
            'leaves' => 'Falling autumn leaves scattered, natural foliage, isolated on transparent background, ' . $style,
            'snow' => 'Falling snowflakes, winter snow particles, isolated on transparent background, ' . $style,
            'rain' => 'Rain drops and streaks, realistic rainfall, isolated on transparent background, ' . $style,
            'dust' => 'Floating dust particles in light beam, atmospheric dust motes, isolated on transparent background, ' . $style
        );
        
        $prompt = isset($prompts[$type]) ? $prompts[$type] : $prompts['particles'];
        
        return $this->generate_gpt_image($prompt, array(
            'transparent' => true,
            'size' => '1024x1024',
            'quality' => 'high',
            'output_format' => 'png'
        ));
    }
    
    /**
     * Save base64 image to WordPress media library
     * 
     * @param string $base64_data Base64 encoded image data
     * @param string $format Image format (png, webp, jpeg)
     * @return string URL of saved image
     */
    private function save_base64_image($base64_data, $format = 'png') {
        $upload_dir = wp_upload_dir();
        $filename = 'vmo-generated-' . uniqid() . '.' . $format;
        $file_path = $upload_dir['path'] . '/' . $filename;
        
        // Decode and save
        $image_data = base64_decode($base64_data); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- data decoding
        vmo_get_filesystem()->put_contents($file_path, $image_data, FS_CHMOD_FILE);
        
        // Get mime type
        $mime_types = array(
            'png' => 'image/png',
            'webp' => 'image/webp',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg'
        );
        $mime_type = isset($mime_types[$format]) ? $mime_types[$format] : 'image/png';
        
        // Add to media library
        $attachment = array(
            'post_mime_type' => $mime_type,
            'post_title' => sanitize_file_name($filename),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        $attach_id = wp_insert_attachment($attachment, $file_path);
        
        if (!is_wp_error($attach_id)) {
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
            wp_update_attachment_metadata($attach_id, $attach_data);
            
            return wp_get_attachment_url($attach_id);
        }
        
        // Fallback to direct URL
        return $upload_dir['url'] . '/' . $filename;
    }
}


// Initialize template handler
new VMO_Template_Handler();
