<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
echo "STARTING INTO MERGE PROCESS<BR>";
require_once 'classes/TransformDocAdv.inc';
require_once 'classes/CreateDocx.inc';
echo "includes lib files<br>";
//Define the template file you wish to load. There is no need to load the Base Template anymore.
$template = $_SERVER['DOCUMENT_ROOT'] . '\\doctopdf\\SSP-Ind-Trustees-2-to-4-Establish-02-02-15_4_trustees-.docx';
echo $template = $_SERVER['DOCUMENT_ROOT'] . '\\wp-content\\uploads\\templatemerge\\masters\\Deed-cover.docx';
echo "<br>template sample file<br>";
//Create PHPDocx object using the template file defined above.
echo "Before Creating PHPDOCx object<br>";
$docx = new CreateDocxFromTemplate($template);
echo "After Creating PHPDOCx object<br>";
//Define the variable names and values in an array.
$variables = array('Name_of_Fund' => "This is a New FUND", 'T1_Name' => "MY T1", 'T2_name' => "MY T2", 'T3_name' => "MY T3", 'T4_name' => "MY T4", 'M1_Residential_Address_not_PO_Box' => "M1 Address", 'M2_Residential_Address_not_PO_Box' => "M2 Address", 'M3_Residential_Address_not_PO_Box' => "M3 Address", 'M4_Residential_Address_not_PO_Box' => "M4 Address", 'STREET_ADDRESS_WHERE_TRUSTEE_MEETINGS_AR' => "Street address meeting held at ", 'M1_Date_of_Birth_ddmmyy' => "01/12/1989", 'M2_Date_of_Birth_ddmmyy' => "02/12/1989", 'M3_Date_of_Birth_ddmmyy' => "03/12/1989", 'M4_Date_of_Birth_ddmmyy' => "04/12/1989", 'M1_Tax_File_Number' => "111111111", 'M2_Tax_File_Number' => "222222222", 'M3_Tax_File_Number' => "333333333", 'M4_Tax_File_Number' => "444444444");
//$variables = array('FUNDNAME' => 'The Test Family Super Fund', 'COMPANYNAME' => 'ABC PTY LTD', 'ACN' => '111 222 333', 'Address_Of_Registered_Office' => '123 Happy Street, Happyville, Victoria, 3000');
//Load the array into the PHPDocx object so that the variable values are inserted into the document template.
$docx->replaceVariableByText($variables);
//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 = 'output\\Deed-cover-ins';
//Define the base directory
$baseDirectory = 'D:\\inetpub\\app\\wwwroot\\wp-content\\plugins\\templatemerge\\phpdocx-v4\\';
//Create the document and save it.
$docx->createDocx($outputWordFileNameAndPath);
//Conver the document to PDF and save.
$docx->transformDocxUsingMSWord($baseDirectory . $outputWordFileNameAndPath . '.docx', $baseDirectory . $outputWordFileNameAndPath . '.pdf');
exit;
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;
}