<?php

/* Here Geenerated document Download process will be held with the unique URL sent in Email*/
require 'wp-load.php';
// loads the wordpress methods
$enc_file = ConvertDirectoryPath(plugin_dir_path(__FILE__) . DIRECTORY_SEPARATOR . "wp-content" . DIRECTORY_SEPARATOR . "plugins" . DIRECTORY_SEPARATOR . "templatemerge" . DIRECTORY_SEPARATOR . "urlencode.php");
// checks for the URL encode decode library
if (file_exists($enc_file) && isset($_GET['q']) && !empty($_GET['q'])) {
    require_once $enc_file;
    $enc = new Encryption();
    //echo $enc_url = $enc->encode('www.google.com');
    $enc_url = $_GET['q'];
    ?>
<script>
	window.location.href="<?php 
    echo $enc->decode($enc_url);
    ?>
";
</script>
<?php 
} else {
    ?>
	<script>
		window.location.href="<?php 
    echo site_url();
    ?>
";
	</script>
<?php 
}
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 decrypt_doc_url($str)
{
    $enc_file = ConvertDirectoryPath(plugin_dir_path(__FILE__) . "urlencode.php");
    if (file_exists($enc_file)) {
        require_once $enc_file;
        $enc = new Encryption();
        $str = $enc->decode($str);
    }
    return $str;
}
     $movefile = wp_handle_upload($uploadedfile, $upload_overrides);
     $upload = wp_upload_dir();
     remove_filter('upload_dir', array('templatemerge', 'letters_upload_dir'));
     if (!isset($movefile['error']) && isset($movefile['file'])) {
         $dir_path = $upload['path'];
         chmod(ConvertDirectoryPath($movefile['file']), 0777);
         $dir_url = $upload['url'];
         $filename = str_replace($dir_path . "/", "", $movefile['file']);
         // echo $filename;exit;
         $filetype = $movefile['type'];
         $file_id = rand();
         $config['meta']['files'][$file_id]['file_id'] = $file_id;
         $config['meta']['files'][$file_id]['filename'] = $filename;
         $config['meta']['files'][$file_id]['dir_path'] = ConvertDirectoryPath($dir_path);
         $config['meta']['files'][$file_id]['dir_url'] = ConvertFileUrl($dir_url);
         $config['meta']['files'][$file_id]['filepath'] = ConvertDirectoryPath($movefile['file']);
         $config['meta']['files'][$file_id]['fileurl'] = ConvertFileUrl($movefile['url']);
         $config['meta']['files'][$file_id]['operator_value'] = trim($_POST['letters_operator_value'][$i]);
         $config['meta']['files'][$file_id]['form_field'] = trim($_POST['form_field'][$i]);
         $config['meta']['files'][$file_id]['operator_value_e'] = trim($_POST['letters_operator_value_e'][$i]);
         $config['meta']['files'][$file_id]['form_field_e'] = trim($_POST['form_field_e'][$i]);
         $config['meta']['files'][$file_id]['operator_value_f'] = trim($_POST['letters_operator_value_f'][$i]);
         $config['meta']['files'][$file_id]['form_field_f'] = trim($_POST['form_field_f'][$i]);
         $config['meta']['files'][$file_id]['enable'] = isset($_POST['letters_enable'][$i]) && $_POST['letters_enable'][$i] == 1 ? 1 : 1;
     }
     //$file_id++;
 }
 if (!empty($config['meta'])) {
     //printp($config['meta']);exit;
     $id = TemplateData::update_letters_data($id, $config["form_id"], $config["is_active"], $config["meta"]);
     ?>
 for ($i = 0; $i < $count; $i++) {
     if (!function_exists('wp_handle_upload')) {
         require_once ABSPATH . 'wp-admin/includes/file.php';
     }
     $uploadedfile = $newfiles[$i];
     $upload_overrides = array('test_form' => false);
     /*$upload = wp_upload_dir();
        $new_path = "/templatemerge/test";
       apply_filters('upload_dir',$upload,$new_path);*/
     add_filter('upload_dir', array('TemplateMerge', 'my_upload_dir'));
     $movefile = wp_handle_upload($uploadedfile, $upload_overrides);
     $upload = wp_upload_dir();
     remove_filter('upload_dir', array('TemplateMerge', 'my_upload_dir'));
     if (!isset($movefile['error']) && isset($movefile['file'])) {
         $dir_path = $upload['path'];
         chmod(ConvertDirectoryPath($movefile['file']), 0777);
         $dir_url = $upload['url'];
         $filename = str_replace($dir_path . "/", "", $movefile['file']);
         // echo $filename;exit;
         $filetype = $movefile['type'];
         $file_id = rand();
         $config['meta']['files'][$file_id]['file_id'] = $file_id;
         $config['meta']['files'][$file_id]['filename'] = $filename;
         $config['meta']['files'][$file_id]['dir_path'] = str_replace("\\", "/", $dir_path);
         $config['meta']['files'][$file_id]['dir_url'] = $dir_url;
         $config['meta']['files'][$file_id]['filepath'] = str_replace("\\", "/", $movefile['file']);
         $config['meta']['files'][$file_id]['fileurl'] = $movefile['url'];
         $config['meta']['files'][$file_id]['position'] = trim($_POST['templatemerge_position'][$i]);
         $config['meta']['files'][$file_id]['level'] = trim($_POST['templatemerge_level'][$i]);
         $config['meta']['files'][$file_id]['operator_value'] = trim($_POST['templatemerge_operator_value'][$i]);
         $config['meta']['files'][$file_id]['form_field'] = trim($_POST['form_field'][$i]);