<?php
/**
 * api/download_doc.php
 * Skrip untuk men-generate file fisik (Excel, Word, PDF) dari Markdown Table AI
 */

if (!isset($_GET['id'])) {
    die("ID Dokumen tidak valid.");
}

$file_id = preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['id']);
$temp_path = "../uploads/" . $file_id . ".txt";

if (!file_exists($temp_path)) {
    die("Dokumen tidak ditemukan atau sudah kadaluarsa.");
}

$dataRaw = file_get_contents($temp_path);
$data = json_decode($dataRaw, true);

if (!$data) {
    die("Format dokumen tidak valid.");
}

$type = strtolower($data['type']);
$content_md = $data['content'];

// Fungsi pembersih format Markdown
function parseInlineMarkdown($text) {
    $text = htmlspecialchars($text);
    // Bold
    $text = preg_replace('/(\*\*|__)(.*?)\1/s', '<strong>$2</strong>', $text);
    // Italic
    $text = preg_replace('/(?<!\*)\*(.*?)\*(?!\*)/s', '<em>$1</em>', $text);
    $text = preg_replace('/(?<!_)_(.*?)_(?!_)/s', '<em>$1</em>', $text);
    // Strikethrough
    $text = preg_replace('/~~(.*?)~~/s', '<del>$1</del>', $text);
    // Inline Code
    $text = preg_replace('/`(.*?)`/s', '<code style="background-color: #f6f8fa; padding: 2px 4px; border-radius: 4px; font-family: monospace; font-size: 11pt; color: #d63384;">$1</code>', $text);
    return $text;
}

