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

/**
 * VMO Documents Handler
 *
 * Bridges the Documents tab with consultation-driven AI results.
 * - Generates lightweight PDF files for requested documents (no external libs)
 * - Stores files in uploads/vmo-documents
 * - Creates/updates WP pages for site policies (privacy/terms/disclaimer)
 * - Exposes AJAX endpoints used by the dashboard
 */

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

if (!function_exists('vmo_prepare_document_generation_runtime')) {
    function vmo_prepare_document_generation_runtime() {
        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');
        }
    }
}

// Utilities
function vmo_docs_get_storage() {
    $uploads = wp_get_upload_dir();
    $dir = trailingslashit($uploads['basedir']) . 'vmo-documents';
    $url = trailingslashit($uploads['baseurl']) . 'vmo-documents';
    if (!file_exists($dir)) {
        wp_mkdir_p($dir);
    }
    return ['dir' => $dir, 'url' => $url];
}

function vmo_docs_slug($str) {
    $slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9\-_]+/', '-', (string)$str), '-'));
    return $slug ?: 'document';
}

/**
 * Minimal PDF writer (single page, Helvetica) to avoid external dependencies.
 * Writes ASCII-safe text content into a simple PDF canvas.
 */
function vmo_docs_write_simple_pdf($text, $filepath, $title = 'Document') {
    // Escape parentheses and backslashes for PDF string
    $esc = function($s){
        $s = str_replace(['\\', '(', ')', "\r", "\n"], ['\\\\', '\\(', '\\)', ' ', ' '], $s);
        // Limit length of a single Tj string
        return substr($s, 0, 50000);
    };

    $content = [];
    $content[] = 'BT';
    $content[] = '/F1 12 Tf';
    $x = 72; // 1 inch margin
    $y = 720; // start near top
    foreach (preg_split("/(\r\n|\n|\r)/", $text) as $line) {
        $safe = $esc($line);
        $content[] = sprintf('%d %d Td (%s) Tj', $x, $y, $safe);
        $y -= 16; // line height
        if ($y < 72) { // stop if out of page; very simple
            $content[] = 'ET';
            break;
        }
    }
    if (end($content) !== 'ET') $content[] = 'ET';
    $content_stream = implode("\n", $content);
    $len = strlen($content_stream);

    $objects = [];
    $objects[] = "1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj"; // catalog
    $objects[] = "2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj"; // pages
    $objects[] = "3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >> endobj"; // page
    $objects[] = "4 0 obj << /Length $len >> stream\n$content_stream\nendstream endobj"; // contents
    $objects[] = "5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj"; // font

    // Build xref
    $pdf = "%PDF-1.4\n";
    $offsets = [];
    $pdf .= "%\xFF\xFF\xFF\xFF\n"; // binary comment line to mark as binary
    foreach ($objects as $obj) {
        $offsets[] = strlen($pdf);
        $pdf .= $obj . "\n";
    }
    $xref_offset = strlen($pdf);
    $pdf .= "xref\n0 " . (count($objects)+1) . "\n";
    $pdf .= sprintf("%010d %05d f \n", 0, 65535);
    foreach ($offsets as $off) {
        $pdf .= sprintf("%010d %05d n \n", $off, 00000);
    }
    $pdf .= "trailer << /Size " . (count($objects)+1) . " /Root 1 0 R /Info 6 0 R >>\n";
    // Info object (6 0)
    $info = "6 0 obj << /Title (" . preg_replace('/[()\\\r\n]/','', (string)$title) . ") /Producer (VMO AI Builder) >> endobj\n";
    $pdf .= $info;
    $xref_offset2 = strlen($pdf);
    $pdf .= "startxref\n$xref_offset\n%%EOF";

    // Write file
    if (!vmo_get_filesystem()->put_contents($filepath, $pdf, FS_CHMOD_FILE)) {
        return new WP_Error('vmo_pdf_write_failed', 'Failed to write PDF file');
    }
    return true;
}

