<?php
// --- PHP LOGIC FOR DOCUMENT GENERATION ---

// Initialize variables to avoid errors on the initial page load
$output_content_html = '';
$docx_content_html = '';
$show_output = false;
$form_values = [
    'ministry' => 'กระทรวงดิจิทัลเพื่อเศรษฐกิจและสังคม',
    'department' => 'สำนักงานคณะกรรมการดิจิทัลเพื่อเศรษฐกิจและสังคมแห่งชาติ',
    'agency' => 'ฝ่ายบริหารกลาง',
    'address' => '120',
    'subdistrict' => 'ทุ่งสองห้อง',
    'district' => 'หลักสี่',
    'province' => 'กรุงเทพมหานคร',
    'zipcode' => '10210',
    'approver_name' => 'พันเอกสรรพชัย หุวะนันทน์',
    'approver_position' => 'กรรมการผู้จัดการใหญ่',
    'project_name' => 'โครงการพัฒนาระบบสำรองและกู้คืนข้อมูล (Disaster Recovery Solution)',
    'start_date' => date('Y-m-d'), // Default to today
    'project_details' => "เนื่องด้วย [ชื่อกรม] ในฐานะหน่วยงานภายใต้สังกัด [ชื่อกระทรวง] มีภารกิจสำคัญในการให้บริการประชาชนและบริหารจัดการข้อมูลภาครัฐ ซึ่งปัจจุบันระบบเทคโนโลยีสารสนเทศหลักยังคงมีความเสี่ยงสูงต่อการหยุดชะงักของบริการอันเนื่องมาจากภัยพิบัติ, ความขัดข้องของอุปกรณ์, หรือภัยคุกคามทางไซเบอร์ ซึ่งอาจส่งผลกระทบต่อความต่อเนื่องในการดำเนินงานและความเชื่อมั่นของประชาชน\n\nดังนั้น [ชื่อกรม] จึงมีความประสงค์ที่จะจัดทำ \"โครงการพัฒนาระบบสำรองและกู้คืนข้อมูล (Disaster Recovery Solution)\" ขึ้น เพื่อสร้างระบบสำรองสำหรับระบบงานและข้อมูลที่สำคัญไว้บนคลาวด์ภาครัฐ (Government Cloud) อันจะช่วยลดความเสี่ยงและสร้างความมั่นใจว่าหน่วยงานจะสามารถกู้คืนระบบและกลับมาให้บริการได้อย่างรวดเร็วในสภาวะฉุกเฉิน",
    'project_objective' => "1. เพื่อจัดตั้งระบบสำรองและกู้คืนข้อมูล (Disaster Recovery Site) สำหรับระบบสารสนเทศที่สำคัญของ [ชื่อกรม] บนโครงสร้างพื้นฐานคลาวด์ภาครัฐ\n2. เพื่อลดความเสี่ยงจากการสูญหายของข้อมูลและลดระยะเวลาการหยุดชะงักของระบบ (Downtime) ให้น้อยที่สุดตามเป้าหมายตัวชี้วัด RTO/RPO ที่กำหนด\n3. เพื่อสร้างความเชื่อมั่นในการให้บริการอย่างต่อเนื่อง (Business Continuity) ของหน่วยงานในทุกสถานการณ์\n4. เพื่อเพิ่มความปลอดภัยและเสถียรภาพของข้อมูล โดยการโอนย้ายข้อมูลจากระบบเดิมขึ้นสู่คลาวด์ภาครัฐที่ได้มาตรฐาน\n5. เพื่อสนับสนุนนโยบายรัฐบาลดิจิทัลและเพิ่มประสิทธิภาพในการบริหารจัดการทรัพยากรเทคโนโลยีสารสนเทศ",
    'project_scope' => "1. วิเคราะห์และประเมินระบบงานปัจจุบัน เพื่อจัดลำดับความสำคัญของระบบที่ต้องนำเข้าสู่แผนการสำรองและกู้คืนข้อมูล\n2. ออกแบบสถาปัตยกรรมของระบบสำรองและกู้คืนข้อมูลบนคลาวด์ภาครัฐให้สอดคล้องกับข้อกำหนดด้านความปลอดภัยและประสิทธิภาพ\n3. ดำเนินการโอนย้าย (Migrate) ระบบงานและข้อมูลที่สำคัญจากระบบเดิมไปยังศูนย์ข้อมูลสำรองบนคลาวด์ภาครัฐ\n4. ติดตั้งและตั้งค่าเครื่องมือสำหรับการทำสำเนาข้อมูล (Data Replication) อย่างสม่ำเสมอระหว่างศูนย์ข้อมูลหลักและศูนย์ข้อมูลสำรอง\n5. จัดทำแผนการกู้คืนระบบ (Disaster Recovery Plan) และขั้นตอนการปฏิบัติงานที่เป็นลายลักษณ์อักษร\n6. ทดสอบแผนการกู้คืนระบบ (DR Drill) เพื่อตรวจสอบความถูกต้องและประสิทธิภาพของระบบที่จัดทำขึ้น\n7. จัดอบรมให้แก่เจ้าหน้าที่ผู้รับผิดชอบ เพื่อให้สามารถบริหารจัดการและปฏิบัติงานตามแผนการกู้คืนระบบได้"
];

