<?php
namespace app\components;

use Yii;
use yii\base\Component;
use yii\helpers\FileHelper;

class Templater extends Component
{
    public $templatePath = '@app/templates/protocol.docx';
    private $content;

    public function process(array $data, $type = 'protocol', $filepath = false)
    {
        $filename = $this->createTempFile($filepath, $type);

        $file = new \ZipArchive();
        if ($file->open($filename) !== true) {
            throw new \Exception('Cannot open docx file');
        }

        $this->content = $file->getFromName('word/document.xml');
        $file->addFromString(
            'word/document.xml',
            $this->replace($this->content, $data)
        );

        $file->close();

        return $filename;
    }

    private function replace($string, array $params = [])
    {
        foreach ($params as $index => $param) {
            $string = str_ireplace($index, $param, $string);
        }
        return $string;
    }

    private function createTempFile($filepath = false, $type)
    {
        $path = $filepath ?: Yii::getAlias('@runtime/tmp');
        FileHelper::createDirectory($path);

        $filename = "{$type}.docx";
        $newFilePath = $path . '/' . $filename;

        $tplPath = Yii::getAlias($this->templatePath);

        if (!file_exists($tplPath)) {
            throw new \Exception("Template not found: " . $tplPath);
        }

        copy($tplPath, $newFilePath);

        return $newFilePath;
    }
}