<?php
/**
 * VMO Legal Document Generator
 *
 * Generates Privacy Policy, Terms of Service, Cookie Policy, and other legal
 * documents tailored to each user's business using AI.
 *
 * @package VMO_AI_Builder
 * @since   1.0.0
 */

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

class VMO_Legal {

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

    /** @var string[] Supported document types */
    private const DOCUMENT_TYPES = [
        'privacy_policy',
        'terms_of_service',
        'cookie_policy',
        'refund_policy',
        'shipping_policy',
        'sms_policy',
        'email_policy',
        'disclaimer',
        'acceptable_use',
    ];

    /** @var int Approximate token cost per legal document generation */
    private const TOKEN_COST_PER_DOC = 800;

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

    /**
     * Constructor — registers AJAX hooks.
     */
    private function __construct() {
        add_action('wp_ajax_vmo_generate_legal_doc',   [$this, 'ajax_generate_legal_doc']);
        add_action('wp_ajax_vmo_get_legal_docs',       [$this, 'ajax_get_legal_docs']);
        add_action('wp_ajax_vmo_save_legal_doc',       [$this, 'ajax_save_legal_doc']);
        add_action('wp_ajax_vmo_delete_legal_doc',     [$this, 'ajax_delete_legal_doc']);
        add_action('wp_ajax_vmo_publish_legal_doc',    [$this, 'ajax_publish_legal_doc']);
    }

