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

class VMO_Generator_Engine {
    
    private $openai_service;

    public function __construct() {
        // Hook into the generation process
        add_action('vmo_generate_website_structure', [$this, 'determine_engine_strategy'], 10, 2);
        
        // Initialize Service
        // Assuming the service class is loaded. In a real DI container, this would be injected.
        if (class_exists('VMO_OpenAI_Service')) {
            $this->openai_service = new VMO_OpenAI_Service();
        }
    }

    /**
     * Decides whether to use the Standard (Component) Engine or Creative (Viewport) Engine.
     * 
     * @param int $user_id
     * @param array $research_data Data from the Deep Research phase (competitors, industry trends).
     */
    public function determine_engine_strategy($user_id, $research_data) {
        $industry = $research_data['industry'] ?? 'generic';
        $competitor_styles = $research_data['competitor_styles'] ?? []; // e.g., ['corporate', 'minimal', 'creative']
        
        // Logic to score "Creativity" vs "Professionalism"
        $creative_score = 0;
        foreach ($competitor_styles as $style) {
            if (in_array($style, ['creative', 'artistic', 'innovative', 'retro', 'interactive'])) {
                $creative_score++;
            }
        }

        // Threshold: If > 50% of competitors are creative, or user explicitly asked for it
        $user_preference = get_user_meta($user_id, 'vmo_design_preference', true);
        
        if ($user_preference === 'creative' || $creative_score > count($competitor_styles) / 2) {
            $this->run_creative_engine($user_id, $research_data);
        } else {
            $this->run_standard_engine($user_id, $research_data);
        }
    }

    /**
     * Engine A: Standard / Corporate
     * Uses Component-based assembly (LEGO approach).
     */
    private function run_standard_engine($user_id, $data) {
        error_log("VMO Generator: Selected Standard Engine for User $user_id");

        do_action('vmo_generator_standard_start', $user_id, $data);

        $business_name = isset($data['business_name']) && $data['business_name'] ? (string)$data['business_name'] : 'Your Business';
        $industry = isset($data['industry']) && $data['industry'] ? (string)$data['industry'] : 'Business';
        $services = isset($data['services']) && is_array($data['services']) ? $data['services'] : array();
        $contact = isset($data['contact_info']) && is_array($data['contact_info']) ? $data['contact_info'] : array();

        $services_list = '';
        foreach ($services as $svc) {
            $svc = is_string($svc) ? trim($svc) : '';
            if ($svc === '') continue;
            $services_list .= '<li class="py-2 border-b border-gray-200 last:border-0">' . esc_html($svc) . '</li>';
        }
        if ($services_list === '') {
            $services_list = '<li class="py-2 border-b border-gray-200 last:border-0">' . esc_html__('Professional services tailored to your needs.', 'vmo') . '</li>';
        }

        $email = isset($contact['email']) ? (string)$contact['email'] : '';
        $phone = isset($contact['phone']) ? (string)$contact['phone'] : '';
        $location = isset($data['location']) ? (string)$data['location'] : '';

        $contact_bits = array();
        if ($email) $contact_bits[] = '<div><strong>' . esc_html__('Email:', 'vmo') . '</strong> ' . esc_html($email) . '</div>';
        if ($phone) $contact_bits[] = '<div><strong>' . esc_html__('Phone:', 'vmo') . '</strong> ' . esc_html($phone) . '</div>';
        if ($location) $contact_bits[] = '<div><strong>' . esc_html__('Location:', 'vmo') . '</strong> ' . esc_html($location) . '</div>';
        $contact_html = $contact_bits ? implode("\n", $contact_bits) : '<div>' . esc_html__('Contact us to learn more.', 'vmo') . '</div>';

        $generated_inner = '';
        if ($this->openai_service) {
            $prompt = "Generate a single-file, modern, responsive HTML page (include full <html> document) for a {$industry} business named '{$business_name}'. " .
                "Include sections: Hero, Services, About, Contact. Use simple CSS (no external CDNs). Keep it professional.";
            $generated_inner = (string)$this->openai_service->generate_text($prompt);
        }

        $html = $generated_inner && stripos($generated_inner, '<html') !== false
            ? $generated_inner
            : $this->assemble_standard_html($business_name, $industry, $services_list, $contact_html);

        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . '/vmo_sites/user_' . $user_id . '_standard.html';
        if (!file_exists(dirname($file_path))) {
            wp_mkdir_p(dirname($file_path));
        }
        vmo_get_filesystem()->put_contents($file_path, $html, FS_CHMOD_FILE);

        $url = $upload_dir['baseurl'] . '/vmo_sites/user_' . $user_id . '_standard.html';
        update_user_meta($user_id, 'vmo_generated_site_url', $url);

        do_action('vmo_generator_standard_complete', $user_id, $file_path, $url, $data);
    }