function vmo_docs_generate_body($doc_id, $context = []) {
    $biz = $context['business_name'] ?? 'Your Business';
    $type = $context['business_type'] ?? '';
    $today = date_i18n('F j, Y');
    $intro = "This document was generated automatically by VMO based on your consultation.\nBusiness: $biz" . ($type ? " ($type)" : '') . "\nDate: $today\n\n";

    // If enhanced consultation outputs are available, prefer them
    $ai = isset($context['ai']) && is_array($context['ai']) ? $context['ai'] : [];
    $ai_privacy = $ai['privacy_policy'] ?? null;
    $ai_terms = $ai['terms_of_service'] ?? null;
    $ai_disclaimer = $ai['disclaimer'] ?? null;
    $ai_business_plan = $ai['business_plan'] ?? null;
    $ai_marketing = $ai['marketing_strategy'] ?? null;
    $ai_competitive = $ai['competitive_analysis'] ?? null;
    switch ($doc_id) {
        case 'privacy':
        case 'privacy_policy':
            return [
                'title' => 'Privacy Policy',
                'body' => $intro . ($ai_privacy ?: (
                    "This Privacy Policy explains how we collect, use, and protect your information when you interact with $biz.\n\n" .
                    "• What we collect: contact details, usage data, purchase info.\n" .
                    "• Why we collect it: provide services, improve experience, comply with law.\n" .
                    "• How we protect it: encryption in transit, access controls, secure storage.\n\n" .
                    "Contact us for privacy requests at the email listed on our website.\n"
                ))
            ];
        case 'terms':
        case 'terms_of_service':
            return [
                'title' => 'Terms of Service',
                'body' => $intro . ($ai_terms ?: (
                    "These Terms govern your use of our website and services. By accessing our site you agree to these Terms.\n\n" .
                    "• Use restrictions and acceptable use\n" .
                    "• Payment, refunds (if applicable)\n" .
                    "• Warranties and disclaimers\n" .
                    "• Limitation of liability\n\n" .
                    "These Terms are governed by the laws of our operating region.\n"
                ))
            ];
        case 'disclaimer':
            return [
                'title' => 'Disclaimer',
                'body' => $intro . ($ai_disclaimer ?: (
                    "The information provided on this website is for general informational purposes only and does not constitute professional advice.\n"
                ))
            ];
        case 'service':
        case 'service_agreement':
            return [
                'title' => 'Service Agreement',
                'body' => $intro .
                    "Scope of work, deliverables, payment terms, acceptance criteria, IP, confidentiality, and termination clauses applicable to services provided by $biz.\n"
            ];
        case 'business_plan':
            return [
                'title' => 'Business Plan',
                'body' => $intro . ($ai_business_plan ?: (
                    "Executive Summary\nCompany Overview\nMarket & Competitor Analysis\nProducts & Services\nGo-to-Market Strategy\nOperations\nFinancial Plan\nMilestones\n"
                ))
            ];
        case 'marketing':
            return [
                'title' => 'Marketing Strategy',
                'body' => $intro . ($ai_marketing ?: (
                    "Target Audience\nPositioning\nBrand Messaging\nAcquisition Channels (SEO, Social, Email)\nCampaign Calendar\nKPIs & Budget\n"
                ))
            ];
        case 'competitive':
            return [
                'title' => 'Competitive Analysis',
                'body' => $intro . ($ai_competitive ?: (
                    "Top Competitors\nFeature Comparison\nDifferentiators\nPricing & Offers\nRisks & Responses\nAction Plan\n"
                ))
            ];
        default:
            // Generic template for library items
            return [
                'title' => ucwords(str_replace(['_', '-'], ' ', (string)$doc_id)),
                'body' => $intro . "Customized template for: " . ucwords(str_replace(['_', '-'], ' ', (string)$doc_id)) . ".\nFill in specific details as needed.\n"
            ];
    }
}

function vmo_docs_upsert_policy_page($slug, $title, $body) {
    // Create or update WP Page for policy docs
    $existing = get_page_by_path($slug);
    $content = wpautop(esc_html($body));
    $page = array(
        'post_title'   => $title,
        'post_name'    => $slug,
        'post_status'  => 'publish',
        'post_type'    => 'page',
        'post_content' => $content,
    );
    if ($existing) {
        $page['ID'] = $existing->ID;
        wp_update_post($page);
        return $existing->ID;
    }
    return wp_insert_post($page);
}