    private function prepare_long_running_runtime(): void {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }
        if (function_exists('ignore_user_abort')) {
            @ignore_user_abort(true);
        }
        if (function_exists('ini_set')) {
            @ini_set('memory_limit', '512M');
        }
    }

    /**
     * Ensure the legal documents table exists.
     */
    private function ensure_table(): string {
        global $wpdb;
        $table = $wpdb->prefix . 'vmo_legal_documents';

        if ($wpdb->get_var("SHOW TABLES LIKE '{$table}'") !== $table) {
            $charset = $wpdb->get_charset_collate();
            $wpdb->query("CREATE TABLE {$table} (
                id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                user_id BIGINT UNSIGNED NOT NULL,
                doc_type VARCHAR(50) NOT NULL,
                title VARCHAR(255) NOT NULL,
                content LONGTEXT NOT NULL,
                business_name VARCHAR(255) DEFAULT '',
                business_url VARCHAR(500) DEFAULT '',
                jurisdiction VARCHAR(100) DEFAULT '',
                version INT UNSIGNED DEFAULT 1,
                status ENUM('draft','published') DEFAULT 'draft',
                published_page_id BIGINT UNSIGNED DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                KEY idx_user_type (user_id, doc_type),
                KEY idx_status (status)
            ) {$charset};");
        }

        return $table;
    }

    /**
     * Programmatic generation used by Phase 8 launch orchestration.
     */
    public function generate_required_documents($user_id, array $context = [], array $doc_types = []): array {
        $this->prepare_long_running_runtime();

        global $wpdb;

        $user_id = (int) $user_id;
        if ($user_id <= 0) {
            return array('generated' => 0, 'documents' => array(), 'errors' => array('Invalid user.'));
        }

        if (empty($doc_types)) {
            $doc_types = array('privacy_policy', 'terms_of_service', 'sms_policy', 'email_policy', 'refund_policy');
            $shipping_context = strtolower((string) ($context['shipping_requirements'] ?? ''));
            if (!empty($context['products_inventory']) || strpos($shipping_context, 'ship') !== false || strpos($shipping_context, 'delivery') !== false) {
                $doc_types[] = 'shipping_policy';
            }
        }

        $business_name = sanitize_text_field((string) ($context['business_name'] ?? get_user_meta($user_id, 'vmo_business_name', true) ?: get_bloginfo('name')));
        $business_type = sanitize_text_field((string) ($context['business_type'] ?? get_user_meta($user_id, 'vmo_industry', true) ?: 'online business'));
        $jurisdiction = sanitize_text_field((string) ($context['jurisdiction'] ?? $context['location'] ?? 'United States'));
        $business_url = esc_url_raw((string) ($context['business_url'] ?? site_url()));
        $table = $this->ensure_table();
        $titles = $this->get_document_titles();
        $generated = array();
        $errors = array();

        foreach (array_values(array_unique(array_map('sanitize_key', $doc_types))) as $doc_type) {
            if (!in_array($doc_type, self::DOCUMENT_TYPES, true)) {
                $errors[] = 'Unsupported legal document type: ' . $doc_type;
                continue;
            }

            $title = ($titles[$doc_type] ?? ucwords(str_replace('_', ' ', $doc_type))) . ' - ' . $business_name;
            $content = $this->generate_launch_legal_content($doc_type, array(
                'business_name' => $business_name,
                'business_url' => $business_url,
                'jurisdiction' => $jurisdiction,
                'business_type' => $business_type,
                'extra_context' => wp_json_encode($context),
            ));

            $existing = $wpdb->get_var($wpdb->prepare(
                "SELECT id FROM {$table} WHERE user_id = %d AND doc_type = %s LIMIT 1",
                $user_id,
                $doc_type
            ));

            $data = array(
                'user_id' => $user_id,
                'doc_type' => $doc_type,
                'title' => $title,
                'content' => $content,
                'business_name' => $business_name,
                'business_url' => $business_url,
                'jurisdiction' => $jurisdiction,
                'status' => 'draft',
            );

            if ($existing) {
                $data['version'] = (int) $wpdb->get_var($wpdb->prepare("SELECT version FROM {$table} WHERE id = %d", $existing)) + 1;
                $wpdb->update($table, $data, array('id' => $existing));
                $doc_id = (int) $existing;
            } else {
                $data['version'] = 1;
                $wpdb->insert($table, $data);
                $doc_id = (int) $wpdb->insert_id;
            }

            if ($doc_id > 0) {
                $generated[] = array('doc_id' => $doc_id, 'doc_type' => $doc_type, 'title' => $title);
            } else {
                $errors[] = 'Failed to store ' . $doc_type;
            }
        }

        return array('generated' => count($generated), 'documents' => $generated, 'errors' => $errors);
    }

    private function get_document_titles(): array {
        return array(
            'privacy_policy' => 'Privacy Policy',
            'terms_of_service' => 'Terms of Service',
            'cookie_policy' => 'Cookie Policy',
            'refund_policy' => 'Refund Policy',
            'shipping_policy' => 'Shipping Policy',
            'sms_policy' => 'SMS Policy',
            'email_policy' => 'Email Policy',
            'disclaimer' => 'Disclaimer',
            'acceptable_use' => 'Acceptable Use Policy',
        );
    }

    private function generate_launch_legal_content(string $doc_type, array $context): string {
        $titles = $this->get_document_titles();
        $label = $titles[$doc_type] ?? ucwords(str_replace('_', ' ', $doc_type));
        $business_name = esc_html($context['business_name']);
        $jurisdiction = esc_html($context['jurisdiction']);
        $business_type = esc_html($context['business_type']);
        $business_url = esc_url($context['business_url']);

        $sections = array(
            'privacy_policy' => array('Information We Collect', 'How We Use Information', 'Data Sharing', 'Cookies and Tracking', 'Your Privacy Rights', 'Data Retention', 'Contact'),
            'terms_of_service' => array('Use of Services', 'Accounts and Responsibilities', 'Purchases and Payments', 'Intellectual Property', 'Limitations of Liability', 'Dispute Resolution', 'Termination'),
            'refund_policy' => array('Refund Eligibility', 'Cancellation Process', 'Processing Timeline', 'Non-Refundable Items', 'Contact'),
            'shipping_policy' => array('Processing Times', 'Shipping Methods', 'Delivery Estimates', 'Lost or Delayed Packages', 'Returns and Exchanges', 'Contact'),
            'sms_policy' => array('Program Description', 'Consent to Receive Messages', 'Opt-Out Instructions', 'Message Frequency', 'Fees and Carrier Disclosure', 'Support'),
            'email_policy' => array('Email Communications', 'Transactional Messages', 'Marketing Consent', 'Unsubscribe Instructions', 'Data Use', 'Support'),
            'cookie_policy' => array('Types of Cookies', 'Why We Use Cookies', 'Third-Party Cookies', 'Managing Cookies', 'Contact'),
            'disclaimer' => array('General Information', 'No Professional Advice', 'External Links', 'AI-Assisted Content', 'Contact'),
            'acceptable_use' => array('Permitted Use', 'Prohibited Conduct', 'Content Standards', 'Enforcement', 'Reporting'),
        );

        $html = '<h1>' . esc_html($label) . '</h1>';
        $html .= '<p><strong>Last Updated:</strong> ' . esc_html(date_i18n(get_option('date_format'))) . '</p>';
        $html .= '<p>This draft ' . esc_html(strtolower($label)) . ' applies to ' . $business_name . ', a ' . $business_type . ' operating in ' . $jurisdiction . '. Website: <a href="' . $business_url . '">' . $business_url . '</a>.</p>';

        foreach ($sections[$doc_type] ?? array('Overview', 'Responsibilities', 'Contact') as $section) {
            $html .= '<h2>' . esc_html($section) . '</h2>';
            $html .= '<p>' . $business_name . ' will maintain this section in plain language for customers and visitors. The final published version should be reviewed against current laws, platform rules, and the company\'s actual operations before launch.</p>';
        }

        $html .= '<h2>Contact</h2><p>Questions about this policy may be sent through the official contact channels listed on the website.</p>';

        return $html;
    }

    /**
     * AJAX: Generate a legal document via AI.
     */
    public function ajax_generate_legal_doc(): void {
        $this->prepare_long_running_runtime();

        if (!current_user_can('read')) {
            wp_send_json_error(['message' => 'Forbidden'], 403);
        }
        if (function_exists('vmo_verify_admin_security') && !vmo_verify_admin_security()) {
            wp_send_json_error(['message' => 'Security check failed'], 403);
        }

        $user_id  = get_current_user_id();
        $doc_type = isset($_POST['doc_type']) ? sanitize_key($_POST['doc_type']) : '';

        if (!in_array($doc_type, self::DOCUMENT_TYPES, true)) {
            wp_send_json_error(['message' => 'Invalid document type. Supported: ' . implode(', ', self::DOCUMENT_TYPES)], 400);
        }

        // Gather business context
        $business_name  = isset($_POST['business_name']) ? sanitize_text_field($_POST['business_name']) : '';
        $business_url   = isset($_POST['business_url'])  ? esc_url_raw($_POST['business_url']) : site_url();
        $jurisdiction   = isset($_POST['jurisdiction'])   ? sanitize_text_field($_POST['jurisdiction']) : 'United States';
        $business_type  = isset($_POST['business_type'])  ? sanitize_text_field($_POST['business_type']) : '';
        $extra_context  = isset($_POST['extra_context'])  ? sanitize_textarea_field($_POST['extra_context']) : '';

        // Fallback business name from user meta or site title
        if (empty($business_name)) {
            $business_name = get_user_meta($user_id, 'vmo_business_name', true) ?: get_bloginfo('name');
        }
        if (empty($business_type)) {
            $business_type = get_user_meta($user_id, 'vmo_industry', true) ?: 'online business';
        }

        // Check token balance
        $tokens = (int) get_user_meta($user_id, 'vmo_token_balance', true);
        if ($tokens < self::TOKEN_COST_PER_DOC) {
            wp_send_json_error([
                'message'        => 'Insufficient tokens. Legal document generation costs ~' . self::TOKEN_COST_PER_DOC . ' tokens.',
                'tokens_needed'  => self::TOKEN_COST_PER_DOC,
                'tokens_current' => $tokens,
            ], 402);
        }

        // Build AI prompt
        $prompt = $this->build_legal_prompt($doc_type, [
            'business_name' => $business_name,
            'business_url'  => $business_url,
            'jurisdiction'  => $jurisdiction,
            'business_type' => $business_type,
            'extra_context' => $extra_context,
        ]);

        // Call OpenAI
        $api_key = get_option('vmo_openai_api_key', '');
        if (empty($api_key)) {
            wp_send_json_error(['message' => 'AI API key not configured'], 500);
        }

        $model = function_exists('vmo_get_model') ? vmo_get_model('mini') : (defined('VMO_PRIMARY_MODEL') ? VMO_PRIMARY_MODEL : 'gpt-5.5-mini');

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'timeout' => 120,
            'headers' => [
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $api_key,
            ],
            'body' => wp_json_encode([
                'model'       => $model,
                'messages'    => [
                    ['role' => 'system', 'content' => 'You are a legal document specialist. Generate professional, comprehensive legal documents formatted in clean HTML. Include proper section headings, numbered clauses, and standard legal language. The document must be jurisdiction-appropriate and cover all standard provisions.'],
                    ['role' => 'user', 'content' => $prompt],
                ],
                'max_completion_tokens' => 4000,
                'temperature' => 0.3,
            ]),
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => 'API error: ' . $response->get_error_message()], 500);
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (empty($body['choices'][0]['message']['content'])) {
            wp_send_json_error(['message' => 'Empty response from AI'], 500);
        }

        $content = $body['choices'][0]['message']['content'];

        // Deduct tokens
        $used_tokens    = ($body['usage']['total_tokens'] ?? self::TOKEN_COST_PER_DOC);
        $new_balance    = max(0, $tokens - $used_tokens);
        update_user_meta($user_id, 'vmo_token_balance', $new_balance);

        // Determine title
        $titles = [
            'privacy_policy'  => 'Privacy Policy',
            'terms_of_service' => 'Terms of Service',
            'cookie_policy'   => 'Cookie Policy',
            'refund_policy'   => 'Refund Policy',
            'shipping_policy' => 'Shipping Policy',
            'sms_policy' => 'SMS Policy',
            'email_policy' => 'Email Policy',
            'disclaimer'      => 'Disclaimer',
            'acceptable_use'  => 'Acceptable Use Policy',
        ];
        $title = ($titles[$doc_type] ?? ucwords(str_replace('_', ' ', (string) $doc_type))) . ' — ' . $business_name;

        // Save to database
        $table = $this->ensure_table();
        global $wpdb;

        // Check for existing doc of same type
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$table} WHERE user_id = %d AND doc_type = %s LIMIT 1",
            $user_id, $doc_type
        ));

        $data = [
            'user_id'       => $user_id,
            'doc_type'      => $doc_type,
            'title'         => $title,
            'content'       => $content,
            'business_name' => $business_name,
            'business_url'  => $business_url,
            'jurisdiction'  => $jurisdiction,
            'status'        => 'draft',
        ];

        if ($existing) {
            $data['version'] = $wpdb->get_var($wpdb->prepare(
                "SELECT version FROM {$table} WHERE id = %d", $existing
            )) + 1;
            $wpdb->update($table, $data, ['id' => $existing]);
            $doc_id = (int) $existing;
        } else {
            $data['version'] = 1;
            $wpdb->insert($table, $data);
            $doc_id = (int) $wpdb->insert_id;
        }

        wp_send_json_success([
            'doc_id'        => $doc_id,
            'title'         => $title,
            'doc_type'      => $doc_type,
            'content'       => $content,
            'tokens_used'   => $used_tokens,
            'token_balance' => $new_balance,
            'version'       => $data['version'],
        ]);
    }

    /**
     * AJAX: Retrieve all legal documents for the current user.
     */
    public function ajax_get_legal_docs(): void {
        if (!current_user_can('read')) {
            wp_send_json_error(['message' => 'Forbidden'], 403);
        }
        if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
            wp_send_json_error(['message' => 'Security check failed'], 403);
        }

        $user_id = get_current_user_id();
        $table   = $this->ensure_table();
        global $wpdb;

        $docs = $wpdb->get_results($wpdb->prepare(
            "SELECT id, doc_type, title, status, version, published_page_id, created_at, updated_at
             FROM {$table} WHERE user_id = %d ORDER BY updated_at DESC",
            $user_id
        ), ARRAY_A);

        wp_send_json_success([
            'documents'       => $docs ?: [],
            'available_types' => self::DOCUMENT_TYPES,
        ]);
    }

    /**
     * AJAX: Save (update) an existing legal document's content.
     */
    public function ajax_save_legal_doc(): void {
        if (!current_user_can('read')) {
            wp_send_json_error(['message' => 'Forbidden'], 403);
        }
        if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
            wp_send_json_error(['message' => 'Security check failed'], 403);
        }

        $user_id = get_current_user_id();
        $doc_id  = isset($_POST['doc_id']) ? intval($_POST['doc_id']) : 0;
        $content = isset($_POST['content']) ? wp_kses_post($_POST['content']) : '';

        if (!$doc_id || empty($content)) {
            wp_send_json_error(['message' => 'Missing doc_id or content'], 400);
        }

        $table = $this->ensure_table();
        global $wpdb;

        $owner = $wpdb->get_var($wpdb->prepare(
            "SELECT user_id FROM {$table} WHERE id = %d", $doc_id
        ));

        if ((int) $owner !== $user_id) {
            wp_send_json_error(['message' => 'Document not found or access denied'], 403);
        }

        $wpdb->update($table, [
            'content' => $content,
            'version' => $wpdb->get_var($wpdb->prepare("SELECT version FROM {$table} WHERE id = %d", $doc_id)) + 1,
        ], ['id' => $doc_id]);

        wp_send_json_success(['message' => 'Document saved', 'doc_id' => $doc_id]);
    }

    /**
     * AJAX: Delete a legal document.
     */
    public function ajax_delete_legal_doc(): void {
        if (!current_user_can('read')) {
            wp_send_json_error(['message' => 'Forbidden'], 403);
        }
        if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
            wp_send_json_error(['message' => 'Security check failed'], 403);
        }

        $user_id = get_current_user_id();
        $doc_id  = isset($_POST['doc_id']) ? intval($_POST['doc_id']) : 0;

        $table = $this->ensure_table();
        global $wpdb;

        $deleted = $wpdb->delete($table, ['id' => $doc_id, 'user_id' => $user_id]);

        if ($deleted) {
            wp_send_json_success(['message' => 'Document deleted']);
        } else {
            wp_send_json_error(['message' => 'Document not found'], 404);
        }
    }

    /**
     * AJAX: Publish a legal document as a WordPress page.
     */
    public function ajax_publish_legal_doc(): void {
        if (!current_user_can('read')) {
            wp_send_json_error(['message' => 'Forbidden'], 403);
        }
        if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
            wp_send_json_error(['message' => 'Security check failed'], 403);
        }

        $user_id = get_current_user_id();
        $doc_id  = isset($_POST['doc_id']) ? intval($_POST['doc_id']) : 0;

        $table = $this->ensure_table();
        global $wpdb;

        $doc = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d AND user_id = %d",
            $doc_id, $user_id
        ), ARRAY_A);

        if (!$doc) {
            wp_send_json_error(['message' => 'Document not found'], 404);
        }

        // Create or update the WordPress page
        $page_data = [
            'post_title'   => $doc['title'],
            'post_content' => $doc['content'],
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_author'  => $user_id,
        ];

        if (!empty($doc['published_page_id']) && get_post($doc['published_page_id'])) {
            $page_data['ID'] = $doc['published_page_id'];
            $page_id = wp_update_post($page_data);
        } else {
            // Set slug based on doc type
            $slugs = [
                'privacy_policy'   => 'privacy-policy',
                'terms_of_service' => 'terms-of-service',
                'cookie_policy'    => 'cookie-policy',
                'refund_policy'    => 'refund-policy',
                'shipping_policy'  => 'shipping-policy',
                'sms_policy'       => 'sms-policy',
                'email_policy'     => 'email-policy',
                'disclaimer'       => 'disclaimer',
                'acceptable_use'   => 'acceptable-use-policy',
            ];
            $page_data['post_name'] = $slugs[$doc['doc_type']] ?? sanitize_title($doc['title']);
            $page_id = wp_insert_post($page_data);
        }

        if (is_wp_error($page_id)) {
            wp_send_json_error(['message' => 'Failed to publish page: ' . $page_id->get_error_message()], 500);
        }

        // Update the legal doc record
        $wpdb->update($table, [
            'status'            => 'published',
            'published_page_id' => $page_id,
        ], ['id' => $doc_id]);

        wp_send_json_success([
            'message'  => 'Legal document published as a page',
            'page_id'  => $page_id,
            'page_url' => get_permalink($page_id),
            'doc_id'   => $doc_id,
        ]);
    }

    /**
     * Build the AI prompt for legal document generation.
     */
    private function build_legal_prompt(string $doc_type, array $context): string {
        $business_name = $context['business_name'];
        $business_url  = $context['business_url'];
        $jurisdiction  = $context['jurisdiction'];
        $business_type = $context['business_type'];
        $extra         = $context['extra_context'];

        $type_labels = [
            'privacy_policy'   => 'Privacy Policy',
            'terms_of_service' => 'Terms of Service',
            'cookie_policy'    => 'Cookie Policy',
            'refund_policy'    => 'Refund & Cancellation Policy',
            'disclaimer'       => 'Website Disclaimer',
            'acceptable_use'   => 'Acceptable Use Policy',
        ];
        $label = $type_labels[$doc_type] ?? ucwords(str_replace('_', ' ', (string) $doc_type));

        $prompt = "Generate a comprehensive, professional {$label} for the following business:\n\n";
        $prompt .= "Business Name: {$business_name}\n";
        $prompt .= "Website URL: {$business_url}\n";
        $prompt .= "Jurisdiction: {$jurisdiction}\n";
        $prompt .= "Business Type: {$business_type}\n";

        if (!empty($extra)) {
            $prompt .= "Additional Context: {$extra}\n";
        }

        $prompt .= "\nRequirements:\n";
        $prompt .= "- Format the document in clean HTML with proper headings (h2, h3)\n";
        $prompt .= "- Include numbered sections and clauses\n";
        $prompt .= "- Use professional, clear legal language accessible to non-lawyers\n";
        $prompt .= "- Include a 'Last Updated' date placeholder at the top\n";
        $prompt .= "- Make it compliant with {$jurisdiction} regulations\n";

        // Type-specific requirements
        switch ($doc_type) {
            case 'privacy_policy':
                $prompt .= "- Include GDPR compliance sections (data collection, processing, rights)\n";
                $prompt .= "- Include CCPA/CPRA provisions\n";
                $prompt .= "- List types of data collected and how it's used\n";
                $prompt .= "- Include cookie usage disclosure\n";
                $prompt .= "- Include third-party service providers disclosure\n";
                $prompt .= "- Include data retention and deletion policies\n";
                break;

            case 'terms_of_service':
                $prompt .= "- Include account creation and responsibilities\n";
                $prompt .= "- Include intellectual property rights\n";
                $prompt .= "- Include limitation of liability\n";
                $prompt .= "- Include dispute resolution/arbitration clause\n";
                $prompt .= "- Include termination provisions\n";
                $prompt .= "- Include governing law section\n";
                break;

            case 'cookie_policy':
                $prompt .= "- List types of cookies used (essential, analytics, marketing)\n";
                $prompt .= "- Explain how to manage/disable cookies\n";
                $prompt .= "- Include third-party cookie providers\n";
                $prompt .= "- Include cookie consent mechanism\n";
                break;

            case 'refund_policy':
                $prompt .= "- Include refund eligibility criteria\n";
                $prompt .= "- Include refund process and timeline\n";
                $prompt .= "- Include subscription cancellation process\n";
                $prompt .= "- Include exceptions and non-refundable items\n";
                break;

            case 'disclaimer':
                $prompt .= "- Include general information disclaimer\n";
                $prompt .= "- Include professional advice disclaimer\n";
                $prompt .= "- Include external links disclaimer\n";
                $prompt .= "- Include AI-generated content disclaimer\n";
                break;

            case 'acceptable_use':
                $prompt .= "- Include prohibited activities\n";
                $prompt .= "- Include content restrictions\n";
                $prompt .= "- Include enforcement and penalties\n";
                $prompt .= "- Include reporting mechanism\n";
                break;
        }

        $prompt .= "\nReturn ONLY the HTML content of the document, no markdown code fences.";

        return $prompt;
    }
}

// Initialize the Legal Document Generator
add_action('init', function() {
    VMO_Legal::get_instance();
});