// Helper function to format date to Thai Buddhist Era
function formatDateThai($date_string) {
    if (empty($date_string)) return '';
    $date = new DateTime($date_string);
    return $date->format('d/m/') . ($date->format('Y') + 543);
}

// Helper function to generate the action plan
function generateActionPlan($start_date_str) {
    if (empty($start_date_str)) {
        $error_msg = '<p class="text-red-500">กรุณาเลือกวันเริ่มโครงการ</p>';
        return ['displayHTML' => $error_msg, 'docxHTML' => $error_msg];
    }

    $tasks = [
        ["name" => "1. วิเคราะห์และประเมินระบบงานปัจจุบัน", "duration" => 14],
        ["name" => "2. ออกแบบสถาปัตยกรรมของระบบสำรองและกู้คืนข้อมูล", "duration" => 14],
        ["name" => "3. ดำเนินการโอนย้าย (Migrate) ระบบงานและข้อมูล", "duration" => 28],
        ["name" => "4. ติดตั้งและตั้งค่าเครื่องมือสำหรับการทำสำเนาข้อมูล", "duration" => 14],
        ["name" => "5. จัดทำแผนการกู้คืนระบบ (DR Plan)", "duration" => 14],
        ["name" => "6. ทดสอบแผนการกู้คืนระบบ (DR Drill)", "duration" => 7],
        ["name" => "7. จัดอบรมให้แก่เจ้าหน้าที่ผู้รับผิดชอบ", "duration" => 7]
    ];

    $current_date = new DateTime($start_date_str);
    $display_table_html = '<table class="timeline-table"><thead><tr><th>ลำดับ</th><th>รายการดำเนินการ</th><th>ระยะเวลา</th><th>วันที่เริ่ม</th><th>วันที่สิ้นสุด</th></tr></thead><tbody>';
    $docx_table_html = '<table border="1" style="width: 100%; border-collapse: collapse;"><thead><tr><th>ลำดับ</th><th>รายการดำเนินการ</th><th>ระยะเวลา</th><th>วันที่เริ่ม</th><th>วันที่สิ้นสุด</th></tr></thead><tbody>';
    
    $milestones = [];
    $thai_months = ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"];

    foreach ($tasks as $index => $task) {
        $task_start_date = clone $current_date;
        $task_end_date = (clone $task_start_date)->modify('+' . ($task['duration'] - 1) . ' days');
        
        $table_row = "
            <tr>
                <td>" . ($index + 1) . "</td>
                <td>" . htmlspecialchars($task['name']) . "</td>
                <td>" . ($task['duration'] / 7) . " สัปดาห์</td>
                <td>" . formatDateThai($task_start_date->format('Y-m-d')) . "</td>
                <td>" . formatDateThai($task_end_date->format('Y-m-d')) . "</td>
            </tr>
        ";
        $display_table_html .= $table_row;
        $docx_table_html .= $table_row;

        $month_year_key = $task_start_date->format('n/Y');
        if (!isset($milestones[$month_year_key])) {
            $milestones[$month_year_key] = [];
        }
        $milestones[$month_year_key][] = "ดำเนินการ '" . htmlspecialchars($task['name']) . "'";
        
        $current_date = (clone $task_end_date)->modify('+1 day');
    }

    $display_table_html .= '</tbody></table>';
    $docx_table_html .= '</tbody></table>';

    $milestone_html = '<div class="mt-6">';
    $docx_milestone_html = '<br/>';
    $milestone_counter = 1;
    
    foreach ($milestones as $key => $items) {
        list($month, $year) = explode('/', $key);
        $month_name = $thai_months[(int)$month - 1];
        $thai_year = (int)$year + 543;
        $milestone_title = "Milestone เดือนที่ {$milestone_counter} ({$month_name} {$thai_year})";
        
        $milestone_items_html = '<ul>';
        foreach ($items as $item) {
            $milestone_items_html .= "<li>{$item}</li>";
        }
        $milestone_items_html .= '</ul>';

        $milestone_html .= "<div class=\"milestone\"><h4 class=\"font-bold text-md text-indigo-700\">{$milestone_title}</h4><ul class=\"list-disc list-inside text-sm text-gray-600 mt-1\">" . str_replace(['<ul>', '</ul>'], '', $milestone_items_html) . "</ul></div>";
        $docx_milestone_html .= "<h3>{$milestone_title}</h3>{$milestone_items_html}";
        $milestone_counter++;
    }
    $milestone_html .= '</div>';

    return [
        'displayHTML' => $display_table_html . $milestone_html,
        'docxHTML' => $docx_table_html . $docx_milestone_html
    ];
}


