<?php

//path to  the CreateDocx class within your PHPDocX installation
require_once '../../../classes/CreateDocx.inc';
$docx = new CreateDocxFromTemplate('../../files/TemplateHTML.docx');
$docx->replaceVariableByHTML('ADDRESS', 'inline', '<p style="font-family: verdana; font-size: 11px">C/ Matías Turrión 24, Madrid 28043 <b>Spain</b></p>', array('isFile' => false, 'parseDivsAsPs' => true, 'downloadImages' => false));
$docx->replaceVariableByHTML('CHUNK_1', 'block', 'http://www.2mdc.com/PHPDOCX/example.html', array('isFile' => true, 'parseDivsAsPs' => true, 'filter' => '#capa_bg_bottom', 'downloadImages' => true));
$docx->replaceVariableByHTML('CHUNK_2', 'block', 'http://www.2mdc.com/PHPDOCX/example.html', array('isFile' => true, 'parseDivsAsPs' => false, 'filter' => '#lateral', 'downloadImages' => true));
$docx->createDocx('example_replaceTemplateVariableByHTML_1');
function cron_tpl_merge_process($tpls, $entry, $type = "", $invoice_number = "")
{
    echo "inside merge process.<br/>";
    require_once "D:\\inetpub\\app\\wwwroot\\wp-content\\plugins\\templatemerge\\phpdocx-v4\\classes\\TransformDocAdv.inc";
    require_once "D:\\inetpub\\app\\wwwroot\\wp-content\\plugins\\templatemerge\\phpdocx-v4\\classes\\CreateDocx.inc";
    $final_doc_url = "";
    $formdetail = RGFormsModel::get_form($entry["form_id"]);
    $new_xml = array();
    $unique_number = date('ymdhis') . "-" . $entry["id"];
    $n = str_replace('+', '_', urlencode($formdetail->title)) . ($type != "" ? "_" . $type : "") . "_" . $unique_number . '-cron.docx';
    if ($type == "Invoice" && $invoice_number == "") {
        $invoice_number = generate_invoice_number();
    }
    $i = 1;
    foreach ($tpls as $tpl) {
        $file = $tpl['file'];
        $value = $tpl['values'];
        $value["Invoice_number"] = $invoice_number;
        if (!empty($file['dir_path']) && !empty($file['filepath'])) {
            $cookie_file_path = $file['filepath'];
            /*echo '<br/>Cookie path: '.$cookie_file_path;
            		if (!file_exists($cookie_file_path)) {
                           echo 'file does not exist';
                       }
                       else {
                       	echo 'file exists';
                       }*/
            //Create PHPDocx object using the template file defined above.
            $docx = new CreateDocxFromTemplate($cookie_file_path);
            $variables = array();
            $variables_html = array();
            foreach ($value as $k => $v) {
                $k_val = explode("-", $k);
                $e_val = array("SIGNED", "PRESENCE", "LengthContent");
                if (count($k_val) > 1 && in_array($k_val[1], $e_val)) {
                    $variables_html[$k] = $v;
                } else {
                    $variables[$k] = $v;
                }
            }
            //Load the array into the PHPDocx object so that the variable values are inserted into the document template.
            $docx->replaceVariableByText($variables);
            if (!empty($variables_html)) {
                foreach ($variables_html as $hk => $hv) {
                    if (!empty($hv)) {
                        $docx->replaceVariableByHTML($hk, 'inline', $hv, array());
                    } else {
                        $docx->replaceVariableByText(array($hk => ""));
                    }
                }
            }
            //echo '<br/>About to check if file exists...';
            if (!file_exists($file['dir_path'] . '/doc/temps/cron/')) {
                mkdir($file['dir_path'] . '/doc/temps/cron/', 0777, true);
            }
            //Define the output location and name of the document to be saved (e.g. Saves in 'Output' folder relative to the location
            //Of this script, and the name of the file will be 'testDeed'.
            $outputWordFileNameAndPath = $file['dir_path'] . '/doc/temps/cron/' . date('ymdhis') . $i . '-cron';
            $newfile = $outputWordFileNameAndPath . ".docx";
            $newfile_pdf = $outputWordFileNameAndPath . ".pdf";
            //Define the base directory
            $baseDirectory = '';
            //Create the document and save it.
            $docx->createDocx($outputWordFileNameAndPath);
            //Conver the document to PDF and save.
            $docx->transformDocxUsingMSWord($baseDirectory . $outputWordFileNameAndPath . '.docx', $baseDirectory . $outputWordFileNameAndPath . '.pdf');
            if (file_exists($newfile_pdf)) {
                //chmod($newfile_pdf, 0777);
                $new_xml['temp_file'][] = $newfile_pdf;
                //chmod($newfile_pdf, 0777);
            }
        }
        $i++;
    }
    $c = count($new_xml['temp_file']);
    if (!file_exists($file['dir_path'] . '/doc/cron/')) {
        mkdir($file['dir_path'] . '/doc/cron/', 0777, true);
    }
    $final_doc = $file['dir_path'] . '/doc/cron/' . $n;
    $final_doc = str_replace('.docx', '.pdf', $final_doc);
    $final_doc = str_replace("/", "\\", $final_doc);
    $final_doc = str_replace("\\", "\\\\", $final_doc);
    $final_doc_url = $file['dir_url'] . '/doc/cron/' . $n;
    $final_doc_url = str_replace('.docx', '.pdf', $final_doc_url);
    if ($c > 1) {
        $alldoc = $new_xml['temp_file'];
        cron_mergerAllPdf($alldoc, $final_doc);
    } else {
        copy($new_xml['temp_file'][0], $final_doc);
    }
    if (file_exists($final_doc)) {
        chmod($final_doc, 0777);
        foreach ($new_xml['temp_file'] as $y) {
            if (file_exists(ConvertDirectoryPath($y))) {
                chmod(ConvertDirectoryPath($y), 0777);
            }
            @unlink(ConvertDirectoryPath($y));
            $y = str_replace(".pdf", ".docx", $y);
            @unlink(ConvertDirectoryPath($y));
        }
        cron_SaveToDB($final_doc_url, $final_doc, $entry["id"], $type, $invoice_number);
        return $final_doc_url;
    }
    foreach ($new_xml['temp_file'] as $y) {
        if (file_exists(ConvertDirectoryPath($y))) {
            chmod(ConvertDirectoryPath($y), 0777);
        }
        @unlink(ConvertDirectoryPath($y));
        $y = str_replace(".pdf", ".docx", $y);
        @unlink(ConvertDirectoryPath($y));
    }
    return "";
}
function tpl_merge_process($tpls, $entry, $type = "")
{
    /* require_once 'PHPWord.php';
        require_once 'phpdocx/classes/MultiMerge.inc';
        //require_once 'phpdocx/classes/CreateDocx.inc';
    	*/
    require_once "phpdocx-v4/classes/TransformDocAdv.inc";
    require_once "phpdocx-v4/classes/CreateDocx.inc";
    $final_doc_url = "";
    $formdetail = RGFormsModel::get_form($entry["form_id"]);
    $unique_number = date('ymdhis');
    $n = str_replace('+', '_', urlencode($formdetail->title)) . ($type != "" ? "_" . $type : "") . "_" . $unique_number . '.docx';
    $invoice_number = "";
    if ($type == "Invoice") {
        $invoice_number = generate_invoice_number();
    }
    $i = 1;
    foreach ($tpls as $tpl) {
        $file = $tpl['file'];
        $value = $tpl['values'];
        $value["Invoice_number"] = $invoice_number;
        if (!empty($file['dir_path']) && !empty($file['filepath'])) {
            $cookie_file_path = $file['filepath'];
            //Create PHPDocx object using the template file defined above.
            $docx = new CreateDocxFromTemplate($cookie_file_path);
            $variables = array();
            $variables_html = array();
            foreach ($value as $k => $v) {
                $k_val = explode("-", $k);
                $e_val = array("SIGNED", "PRESENCE", "LengthContent");
                if (count($k_val) > 1 && in_array($k_val[1], $e_val)) {
                    $variables_html[$k] = $v;
                } else {
                    $variables[$k] = $v;
                }
            }
            // printp($variables_html);exit;
            //Load the array into the PHPDocx object so that the variable values are inserted into the document template.
            $docx->replaceVariableByText($variables);
            if (!empty($variables_html)) {
                foreach ($variables_html as $hk => $hv) {
                    if (!empty($hv)) {
                        $docx->replaceVariableByHTML($hk, 'inline', $hv, array());
                    } else {
                        $docx->replaceVariableByText(array($hk => ""));
                    }
                }
            }
            /*$new_xml['xml'][] = $document->getTemplateXML();
                    $new_xml['file'][] =  $document->getTempFileName();
                    if(file_exists($document->getTempFileName())){
              	chmod($document->getTempFileName(), 0777);
              }*/
            if (!file_exists($file['dir_path'] . '/doc/temps/cron/')) {
                mkdir($file['dir_path'] . '/doc/temps/cron/', 0777, true);
            }
            //Define the output location and name of the document to be saved (e.g. Saves in 'Output' folder relative to the location
            //Of this script, and the name of the file will be 'testDeed'.
            $outputWordFileNameAndPath = $file['dir_path'] . '/doc/temps/cron/' . date('ymdhis') . $i . '-cron';
            $newfile = $outputWordFileNameAndPath . ".docx";
            $newfile_pdf = $outputWordFileNameAndPath . ".pdf";
            //Define the base directory
            $baseDirectory = '';
            //Create the document and save it.
            $docx->createDocx($outputWordFileNameAndPath);
            //Conver the document to PDF and save.
            $docx->transformDocxUsingMSWord($baseDirectory . $outputWordFileNameAndPath . '.docx', $baseDirectory . $outputWordFileNameAndPath . '.pdf');
            if (file_exists($newfile_pdf)) {
                chmod($newfile_pdf, 0777);
                $new_xml['temp_file'][] = $newfile_pdf;
                chmod($newfile_pdf, 0777);
            }
        }
        $i++;
        /*$document->save($newfile);
              	
              	if(file_exists($newfile)){
        		chmod($newfile, 0777);
        		$newfile = converttoPDF(str_replace("/","\\",$newfile));
                      $new_xml['temp_file'][] = $newfile;
            	chmod($newfile, 0777);
            }*/
    }
    $c = count($new_xml['temp_file']);
    $final_doc = $file['dir_path'] . '/doc/' . $n;
    $final_doc = str_replace('.docx', '.pdf', $final_doc);
    $final_doc = str_replace("/", "\\", $final_doc);
    $final_doc = str_replace("\\", "\\\\", $final_doc);
    $final_doc_url = $file['dir_url'] . '/doc/' . $n;
    $final_doc_url = str_replace('.docx', '.pdf', $final_doc_url);
    if ($c > 1) {
        $alldoc = $new_xml['temp_file'];
        mergerAllPdf($alldoc, $final_doc);
    } else {
        copy($new_xml['temp_file'][0], $final_doc);
    }
    if (file_exists($final_doc)) {
        chmod($final_doc, 0777);
        if ($type == "") {
            SaveDocToDb($entry, $final_doc_url, $final_doc, $unique_number);
        } else {
            //printp($invoice_number);
            UpdateDocToDb($entry, $final_doc_url, $final_doc, $type, $invoice_number);
        }
        foreach ($new_xml['temp_file'] as $y) {
            if (file_exists(ConvertDirectoryPath($y))) {
                chmod(ConvertDirectoryPath($y), 0777);
            }
            @unlink(ConvertDirectoryPath($y));
            $y = str_replace(".pdf", ".docx", $y);
            @unlink(ConvertDirectoryPath($y));
        }
        return $final_doc_url;
    }
    foreach ($new_xml['temp_file'] as $y) {
        if (file_exists(ConvertDirectoryPath($y))) {
            chmod(ConvertDirectoryPath($y), 0777);
        }
        @unlink(ConvertDirectoryPath($y));
        $y = str_replace(".pdf", ".docx", $y);
        @unlink(ConvertDirectoryPath($y));
    }
    return "";
    //	exit;
}