<?php
namespace CAE\Modules\ExportEngine;

use CAE\Lib\Database;

class ExportEngine
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function getContent(int $contentId): ?array
    {
        return $this->db->fetch(
            "SELECT gc.*, t.title, t.primary_keyword, t.supporting_keywords,
                    p.business_name, pt.name AS page_type_name,
                    q.word_count, q.passed AS qa_passed, q.keyword_density
             FROM generated_content gc
             LEFT JOIN topics t   ON t.id  = gc.topic_id
             LEFT JOIN projects p ON p.id  = t.project_id
             LEFT JOIN page_types pt ON pt.id = t.page_type_id
             LEFT JOIN qa_logs q  ON q.content_id = gc.id
             WHERE gc.id = ?
             ORDER BY q.id DESC
             LIMIT 1",
            [$contentId]
        );
    }

    public function toHTML(int $contentId): string
    {
        $data = $this->getContent($contentId);
        if (!$data) {
            throw new \RuntimeException("Content #{$contentId} not found");
        }

        return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{$this->e($data['title'])}</title>
<style>
  body { font-family: Georgia, serif; max-width: 860px; margin: 40px auto; padding: 0 20px; line-height: 1.7; color: #2d2d2d; }
  h1 { font-size: 2em; margin-bottom: .4em; }
  h2 { font-size: 1.4em; margin-top: 1.8em; color: #1a1a2e; }
  h3 { font-size: 1.15em; margin-top: 1.4em; color: #333; }
  p  { margin: .9em 0; }
  ul, ol { margin: .9em 0 .9em 1.5em; }
  .meta { font-size: .85em; color: #888; margin-bottom: 2em; border-bottom: 1px solid #eee; padding-bottom: .8em; }
</style>
</head>
<body>
<div class="meta">
  <strong>Business:</strong> {$this->e($data['business_name'])} &nbsp;|&nbsp;
  <strong>Page Type:</strong> {$this->e($data['page_type_name'])} &nbsp;|&nbsp;
  <strong>Keyword:</strong> {$this->e($data['primary_keyword'])} &nbsp;|&nbsp;
  <strong>Words:</strong> {$data['word_count']}
</div>
{$data['output']}
</body>
</html>
HTML;
    }

    public function toJSON(int $contentId): string
    {
        $data = $this->getContent($contentId);
        if (!$data) {
            throw new \RuntimeException("Content #{$contentId} not found");
        }

        $export = [
            'id'               => $data['id'],
            'title'            => $data['title'],
            'business_name'    => $data['business_name'],
            'page_type'        => $data['page_type_name'],
            'primary_keyword'  => $data['primary_keyword'],
            'content_html'     => $data['output'],
            'word_count'       => $data['word_count'],
            'keyword_density'  => $data['keyword_density'],
            'qa_passed'        => (bool)$data['qa_passed'],
            'model_used'       => $data['model_used'],
            'generated_at'     => $data['created_at'],
            'tokens'           => [
                'input'  => $data['input_tokens'],
                'output' => $data['output_tokens'],
            ],
        ];

        return json_encode($export, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    public function toWord(int $contentId): string
    {
        $data = $this->getContent($contentId);
        if (!$data) {
            throw new \RuntimeException("Content #{$contentId} not found");
        }

        // Word-compatible HTML (opens in MS Word as .doc)
        return <<<DOC
<html xmlns:o='urn:schemas-microsoft-com:office:office'
      xmlns:w='urn:schemas-microsoft-com:office:word'
      xmlns='http://www.w3.org/TR/REC-html40'>
<head>
<meta charset="UTF-8">
<meta name=ProgId content=Word.Document>
<meta name=Generator content='Microsoft Word 11'>
<meta name=Originator content='Microsoft Word 11'>
<!--[if gte mso 9]><xml>
<w:WordDocument>
  <w:View>Print</w:View>
  <w:Zoom>90</w:Zoom>
  <w:DoNotOptimizeForBrowser/>
</w:WordDocument>
</xml><![endif]-->
<style>
  body { font-family: Calibri, sans-serif; font-size: 11pt; line-height: 1.6; }
  h1   { font-size: 18pt; color: #1a1a2e; }
  h2   { font-size: 14pt; color: #2c3e50; }
  h3   { font-size: 12pt; color: #34495e; }
  p    { margin: 6pt 0; }
  .meta{ font-size: 9pt; color: #666; border-bottom: 1pt solid #ccc; padding-bottom: 6pt; margin-bottom: 12pt; }
</style>
</head>
<body>
<div class="meta">
  Business: {$this->e($data['business_name'])} | Page Type: {$this->e($data['page_type_name'])} |
  Keyword: {$this->e($data['primary_keyword'])} | Words: {$data['word_count']} | Generated: {$data['created_at']}
</div>
{$data['output']}
</body>
</html>
DOC;
    }

    private function e(mixed $v): string
    {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}