function vmo_docs_generate_and_store($doc_id, $context = []) {
    vmo_prepare_document_generation_runtime();

    $storage = vmo_docs_get_storage();
    $map = vmo_docs_generate_body($doc_id, $context);
    $title = $map['title'];
    $body = $map['body'];
    $slug = vmo_docs_slug($doc_id);
    $filename = $slug . '.pdf';
    $path = trailingslashit($storage['dir']) . $filename;
    $url  = trailingslashit($storage['url']) . $filename;

    $result = vmo_docs_write_simple_pdf($title . "\n\n" . $body, $path, $title);
    if (is_wp_error($result)) return $result;

    // Integrate into website for policy docs
    if (in_array($slug, ['privacy', 'privacy_policy'], true)) {
        vmo_docs_upsert_policy_page('privacy-policy', 'Privacy Policy', $body);
    } elseif (in_array($slug, ['terms', 'terms_of_service'], true)) {
        vmo_docs_upsert_policy_page('terms-of-service', 'Terms of Service', $body);
    } elseif (in_array($slug, ['disclaimer'], true)) {
        vmo_docs_upsert_policy_page('disclaimer', 'Disclaimer', $body);
    }

    return [
        'id' => $slug,
        'title' => $title,
        'filename' => $filename,
        'url' => $url,
        'generated_at' => current_time('mysql'),
    ];
}

// AJAX: Generate requested documents
function vmo_ai_generate_documents_ajax() {
    vmo_prepare_document_generation_runtime();

    if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    $user_id = get_current_user_id();

    // Load consultation context if available
    $context = [];
    if (class_exists('VMO_Consultation_Database')) {
        $db = new VMO_Consultation_Database();
        // Find latest consultation for user
        $rows = $db->get_user_consultations($user_id);
        if ($rows && count($rows)) {
            $latest = $rows[0];
            $context['business_name'] = $latest->business_name ?: '';
            $context['business_type'] = $latest->business_type ?: '';

            // Try to extract AI-generated texts from stored columns
            $ai = [];
            $maybe_decode = function($raw) {
                if (!is_string($raw) || $raw === '') return null;
                $d = json_decode($raw, true);
                return is_array($d) ? $d : $raw;
            };
            $consultation_data = $maybe_decode($latest->consultation_data);
            $business_analysis = $maybe_decode($latest->business_analysis);
            $recommendations = $maybe_decode($latest->recommendations);
            $website_data = $maybe_decode($latest->website_data);

            // Heuristics: look for likely keys from wizard outputs
            if (is_array($consultation_data)) {
                if (isset($consultation_data['business_package']) && is_array($consultation_data['business_package'])) {
                    $bp = $consultation_data['business_package'];
                    $ai['marketing_strategy'] = $bp['marketing_strategy'] ?? ($bp['seo_strategy'] ?? null);
                    $ai['competitive_analysis'] = $bp['competitor_analysis'] ?? null;
                    // Some flows may include legal docs inline
                    if (isset($bp['website']['legal_docs']) && is_array($bp['website']['legal_docs'])) {
                        $ld = $bp['website']['legal_docs'];
                        $ai['privacy_policy'] = $ld['privacy_policy'] ?? null;
                        $ai['terms_of_service'] = $ld['terms_of_service'] ?? null;
                        $ai['disclaimer'] = $ld['disclaimer'] ?? null;
                    }
                    if (isset($bp['downloads']['business_plan'])) {
                        $ai['business_plan'] = is_string($bp['downloads']['business_plan']) ? $bp['downloads']['business_plan'] : null;
                    }
                }
            }
            if (is_array($business_analysis)) {
                $ai['competitive_analysis'] = $ai['competitive_analysis'] ?? ($business_analysis['competitor_analysis'] ?? null);
                $ai['marketing_strategy'] = $ai['marketing_strategy'] ?? ($business_analysis['marketing_strategy'] ?? null);
            }
            if (is_array($website_data) && isset($website_data['legal_docs'])) {
                $ld = $website_data['legal_docs'];
                if (is_array($ld)) {
                    $ai['privacy_policy'] = $ai['privacy_policy'] ?? ($ld['privacy_policy'] ?? null);
                    $ai['terms_of_service'] = $ai['terms_of_service'] ?? ($ld['terms_of_service'] ?? null);
                    $ai['disclaimer'] = $ai['disclaimer'] ?? ($ld['disclaimer'] ?? null);
                }
            }

            // Attach if any
            if (!empty($ai)) {
                $context['ai'] = $ai;
            }
        }
    }

    $docs_json = isset($_POST['documents']) ? wp_unslash($_POST['documents']) : '[]';
    $docs = json_decode($docs_json, true);
    if (!is_array($docs)) $docs = [];
    $out = [];
    foreach ($docs as $d) {
        $id = isset($d['id']) ? $d['id'] : 'document';
        $gen = vmo_docs_generate_and_store($id, $context);
        if (!is_wp_error($gen)) $out[] = $gen;
    }
    wp_send_json_success(['documents' => $out]);
}

