<?php
session_start();
require_once __DIR__ . '/vendor/autoload.php';


use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Settings;

$data = json_decode(file_get_contents('php://input'), true);
if ($data && isset($_SESSION['username']) && isset($_SESSION['password']) && $data['Action'] == "SANG-HR") {
    // Hàm thực hiện tìm kiếm và thay thế văn bản trong đối tượng PhpWord
    function findAndReplaceText($phpWord, $search, $replace)
    {
        foreach ($phpWord->getSections() as $section) {
            foreach ($section->getElements() as $element) {
                if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    foreach ($element->getElements() as $text) {
                        if ($text instanceof \PhpOffice\PhpWord\Element\Text) {
                            $textValue = $text->getText();
                            $newText = str_replace($search, $replace, $textValue);
                            $text->setText($newText);
                        }
                    }
                }
            }
        }
    }
    if ($data['Type'] == "Offer") {
        $originalFilePath =  './form/Offer Letter.docx';

        // Tên mới cho file Word sau khi chỉnh sửa
        $newFileName = './Temp/Offer Letter.pdf';


        // Load file Word
        $phpWord = IOFactory::load($originalFilePath);

        findAndReplaceText($phpWord, '[FULL NAME]', $data['hoten']);

        $mpdf = new \Mpdf\Mpdf();
        $htmlWriter = IOFactory::createWriter($phpWord, 'HTML');
        ob_start();
        $htmlWriter->save('php://output');
        $html = ob_get_contents();
        ob_end_clean();

        $mpdf->WriteHTML($html);
        $mpdf->Output($newFileName, 'F');

        

        // Lưu file Word với tên mới
        //$newWordFileName = './Temp/sang1.docx';
        //$writer = IOFactory::createWriter($phpWord, 'Word2007');
        //$writer->save($newWordFileName);
    }
} else {
    // Trả về lỗi
    header('location:../template/index.php?mod=error');   //redirect đến trang error.php
    exit();
}
