<?php

/*
 * Copyright 2020 Netsyms Technologies.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

class Label {

    private $fields = [];
    private $labelpath = "";
    private $title = "label";

    /**
     *
     * @param string $labelpath Path to the glabels 3 label template.
     */
    public function __construct(string $labelpath, string $labeltitle = "label") {
        if (file_exists($labelpath)) {
            $this->labelpath = $labelpath;
        } else {
            throw new InvalidArgumentException("Label $labelpath does not exist.");
        }
        $this->title = $labeltitle;
    }

    /**
     * Set the value of a mail merge field.
     * @param string $name
     * @param string $value
     */
    public function setField(string $name, string $value) {
        $this->fields[$name] = $value;
    }

    /**
     * Set multiple mail merge fields at once.
     * @param array $fields key => value string array
     */
    public function setFields(array $fields) {
        foreach ($fields as $name => $value) {
            $this->fields[$name] = $value;
        }
    }

    public function setTitle(string $title) {
        $this->title = $title;
    }

    private function writeCSVFileAndReturnFilePath(): string {
        $csvfile = tempnam(sys_get_temp_dir(), "GLABELS_MERGE_CSV");

        $fp = fopen($csvfile, 'w');
        fputcsv($fp, array_keys($this->fields));
        fputcsv($fp, array_values($this->fields));
        fclose($fp);

        return $csvfile;
    }

    private function toPDFFilePath() {
        $csvfile = $this->writeCSVFileAndReturnFilePath();
        $pdffile = tempnam(sys_get_temp_dir(), "GLABELS_MERGE_PDF");

        shell_exec("glabels-3-batch --input=$csvfile --output=$pdffile " . $this->labelpath);

        unlink($csvfile);

        return $pdffile;
    }

    public function servePDF() {
        $pdfpath = $this->toPDFFilePath();
        $pdfsize = filesize($pdfpath);

        header('Content-Type: application/pdf');
        header("Content-Length: $pdfsize");
        header("Content-Disposition: inline; filename=\"$this->title\"");
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');

        echo file_get_contents($pdfpath);
        unlink($pdfpath);
    }

}