// AJAX: Return manifest (timestamps etc.)
function vmo_documents_manifest_ajax() {
    if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    $storage = vmo_docs_get_storage();
    $dir = rtrim($storage['dir'], '/');
    $manifest = [];
    if (file_exists($dir)) {
        $files = glob($dir . '/*.pdf');
        if ($files) {
            foreach ($files as $file) {
                $slug = basename($file, '.pdf');
                $manifest[$slug] = [
                    'updated' => date('c', filemtime($file)),
                    'url' => trailingslashit($storage['url']) . basename($file),
                ];
            }
        }
    }
    wp_send_json_success($manifest);
}

// AJAX: Custom documents uploaded by user
function vmo_documents_custom_ajax() {
    if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
        wp_send_json_error(['message' => 'Security check failed']);
    }
    // If needed, scan a subfolder uploads/vmo-documents/custom
    $storage = vmo_docs_get_storage();
    $custom_dir = trailingslashit($storage['dir']) . 'custom';
    $entries = [];
    if (file_exists($custom_dir)) {
        foreach (glob($custom_dir . '/*.*') as $f) {
            $entries[] = [
                'name' => basename($f),
                'added' => date('c', filemtime($f)),
                'path' => $f,
            ];
        }
    }
    wp_send_json_success(['items' => $entries]);
}

// AJAX: Log download (non-blocking client, here we just write to debug log)
function vmo_documents_log_download_ajax() {
    // Soft-validate nonce
    if (!function_exists('vmo_verify_admin_security') || !vmo_verify_admin_security()) {
        // still return success to avoid UX friction
        wp_send_json_success(['logged' => false]);
    }
    $doc = sanitize_text_field($_POST['document'] ?? $_POST['doc_type'] ?? '');
    $fmt = sanitize_text_field($_POST['format'] ?? 'pdf');
    $user = get_current_user_id();
    if (function_exists('error_log')) {
        error_log('[VMO] Document download: user=' . $user . ' doc=' . $doc . ' fmt=' . $fmt);
    }
    wp_send_json_success(['logged' => true]);
}

// Register AJAX actions
add_action('wp_ajax_vmo_ai_generate_documents', 'vmo_ai_generate_documents_ajax');
add_action('wp_ajax_vmo_documents_manifest', 'vmo_documents_manifest_ajax');
add_action('wp_ajax_vmo_documents_custom', 'vmo_documents_custom_ajax');
add_action('wp_ajax_vmo_documents_log_download', 'vmo_documents_log_download_ajax');

// Auto-generate core documents as soon as consultation generation artifacts are persisted.
add_action('vmo_consultation_generation_persisted', function($user_id, $session_id, $business_package, $website_result) {
    // Build context from business_package if available
    $ctx = [];
    if (is_array($business_package)) {
        $ctx['business_name'] = $business_package['business_name'] ?? '';
        $ctx['business_type'] = $business_package['business_type'] ?? '';
        $ctx['ai'] = [];
        if (isset($business_package['legal_docs'])) {
            $ctx['ai']['privacy_policy'] = $business_package['legal_docs']['privacy_policy'] ?? null;
            $ctx['ai']['terms_of_service'] = $business_package['legal_docs']['terms_of_service'] ?? null;
            $ctx['ai']['disclaimer'] = $business_package['legal_docs']['disclaimer'] ?? null;
        }
        if (isset($business_package['downloads']['business_plan'])) {
            $ctx['ai']['business_plan'] = is_string($business_package['downloads']['business_plan']) ? $business_package['downloads']['business_plan'] : null;
        }
        if (isset($business_package['marketing_strategy'])) {
            $ctx['ai']['marketing_strategy'] = $business_package['marketing_strategy'];
        }
        if (isset($business_package['competitor_analysis'])) {
            $ctx['ai']['competitive_analysis'] = $business_package['competitor_analysis'];
        }
    }
    // Generate core set
    $core = ['privacy','terms','disclaimer','business_plan','marketing','competitive'];
    foreach ($core as $doc) {
        vmo_docs_generate_and_store($doc, $ctx);
    }
    // Ensure dashboard timestamp reflects document generation completion
    update_option('vmo_dashboard_last_update_ts', time());
}, 10, 4);

?>