    private function assemble_standard_html($business_name, $industry, $services_list, $contact_html) {
        $title = esc_html($business_name);
        $industry_esc = esc_html($industry);
        $ajax_url = admin_url('admin-ajax.php');
        
        // Form HTML directly embedded to work in static/preview mode
        $support_form = <<<HTML
        <div class="support-box">
            <h3>Support Request</h3>
            <p style="font-size:12px; margin-bottom:10px;">Send a request directly to our team.</p>
            <form id="vmo-ticket-form-gen">
                <input type="hidden" name="action" value="vmo_submit_ticket">
                <input type="hidden" name="security_check" value="public"> 
                <div style="display:flex; gap:10px; margin-bottom:10px;">
                    <input type="text" name="data[guest_name]" placeholder="Your Name" required style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                    <input type="email" name="data[guest_email]" placeholder="Your Email" required style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                </div>
                <select name="data[department]" style="width:100%; padding:8px; margin-bottom:10px; border:1px solid #ddd; border-radius:4px;">
                    <option value="general">General Inquiry</option>
                    <option value="technical">Technical Support</option>
                    <option value="billing">Billing Question</option>
                    <option value="sales">Sales & Services</option>
                </select>
                <input type="text" name="data[subject]" placeholder="Subject" required style="width:100%; padding:8px; margin-bottom:10px; border:1px solid #ddd; border-radius:4px;">
                <textarea name="data[message]" rows="3" placeholder="How can we help?" required style="width:100%; padding:8px; margin-bottom:10px; border:1px solid #ddd; border-radius:4px; font-family:inherit;"></textarea>
                <button type="submit" id="vmo-gen-btn" style="width:100%; padding:10px; background:var(--fg); color:#fff; border:none; border-radius:4px; cursor:pointer;">Send Message</button>
                <div id="vmo-gen-msg" style="margin-top:10px; font-size:13px;"></div>
            </form>
        </div>
HTML;

        return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$title}</title>
    <style>
        :root { --fg:#0f172a; --muted:#475569; --bg:#ffffff; --card:#f8fafc; --border:#e2e8f0; }
        body { margin:0; font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji"; color:var(--fg); background:var(--bg); }
        .wrap { max-width: 980px; margin: 0 auto; padding: 40px 20px; }
        .hero { padding: 48px 24px; background: var(--card); border:1px solid var(--border); border-radius: 16px; }
        h1 { margin:0 0 10px 0; font-size: 40px; line-height: 1.1; }
        p { margin: 0; color: var(--muted); line-height: 1.6; }
        .grid { display:grid; grid-template-columns: 1fr; gap: 18px; margin-top: 24px; }
        @media (min-width: 900px){ .grid { grid-template-columns: 1.2fr 0.8fr; } }
        .card { border:1px solid var(--border); border-radius: 14px; padding: 18px; background:#fff; }
        .card h2 { margin:0 0 10px 0; font-size: 18px; }
        ul { margin:0; padding-left: 18px; color: var(--fg); }
        .footer { margin-top: 32px; padding-top: 18px; border-top: 1px solid var(--border); color: var(--muted); font-size: 14px; }
        a.btn { display:inline-block; margin-top: 16px; padding: 10px 14px; border-radius: 10px; background: var(--fg); color:#fff; text-decoration:none; }
        .support-box { background: #f0fdf4; border: 1px solid #bbf7d0; padding: 15px; border-radius: 8px; margin-top: 15px; }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        var vmo_ajax_url = "{$ajax_url}";
        $(document).ready(function() {
            $('#vmo-ticket-form-gen').on('submit', function(e) {
                e.preventDefault();
                var btn = $('#vmo-gen-btn');
                btn.prop('disabled', true).text('Sending...');
                
                // Construct payload manually to match expected format
                var formData = $(this).serialize(); // Serialize form data
                
                $.post(vmo_ajax_url, formData, function(res) {
                    if(res.success) {
                        $('#vmo-gen-msg').html('<span style="color:green">✔ ' + res.data.message + '</span>');
                        $('#vmo-ticket-form-gen')[0].reset();
                        btn.prop('disabled', false).text('Sent!');
                        setTimeout(function(){ btn.text('Send Message'); }, 3000);
                    } else {
                         $('#vmo-gen-msg').html('<span style="color:red">✘ ' + (res.data.message || 'Error occurred') + '</span>');
                         btn.prop('disabled', false).text('Try Again');
                    }
                }).fail(function() {
                     $('#vmo-gen-msg').html('<span style="color:red">✘ Connection Failed</span>');
                     btn.prop('disabled', false).text('Try Again');
                });
            });
        });
    </script>
</head>
<body>
    <div class="wrap">
        <div class="hero">
            <h1>{$title}</h1>
            <p>Professional {$industry_esc} solutions built to help you grow.</p>
            <a class="btn" href="#contact">Get in touch</a>
        </div>

        <div class="grid">
            <div class="card">
                <h2>Services</h2>
                <ul>{$services_list}</ul>
            </div>
            <div class="card">
                <h2>About</h2>
                <p>{$title} delivers reliable, high-quality work with a focus on clarity, trust, and measurable results.</p>
            </div>
            <div class="card" id="contact" style="grid-column: 1 / -1;">
                <h2>Contact & Support</h2>
                <p>{$contact_html}</p>
                {$support_form}
            </div>
        </div>

        <div class="footer">Generated by VMO.</div>
    </div>
</body>
</html>
HTML;
    }

    /**
     * Engine B: Creative / Unique
     * Uses Viewport-based assembly (Green Screen approach).
     */
    private function run_creative_engine($user_id, $data) {
        error_log("VMO Generator: Selected Creative Engine for User $user_id");

        if (!$this->openai_service) {
            error_log("VMO Generator Error: OpenAI Service not available.");
            return;
        }

        // 1. Generate "Shell" Image via GPT Image 1
        $industry = $data['industry'] ?? 'Technology';
        $vibe = $data['vibe'] ?? 'Futuristic';
        
        $prompt = "A photorealistic, high-resolution front-facing view of a {$vibe} {$industry} interface device on a desk or surface. " .
                  "The main screen area of the device must be a solid, pure green color (#00FF00) to serve as a chroma key. " .
                  "The device should look premium and detailed. Cinematic lighting.";
        
        $image_url = $this->openai_service->generate_image($prompt);
        
        if (!$image_url) {
            error_log("VMO Generator Error: Failed to generate Creative Shell image.");
            // Fallback to standard engine?
            $this->run_standard_engine($user_id, $data);
            return;
        }

        // 2. Analyze Image for "Green Screen" coordinates (Viewport)
        $viewport = $this->detect_green_screen($image_url);
        
        // 3. Generate Content to fit inside Viewport
        $content_html = $this->generate_viewport_content($data);

        // 4. Save/Render "Wrapper" HTML
        $final_html = $this->assemble_creative_html($image_url, $viewport, $content_html);
        
        // Save to a file or post meta (Simulated here)
        $upload_dir = wp_upload_dir();
        $file_path = $upload_dir['basedir'] . '/vmo_sites/user_' . $user_id . '_creative.html';
        
        if (!file_exists(dirname($file_path))) {
            wp_mkdir_p(dirname($file_path));
        }
        
        vmo_get_filesystem()->put_contents($file_path, $final_html, FS_CHMOD_FILE);
        update_user_meta($user_id, 'vmo_generated_site_url', $upload_dir['baseurl'] . '/vmo_sites/user_' . $user_id . '_creative.html');
        
        do_action('vmo_generator_creative_complete', $user_id, $file_path);
    }

    /**
     * Detects the green screen area in the image.
     * Returns CSS percentage values.
     */
    private function detect_green_screen($image_url) {
        // Default fallback if analysis fails
        $default_viewport = [
            'top' => '20%',
            'left' => '20%',
            'width' => '60%',
            'height' => '60%'
        ];

        if (!function_exists('imagecreatefrompng') && !function_exists('imagecreatefromjpeg')) {
            return $default_viewport;
        }

        // Download image to temp
        $temp_file = tempnam(sys_get_temp_dir(), 'vmo_img');
        $image_response = wp_remote_get($image_url);
        $image_data = is_wp_error($image_response) ? false : wp_remote_retrieve_body($image_response);
        if (!$image_data) return $default_viewport;
        
        vmo_get_filesystem()->put_contents($temp_file, $image_data, FS_CHMOD_FILE);

        // Load image
        $info = getimagesize($temp_file);
        $mime = $info['mime'];
        
        if ($mime == 'image/jpeg') 
            $im = imagecreatefromjpeg($temp_file);
        elseif ($mime == 'image/png')
            $im = imagecreatefrompng($temp_file);
        else {
            unlink($temp_file);
            return $default_viewport;
        }

        if (!$im) {
            unlink($temp_file);
            return $default_viewport;
        }

        $width = imagesx($im);
        $height = imagesy($im);
        
        $min_x = $width; $min_y = $height;
        $max_x = 0; $max_y = 0;
        $found = false;

        // Scan pixels (Sampling every 10th pixel for performance)
        for ($y = 0; $y < $height; $y += 10) {
            for ($x = 0; $x < $width; $x += 10) {
                $rgb = imagecolorat($im, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // Check for Green (High G, Low R/B)
                // #00FF00 is 0, 255, 0. Allow some tolerance.
                if ($g > 200 && $r < 50 && $b < 50) {
                    if ($x < $min_x) $min_x = $x;
                    if ($x > $max_x) $max_x = $x;
                    if ($y < $min_y) $min_y = $y;
                    if ($y > $max_y) $max_y = $y;
                    $found = true;
                }
            }
        }

        imagedestroy($im);
        unlink($temp_file);

        if (!$found) return $default_viewport;

        // Convert to percentages
        return [
            'top' => round(($min_y / $height) * 100, 2) . '%',
            'left' => round(($min_x / $width) * 100, 2) . '%',
            'width' => round(($max_x - $min_x) / $width * 100, 2) . '%',
            'height' => round(($max_y - $min_y) / $height * 100, 2) . '%'
        ];
    }

    private function generate_viewport_content($data) {
        $industry = $data['industry'] ?? 'Business';
        $prompt = "Generate a single-file HTML/TailwindCSS body content for a {$industry} website. " .
                  "It should be modern, responsive, and fit within a container. " .
                  "Include a Hero section, a Services list, and a Contact button. " .
                  "Do not include <html> or <body> tags, just the inner content.";
        
        return $this->openai_service->generate_text($prompt);
    }

    private function assemble_creative_html($bg_image, $viewport, $content) {
        return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Creative Site</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; background: #000; }
        .creative-wrapper {
            position: relative;
            width: 100vw;
            height: 100vh;
            background-image: url('{$bg_image}');
            background-size: cover;
            background-position: center;
        }
        .viewport-container {
            position: absolute;
            top: {$viewport['top']};
            left: {$viewport['left']};
            width: {$viewport['width']};
            height: {$viewport['height']};
            overflow-y: auto;
            background: white; /* Fallback */
            box-shadow: inset 0 0 20px rgba(0,0,0,0.5);
        }
        /* Hide scrollbar for cleaner look */
        .viewport-container::-webkit-scrollbar { width: 0px; background: transparent; }
    </style>
</head>
<body>
    <div class="creative-wrapper">
        <div class="viewport-container">
            {$content}
        </div>
    </div>
</body>
</html>
HTML;
    }
}