// Konversi Markdown lengkap (Artikel, List, Tabel) menjadi HTML
function parseFullMarkdown($markdown) {
    // Ekstrak code blocks (multiline) terlebih dahulu agar tidak terpotong per baris
    $codeBlocks = [];
    $markdown = preg_replace_callback('/```([a-zA-Z]*)\n?(.*?)```/s', function($matches) use (&$codeBlocks) {
        $code = htmlspecialchars($matches[2]);
        $placeholder = "%%%CODE_BLOCK_" . count($codeBlocks) . "%%%";
        $codeBlocks[] = "<pre style='background-color: #f6f8fa; padding: 12px; border-radius: 6px; font-family: \"Courier New\", Courier, monospace; font-size: 11pt; overflow-x: auto; border: 1px solid #e1e4e8; margin: 15px 0;'><code style='white-space: pre-wrap;'>$code</code></pre>";
        return "\n$placeholder\n";
    }, $markdown);

    $lines = explode("\n", trim($markdown));
    $parsed_html = "";
    
    $inTable = false;
    $isHeader = true;
    $inUl = false;
    $inOl = false;

    foreach ($lines as $line) {
        $trimmed = trim($line);
        
        // Kembalikan Code Block
        if (preg_match('/^%%%CODE_BLOCK_[0-9]+%%%$/', $trimmed)) {
            // Tutup list/tabel sebelum menyisipkan code block
            if ($inUl) { $parsed_html .= "</ul>\n"; $inUl = false; }
            if ($inOl) { $parsed_html .= "</ol>\n"; $inOl = false; }
            if ($inTable) { $parsed_html .= "</table>\n"; $inTable = false; }
            $parsed_html .= $trimmed . "\n";
            continue;
        }

        // Jangan putuskan list atau elemen lain saat ada baris kosong
        if ($trimmed === '') {
            if ($inTable) { $parsed_html .= "</table>\n"; $inTable = false; }
            continue;
        }

        // Deteksi List Item
        $isUlItem = preg_match('/^[\-\*]\s+(.*)$/', $trimmed, $ulMatch);
        $isOlItem = preg_match('/^[0-9]+\.\s+(.*)$/', $trimmed, $olMatch);
        
        if ($isUlItem && $inOl) { $parsed_html .= "</ol>\n"; $inOl = false; }
        if ($isOlItem && $inUl) { $parsed_html .= "</ul>\n"; $inUl = false; }
        
        if (!$isUlItem && !$isOlItem) {
            if ($inUl) { $parsed_html .= "</ul>\n"; $inUl = false; }
            if ($inOl) { $parsed_html .= "</ol>\n"; $inOl = false; }
        }

        // --- TABLES ---
        if (strpos($trimmed, '|') !== false && strlen($trimmed) >= 3 && preg_match('/\|.*\|/', $trimmed)) {
            if (preg_match('/^[\s\|\-:]+$/', $trimmed)) {
                $isHeader = false;
                continue; 
            }
            if (!$inTable) {
                $parsed_html .= "<table border='1' cellpadding='8' cellspacing='0' style='border-collapse: collapse; width: 100%; margin: 15px 0; font-family: Arial, Helvetica, sans-serif; font-size: 12pt; border: 1px solid #d1d5db;'>\n";
                $inTable = true;
                $isHeader = true; 
            }
            $cols = explode('|', trim($trimmed, '|'));
            $parsed_html .= "  <tr>\n";
            foreach ($cols as $col) {
                // Abaikan cell kosong pertama dan terakhir
                if ($col === '' && ($cols[0] === '' || end($cols) === '')) continue;
                $val = parseInlineMarkdown(trim($col)); 
                if ($isHeader) {
                    $parsed_html .= "    <th style='background-color: #f3f4f6; font-weight: bold; text-align: left; border: 1px solid #d1d5db; padding: 10px; color: #111827; font-family: Arial, Helvetica, sans-serif; font-size: 12pt;'>" . $val . "</th>\n";
                } else {
                    $parsed_html .= "    <td style='border: 1px solid #d1d5db; padding: 10px; color: #374151; font-family: Arial, Helvetica, sans-serif; font-size: 12pt; text-align: left; vertical-align: top;'>" . $val . "</td>\n";
                }
            }
            $parsed_html .= "  </tr>\n";
            continue;
        }
        
        if ($inTable && $trimmed !== '') {
            $parsed_html .= "</table>\n";
            $inTable = false;
        }
        
        // --- HEADINGS ---
        if (preg_match('/^(#{1,6})\s*(.*)$/', $trimmed, $m)) {
            $level = strlen($m[1]);
            $title = parseInlineMarkdown($m[2]);
            $styles = [
                1 => "margin-top: 20px; margin-bottom: 15px; font-family: Arial, Helvetica, sans-serif; color: #1a73e8; border-bottom: 2px solid #1a73e8; padding-bottom: 8px; font-size: 18pt; font-weight: bold; text-align: center;",
                2 => "margin-top: 20px; margin-bottom: 12px; font-family: Arial, Helvetica, sans-serif; color: #111827; border-bottom: 1px solid #e5e7eb; padding-bottom: 5px; font-size: 16pt; font-weight: bold;",
                3 => "margin-top: 15px; margin-bottom: 10px; font-family: Arial, Helvetica, sans-serif; color: #1f2937; font-size: 14pt; font-weight: bold;",
                4 => "margin-top: 10px; margin-bottom: 8px; font-family: Arial, Helvetica, sans-serif; color: #374151; font-size: 12pt; font-weight: bold;",
                5 => "margin-top: 10px; margin-bottom: 8px; font-family: Arial, Helvetica, sans-serif; color: #4b5563; font-size: 12pt; font-weight: bold; font-style: italic;",
                6 => "margin-top: 10px; margin-bottom: 8px; font-family: Arial, Helvetica, sans-serif; color: #6b7280; font-size: 12pt; font-weight: bold;"
            ];
            $parsed_html .= "<h{$level} style='{$styles[$level]}'>" . $title . "</h{$level}>\n";
        } 
        
        // --- LISTS ---
        elseif ($isUlItem) {
            if (!$inUl) {
                $parsed_html .= "<ul style='margin-bottom: 15px; margin-top: 5px; padding-left: 25px; font-family: Arial, Helvetica, sans-serif; font-size: 12pt; line-height: 1.5; color: #000000; text-align: justify;'>\n";
                $inUl = true;
            }
            $parsed_html .= "  <li style='margin-bottom: 6px;'>" . parseInlineMarkdown($ulMatch[1]) . "</li>\n";
        } elseif ($isOlItem) {
            if (!$inOl) {
                $parsed_html .= "<ol style='margin-bottom: 15px; margin-top: 5px; padding-left: 25px; font-family: Arial, Helvetica, sans-serif; font-size: 12pt; line-height: 1.5; color: #000000; text-align: justify;'>\n";
                $inOl = true;
            }
            $parsed_html .= "  <li style='margin-bottom: 6px;'>" . parseInlineMarkdown($olMatch[1]) . "</li>\n";
        } 
        
        // --- BLOCKQUOTES ---
        elseif (preg_match('/^>\s+(.*)$/', $trimmed, $m)) {
            $parsed_html .= "<blockquote style='border-left: 4px solid #cbd5e1; padding: 10px 15px; color: #475569; margin: 12px 0; font-style: italic; background-color: #f8fafc; font-family: Arial, Helvetica, sans-serif; font-size: 12pt; text-align: justify;'>" . parseInlineMarkdown($m[1]) . "</blockquote>\n";
        }
        
        // --- PARAGRAPHS ---
        else {
            $parsed_html .= "<p style='margin-bottom: 12px; margin-top: 0; line-height: 1.5; font-family: Arial, Helvetica, sans-serif; font-size: 12pt; color: #000000; text-align: justify;'>" . parseInlineMarkdown($trimmed) . "</p>\n";
        }
    }
    
    if ($inUl) $parsed_html .= "</ul>\n";
    if ($inOl) $parsed_html .= "</ol>\n";
    if ($inTable) $parsed_html .= "</table>\n";
    
    // Kembalikan Code Blocks ke posisinya
    foreach ($codeBlocks as $i => $block) {
        $parsed_html = str_replace("%%%CODE_BLOCK_$i%%%", $block, $parsed_html);
    }
    
    return $parsed_html;
}

