<?php
/**
 * @package CleverOgre
 * @subpackage woocommerce-download-template
 * @version 0.1.0
 * @since 0.1.0
 */

namespace WooCommerce\DownloadTemplate;

defined('ABSPATH') || exit;

class Template {
    use Singleton;

    public function __construct() { }

    private function load():bool {
        return class_exists('\PhpOffice\PhpWord\Settings');
    }

    public function apply(string $path, array $args = [], array $values = []):string {
        if (!$this->load()) return $path;

        if (empty($values)) $values = Values::instance()->get($args);

        $path_parts = pathinfo($path);
        $filename = $path_parts['filename'];
        if (is_array($args) && !empty($args)) {
            foreach ($args as $key => $value) {
                if (is_string($value) && !empty($value)) $filename .= '_' . sanitize_title($value);
            }
        }
        $tmp_path = sprintf('%s/%s.%s', sys_get_temp_dir(), $filename, $path_parts['extension']);

        switch ($path_parts['extension']) {
            case 'xls':
            case 'xlsx':
            case 'ods':
            case 'csv':
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
                $worksheet = $spreadsheet->getActiveSheet();

                foreach ($worksheet->getRowIterator() as $row) {
                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(true);
                    foreach ($cellIterator as $cell) {
                        $value = $cell->getValue();
                        if (strpos($value, '${') === false) continue;
                        if (preg_match_all('/\${([^}]+)}/', $value, $matches) === false) continue;
                        foreach ($matches[1] as $key) {
                            if (!isset($values[$key])) continue;
                            $value = str_replace('${'.$key.'}', $values[$key], $value);
                        }
                        $cell->setValue($value);
                    }
                }

                $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, ucfirst(strtolower(trim($path_parts['extension']))));
                $writer->save($tmp_path);
                break;
            case 'doc':
            case 'docx':
            case 'odf':
            case 'rtf':
                $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor($path);
                $templateProcessor->setValues($values);
                $templateProcessor->saveAs($tmp_path);
                break;
        }

        return $tmp_path;
    }

    public function apply_password(string $path, string $password = '') {
        if (!$this->load()) return $path;

        if (empty($password)) $password = $this->get_default_password();

        $path_parts = pathinfo($path);
        $tmp_path = sprintf('%s/%s_p.%s', sys_get_temp_dir(), $path_parts['filename'], $path_parts['extension']);

        $phpWord = \PhpOffice\PhpWord\IOFactory::load($path);
        $documentProtection = $phpWord->getSettings()->getDocumentProtection();
        $documentProtection->setEditing(\PhpOffice\PhpWord\SimpleType\DocProtect::READ_ONLY);
        $documentProtection->setPassword($password);
        $phpWord->save($tmp_path);

        return $tmp_path;
    }
    private function get_default_password() {
        return apply_filters('wc_download_template_default_password', date('Ymd'));
    }

}
