<?php
/**
 * Created by PhpStorm.
 * User: Santiago
 * Date: 8/1/15
 * Time: 11:55
 */

class Parser_Word{

    public $_vars = Array();
    public $_template = "";

    public function __construct($template){
        $this->_template = $template;
    }

    public function getTemplate(){
        return $this->_template;
    }

    public function getVars(){
        return $this->_vars;
    }

    public function addVar($key,$value){
        $this->_vars[$key] = html_entity_decode($value);
    }

    public function parseTemplate($ruta_salida = null){

        $phpword = new PHPWord();

        $ruta = DOCROOT .$this->getTemplate();

        if($ruta_salida){
            $savelink = DOCROOT . $ruta_salida;
        }
        else{
            $savelink = DOCROOT . 'docs/contratos/'.uniqid('output_').'.docx';
        }

        //Intento cargar el template con la ruta especificada en el controlador
        try{
            $templateword = $phpword->loadTemplate($ruta);
        }catch(Exception $e){
            \Log::error($e->getMessage());
        }

        //Seteo todas las variables del template
        foreach($this->getVars() as $key => $value){
            $templateword->setValue($key, $value);
        }

        //Intento salvar el template rellenado
        try{
            $templateword->save($savelink);
        }catch(Exception $e){
            \Log::error($e->getMessage());
        }

        return $savelink;
    }
}