// Check if the form was submitted via POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $show_output = true;

    // Sanitize and retrieve form values, overwriting defaults
    foreach ($form_values as $key => $default) {
        $form_values[$key] = isset($_POST[$key]) ? htmlspecialchars($_POST[$key], ENT_QUOTES, 'UTF-8') : $default;
    }

    // Replace placeholders in textareas
    $ministry_name = $form_values['ministry'];
    $department_name = $form_values['department'];

    $project_details_processed = str_replace(
        ['[ชื่อกระทรวง]', '[ชื่อกรม]'],
        [$ministry_name, $department_name],
        $form_values['project_details']
    );

    $project_objective_processed = str_replace(
        '[ชื่อกรม]',
        $department_name,
        $form_values['project_objective']
    );

    $project_scope_processed = $form_values['project_scope'];
    
    // Generate Action Plan
    $plan_data = generateActionPlan($form_values['start_date']);

    // --- Prepare Display HTML ---
    $output_content_html = "
        <div>
            <h3 class='font-bold text-lg mb-4 border-b pb-2'>ข้อมูลหน่วยงาน</h3>
            <div class='space-y-2 text-sm'>
                <div class='flex'><p class='output-label'>กระทรวง :</p><p class='output-value'>{$form_values['ministry']}</p></div>
                <div class='flex'><p class='output-label'>กรม :</p><p class='output-value'>{$form_values['department']}</p></div>
                <div class='flex'><p class='output-label'>หน่วยงาน :</p><p class='output-value'>{$form_values['agency']}</p></div>
                <div class='flex'>
                    <div class='flex w-1/2 pr-2'><p class='output-label'>ที่อยู่ :</p><p class='output-value'>{$form_values['address']}</p></div>
                     <div class='flex w-1/2 pl-2'><p class='output-label'>แขวง/ตำบล :</p><p class='output-value'>{$form_values['subdistrict']}</p></div>
                </div>
                <div class='flex'>
                    <div class='flex w-1/2 pr-2'><p class='output-label'>เขต/อำเภอ :</p><p class='output-value'>{$form_values['district']}</p></div>
                    <div class='flex w-1/2 pl-2'><p class='output-label'>จังหวัด :</p><p class='output-value'>{$form_values['province']}</p></div>
                </div>
                 <div class='flex'><p class='output-label'>รหัสไปรษณีย์ :</p><p class='output-value'>{$form_values['zipcode']}</p></div>
                <div class='flex'>
                    <div class='flex w-1/2 pr-2'><p class='output-label'>ชื่อผู้มีอำนาจอนุมัติ :</p><p class='output-value'>{$form_values['approver_name']}</p></div>
                    <div class='flex w-1/2 pl-2'><p class='output-label'>ตำแหน่ง :</p><p class='output-value'>{$form_values['approver_position']}</p></div>
                </div>
            </div>
        </div>
        <hr class='my-6'>
        <div>
            <h3 class='font-bold text-lg mb-4 border-b pb-2'>ข้อมูลโครงการ</h3>
            <div class='space-y-4 text-sm'>
                <div class='flex'><p class='output-label'>ชื่อโครงการ :</p><p class='output-value font-semibold'>{$form_values['project_name']}</p></div>
                <div><p class='output-label mb-1'>รายละเอียดโครงการ :</p><p class='pl-4 text-gray-700'>" . nl2br($project_details_processed) . "</p></div>
                <div><p class='output-label mb-1'>วัตถุประสงค์โครงการ :</p><p class='pl-4 text-gray-700'>" . nl2br($project_objective_processed) . "</p></div>
                <div><p class='output-label mb-1'>ขอบเขตของโครงการ :</p><p class='pl-4 text-gray-700'>" . nl2br($project_scope_processed) . "</p></div>
            </div>
        </div>
        <hr class='my-6'>
        <div>
            <h3 class='font-bold text-lg mb-4 border-b pb-2'>แผนการดำเนินการ</h3>
            {$plan_data['displayHTML']}
        </div>
    ";
    
    // --- Prepare DOCX HTML ---
    $docx_content_html = "
        <h1>ข้อมูลหน่วยงาน</h1>
        <table style='width: 100%; border-collapse: collapse;'>
            <tr><td style='width: 150px;'><b>กระทรวง:</b></td><td>{$form_values['ministry']}</td></tr>
            <tr><td><b>กรม:</b></td><td>{$form_values['department']}</td></tr>
            <tr><td><b>หน่วยงาน:</b></td><td>{$form_values['agency']}</td></tr>
            <tr><td><b>ที่อยู่:</b></td><td>{$form_values['address']}, แขวง/ตำบล {$form_values['subdistrict']}</td></tr>
            <tr><td><b>เขต/อำเภอ:</b></td><td>{$form_values['district']}, จังหวัด {$form_values['province']} {$form_values['zipcode']}</td></tr>
            <tr><td><b>ผู้มีอำนาจอนุมัติ:</b></td><td>{$form_values['approver_name']} ({$form_values['approver_position']})</td></tr>
        </table>
        <br/>
        <h1>ข้อมูลโครงการ</h1>
        <p><b>ชื่อโครงการ:</b> {$form_values['project_name']}</p>
        <h3>รายละเอียดโครงการ</h3>
        <p>" . nl2br($project_details_processed) . "</p>
        <h3>วัตถุประสงค์โครงการ</h3>
        <p>" . nl2br($project_objective_processed) . "</p>
        <h3>ขอบเขตของโครงการ</h3>
        <p>" . nl2br($project_scope_processed) . "</p>
        <br/>
        <h1>แผนการดำเนินการ</h1>
        {$plan_data['docxHTML']}
    ";
}
?>
<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document Generator (PHP)</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;500;700&display=swap" rel="stylesheet">
    <!-- Add libraries for DOCX export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script src="https://unpkg.com/html-to-docx@1.8.0/dist/browser/html-to-docx.js"></script>
    <style>
        body { font-family: 'Sarabun', sans-serif; }
        .form-section-header { border-bottom: 2px solid #e5e7eb; padding-bottom: 0.5rem; margin-bottom: 1.5rem; font-size: 1.25rem; font-weight: 700; color: #111827; }
        .output-label { min-width: 150px; font-weight: 500; color: #4b5563; }
        .output-value { border-bottom: 1px dotted #9ca3af; flex-grow: 1; min-height: 24px; }
        .timeline-table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
        .timeline-table th, .timeline-table td { border: 1px solid #ddd; padding: 8px; text-align: left; font-size: 0.875rem; }
        .timeline-table th { background-color: #f2f2f2; font-weight: bold; }
        .milestone { margin-top: 1.5rem; padding-left: 1rem; border-left: 3px solid #6366f1; }
        @media print {
            body * { visibility: hidden; }
            #document-output, #document-output * { visibility: visible; }
            #document-output { position: absolute; left: 0; top: 0; width: 100%; }
            #exportButton { display: none; }
            .timeline-table th, .timeline-table td { font-size: 10px; }
        }
    </style>
</head>
<body class="bg-gray-100 text-gray-800">

    <div class="container mx-auto p-4 sm:p-6 lg:p-8">
        <div class="max-w-4xl mx-auto bg-white rounded-xl shadow-lg p-6 sm:p-8">
            <h1 class="text-2xl sm:text-3xl font-bold text-center text-gray-900 mb-6">แบบฟอร์มสร้างเอกสาร (PHP)</h1>

            <!-- Form Section -->
            <form id="input-form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
                <!-- Agency Information -->
                <h2 class="form-section-header">ข้อมูลหน่วยงาน</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4 mb-6">
                    <div>
                        <label for="ministry" class="block text-sm font-medium text-gray-700">กระทรวง</label>
                        <input type="text" id="ministry" name="ministry" value="<?php echo $form_values['ministry']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="department" class="block text-sm font-medium text-gray-700">กรม</label>
                        <input type="text" id="department" name="department" value="<?php echo $form_values['department']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div class="md:col-span-2">
                        <label for="agency" class="block text-sm font-medium text-gray-700">หน่วยงาน</label>
                        <input type="text" id="agency" name="agency" value="<?php echo $form_values['agency']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                     <div>
                        <label for="address" class="block text-sm font-medium text-gray-700">ที่อยู่</label>
                        <input type="text" id="address" name="address" value="<?php echo $form_values['address']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="subdistrict" class="block text-sm font-medium text-gray-700">แขวง/ตำบล</label>
                        <input type="text" id="subdistrict" name="subdistrict" value="<?php echo $form_values['subdistrict']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="district" class="block text-sm font-medium text-gray-700">เขต/อำเภอ</label>
                        <input type="text" id="district" name="district" value="<?php echo $form_values['district']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="province" class="block text-sm font-medium text-gray-700">จังหวัด</label>
                        <input type="text" id="province" name="province" value="<?php echo $form_values['province']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                     <div class="md:col-span-2">
                        <label for="zipcode" class="block text-sm font-medium text-gray-700">รหัสไปรษณีย์</label>
                        <input type="text" id="zipcode" name="zipcode" value="<?php echo $form_values['zipcode']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="approver_name" class="block text-sm font-medium text-gray-700">ชื่อผู้มีอำนาจอนุมัติ</label>
                        <input type="text" id="approver_name" name="approver_name" value="<?php echo $form_values['approver_name']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="approver_position" class="block text-sm font-medium text-gray-700">ตำแหน่ง</label>
                        <input type="text" id="approver_position" name="approver_position" value="<?php echo $form_values['approver_position']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                </div>

                <!-- Project Information -->
                <h2 class="form-section-header">ข้อมูลโครงการ</h2>
                <div class="space-y-4">
                    <div>
                        <label for="project_name" class="block text-sm font-medium text-gray-700">ชื่อโครงการ</label>
                        <input type="text" id="project_name" name="project_name" value="<?php echo $form_values['project_name']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="start_date" class="block text-sm font-medium text-gray-700">วันเริ่มโครงการ</label>
                        <input type="date" id="start_date" name="start_date" value="<?php echo $form_values['start_date']; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label for="project_details" class="block text-sm font-medium text-gray-700">รายละเอียดโครงการ</label>
                        <textarea id="project_details" name="project_details" rows="5" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"><?php echo $form_values['project_details']; ?></textarea>
                    </div>
                    <div>
                        <label for="project_objective" class="block text-sm font-medium text-gray-700">วัตถุประสงค์โครงการ</label>
                        <textarea id="project_objective" name="project_objective" rows="5" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"><?php echo $form_values['project_objective']; ?></textarea>
                    </div>
                    <div>
                        <label for="project_scope" class="block text-sm font-medium text-gray-700">ขอบเขตของโครงการ</label>
                        <textarea id="project_scope" name="project_scope" rows="7" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"><?php echo $form_values['project_scope']; ?></textarea>
                    </div>
                </div>

                <!-- Generate Button -->
                <div class="mt-8 text-center">
                    <button type="submit" class="w-full sm:w-auto bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-10 rounded-lg shadow-md transition-transform transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                        Generate Document
                    </button>
                </div>
            </form>
        </div>

        <!-- Output Section -->
        <div id="document-output" class="max-w-4xl mx-auto bg-white rounded-xl shadow-lg p-6 sm:p-10 mt-8" style="<?php echo $show_output ? 'display: block;' : 'display: none;'; ?>">
             <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl font-bold">เอกสารข้อมูลโครงการ</h1>
                <button id="exportButton" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded inline-flex items-center transition-colors">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path></svg>
                    <span>Export as .docx</span>
                </button>
            </div>
            
            <div id="output-content" class="space-y-5">
                <?php echo $output_content_html; ?>
            </div>
        </div>
    </div>

    <script>
        // Store the HTML for the DOCX file, passed from PHP
        const docxContentHTML = <?php echo json_encode($docx_content_html); ?>;
        
        // If the output is visible after form submission, scroll to it
        if (<?php echo json_encode($show_output); ?>) {
            document.getElementById('document-output').scrollIntoView({ behavior: 'smooth' });
        }

        // Add event listener for the export button
        document.getElementById('exportButton').addEventListener('click', async function() {
            if (!docxContentHTML) {
                alert('กรุณาสร้างเอกสารก่อน Export');
                return;
            }
            
            const button = this;
            const originalText = button.innerHTML;
            button.disabled = true;
            button.innerHTML = '<span>Generating...</span>';

            try {
                const fullHtml = `<!DOCTYPE html><html><head><meta charset="UTF-8"><style>body { font-family: "Sarabun", sans-serif; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid black; padding: 8px; text-align: left; } h1 { font-size: 20px; } h3 { font-size: 16px; }</style></head><body>${docxContentHTML}</body></html>`;
                
                const blob = await htmlToDocx.asBlob(fullHtml);
                saveAs(blob, 'project-document.docx');
            } catch (error) {
                console.error('Error generating DOCX file:', error);
                alert('เกิดข้อผิดพลาดในการสร้างไฟล์ DOCX');
            } finally {
                button.disabled = false;
                button.innerHTML = originalText;
            }
        });
    </script>
</body>
</html>
