<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/LegalTools.php';

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();

$input      = dbnToolsJsonInput(200000);
$events     = is_array($input['events'] ?? null) ? $input['events'] : [];
$whatFound  = trim((string)($input['what_we_found'] ?? ''));
$format     = (string)($input['format'] ?? 'docx');

if ($format !== 'docx') {
    http_response_code(400);
    echo json_encode(['error' => ['message' => 'Unsupported format.']]);
    exit;
}

if (!$events) {
    http_response_code(422);
    echo json_encode(['error' => ['message' => 'No events provided.']]);
    exit;
}

if (!class_exists('ZipArchive')) {
    http_response_code(500);
    echo json_encode(['error' => ['message' => 'ZipArchive extension not available.']]);
    exit;
}

$text = buildTimelineText($events, $whatFound);
$docx = buildTimelineDocx($text);

header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Disposition: attachment; filename="timeline.docx"');
header('Content-Length: ' . strlen($docx));
header('Cache-Control: no-store');
echo $docx;
exit;

function buildTimelineText(array $events, string $whatFound): string
{
    $lines = [];
    if ($whatFound !== '') {
        $lines[] = $whatFound;
        $lines[] = '';
        $lines[] = str_repeat("\u{2500}", 40);
        $lines[] = '';
    }

    foreach ($events as $ev) {
        $date      = (string)($ev['date']      ?? 'unknown date');
        $time      = (string)($ev['time']      ?? '');
        $actor     = (string)($ev['actor']     ?? '');
        $event     = (string)($ev['event']     ?? '');
        $excerpt   = (string)($ev['source_excerpt'] ?? '');
        $conf      = (string)($ev['confidence'] ?? '');

        $dateStr = $time !== '' ? "{$date}  {$time}" : $date;
        $header  = $actor !== '' ? "[{$dateStr}]  {$actor}" : "[{$dateStr}]";
        if ($conf !== '' && $conf !== 'high') {
            $header .= "  ({$conf} confidence)";
        }

        $lines[] = $header;
        if ($event !== '') $lines[] = $event;
        if ($excerpt !== '') $lines[] = "Source: \u{201C}{$excerpt}\u{201D}";
        $lines[] = '';
        $lines[] = str_repeat("\u{2500}", 40);
        $lines[] = '';
    }

    return implode("\n", $lines);
}

function buildTimelineDocx(string $text): string
{
    $tmp = tempnam(sys_get_temp_dir(), 'dbn_tl_');
    @unlink($tmp);
    $tmp .= '.docx';

    $zip = new ZipArchive();
    $zip->open($tmp, ZipArchive::CREATE | ZipArchive::OVERWRITE);

    $zip->addFromString('[Content_Types].xml', tlContentTypesXml());
    $zip->addFromString('_rels/.rels', tlRelsXml());
    $zip->addFromString('word/document.xml', tlDocumentXml($text));
    $zip->addFromString('word/_rels/document.xml.rels', tlWordRelsXml());
    $zip->addFromString('docProps/app.xml', tlAppXml());
    $zip->addFromString('docProps/core.xml', tlCoreXml());

    $zip->close();

    $bytes = file_get_contents($tmp);
    @unlink($tmp);
    return $bytes;
}

function tlDocumentXml(string $text): string
{
    $lines = explode("\n", str_replace("\r\n", "\n", str_replace("\r", "\n", $text)));
    $paras = [];
    foreach ($lines as $line) {
        $safe = htmlspecialchars($line, ENT_XML1 | ENT_COMPAT, 'UTF-8');
        if ($safe === '') {
            $paras[] = '<w:p/>';
        } elseif (preg_match('/^\[.+?\]/', $line)) {
            // Event header line — bold
            $paras[] = '<w:p><w:r><w:rPr><w:b/><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="20"/></w:rPr>'
                     . '<w:t xml:space="preserve">' . $safe . '</w:t></w:r></w:p>';
        } elseif (str_starts_with($line, str_repeat("\u{2500}", 5))) {
            // Divider line — light grey
            $paras[] = '<w:p><w:r><w:rPr><w:color w:val="AAAAAA"/><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="16"/></w:rPr>'
                     . '<w:t xml:space="preserve">' . $safe . '</w:t></w:r></w:p>';
        } else {
            $paras[] = '<w:p><w:r><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri"/><w:sz w:val="20"/></w:rPr>'
                     . '<w:t xml:space="preserve">' . $safe . '</w:t></w:r></w:p>';
        }
    }
    return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        . '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
        . '<w:body>' . implode('', $paras)
        . '<w:sectPr><w:pgSz w:w="12240" w:h="15840"/>'
        . '<w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>'
        . '</w:sectPr></w:body></w:document>';
}

function tlContentTypesXml(): string
{
    return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        . '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
        . '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
        . '<Default Extension="xml" ContentType="application/xml"/>'
        . '<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
        . '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>'
        . '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>'
        . '</Types>';
}

function tlRelsXml(): string
{
    return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
        . '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>'
        . '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>'
        . '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>'
        . '</Relationships>';
}

function tlWordRelsXml(): string
{
    return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        . '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>';
}

function tlAppXml(): string
{
    return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        . '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">'
        . '<Application>DoBetterNorge Timeline</Application>'
        . '</Properties>';
}

function tlCoreXml(): string
{
    $date = date('Y-m-d\TH:i:s\Z');
    return '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
        . '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"'
        . ' xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/"'
        . ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
        . '<dc:creator>DoBetterNorge</dc:creator>'
        . '<dcterms:created xsi:type="dcterms:W3CDTF">' . $date . '</dcterms:created>'
        . '</cp:coreProperties>';
}