$html_content = parseFullMarkdown($content_md);
$filename = "XieqaAI_Document_" . date('Ymd_His');

if ($type === 'excel') {
    header("Content-Type: application/vnd.ms-excel; charset=utf-8");
    header("Content-Disposition: attachment; filename=\"$filename.xls\"");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">\n";
    echo "<head><meta charset='UTF-8'>\n";
    echo "<style> body { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #000; padding: 8px; vertical-align: top; } th { background-color: #f2f2f2; font-weight: bold; } </style>\n";
    echo "</head><body>";
    echo "<h2 style='text-align: center; font-family: Arial, Helvetica, sans-serif; font-size: 16pt; margin-bottom: 20px;'>Data Generate by Xieqa AI</h2>";
    echo $html_content;
    echo "</body></html>";
    exit;
} 
elseif ($type === 'word') {
    header("Content-Type: application/vnd.ms-word; charset=utf-8");
    header("Content-Disposition: attachment; filename=\"$filename.doc\"");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo "<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\">\n";
    echo "<head><meta charset='UTF-8'>\n";
    echo "<style>\n";
    echo "  @page WordSection1 { size: 595.3pt 841.9pt; margin: 72.0pt 72.0pt 72.0pt 72.0pt; mso-header-margin: 36.0pt; mso-footer-margin: 36.0pt; mso-paper-source: 0; }\n";
    echo "  div.WordSection1 { page: WordSection1; }\n";
    echo "  body { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; line-height: 1.5; text-align: justify; }\n";
    echo "  p { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; line-height: 1.5; margin-bottom: 12pt; text-align: justify; }\n";
    echo "  table { width: 100%; border-collapse: collapse; margin-bottom: 12pt; }\n";
    echo "  th, td { border: 1px solid #000; padding: 8px; vertical-align: top; }\n";
    echo "  h1, h2, h3, h4, h5, h6 { font-family: Arial, Helvetica, sans-serif; font-weight: bold; }\n";
    echo "</style>\n";
    echo "</head><body>";
    echo "<div class='WordSection1'>\n";
    echo "<h2 style='text-align: center; font-family: Arial, Helvetica, sans-serif; font-size: 16pt; margin-bottom: 20px;'>Dokumen Generate by Xieqa AI</h2>";
    echo $html_content;
    echo "</div></body></html>";
    exit;
}
elseif ($type === 'pdf') {
    // Cegah warning dari PHP 8 yang bisa merusak output PDF
    error_reporting(0);
    ini_set('display_errors', 0);
    ob_start();

    // Memuat library TCPDF
    require_once('../libs/TCPDF-6.7.5/tcpdf.php');
    
    // Buat objek PDF baru
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

    // Set informasi dokumen
    $pdf->SetCreator('Xieqa AI');
    $pdf->SetAuthor('Agent Koding');
    $pdf->SetTitle($filename);

    // Set header & footer margin
    $pdf->SetMargins(15, 15, 15);
    $pdf->SetHeaderMargin(5);
    $pdf->SetFooterMargin(10);
    $pdf->SetAutoPageBreak(TRUE, 15);
    
    // Hapus header bawaan agar lebih bersih
    $pdf->setPrintHeader(false);
    $pdf->setPrintFooter(true);

    // Tambahkan halaman baru
    $pdf->AddPage();

    // Set Font 'helvetica' yang setara dengan Arial
    $pdf->SetFont('helvetica', '', 12);

    // Buat styling CSS bawaan untuk tabel
    $style = "
        <style>
            h2 { color: #1a73e8; border-bottom: 2px solid #1a73e8; text-align: center; font-size: 16pt; font-family: helvetica, sans-serif; }
            table { width: 100%; border-collapse: collapse; }
            th { background-color: #f2f2f2; font-weight: bold; border: 1px solid #ccc; padding: 8px; font-family: helvetica, sans-serif; }
            td { border: 1px solid #ccc; padding: 8px; font-family: helvetica, sans-serif; }
            p { font-family: helvetica, sans-serif; font-size: 12pt; line-height: 1.5; text-align: justify; margin-bottom: 12pt; }
        </style>
    ";

    // Gabungkan konten
    $pdf_content = $style . '<h2>Data Generate by Xieqa AI</h2><br>' . $html_content;

    // Tulis ke PDF
    $pdf->writeHTML($pdf_content, true, false, true, false, '');

    // Bersihkan buffer agar tidak ada spasi atau teks warning yang terkirim ke PDF
    while (ob_get_level()) {
        ob_end_clean();
    }

    // Output file (Langsung Unduh dengan parameter 'D')
    $pdf->Output($filename . '.pdf', 'D');
    exit;
} else {
    die("Tipe file tidak didukung.");
}
?>
