<?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 MergeLabels {

    private $keys = [];
    private $rows = [[]];
    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 multiple merge fields at once.
     * @param array $fields key => value string array
     */
    public function setColumnKeys(array $titles) {
        $this->keys = $titles;
    }

    /**
     * Set multiple merge fields at once, allowing for multiple labels at once.
     * @param array $fields key => value string array
     */
    public function setMergeFields(array $rows) {
        $this->rows = $rows;
    }

    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_values($this->keys));
        foreach ($this->rows as $row) {
            fputcsv($fp, $row);
        }
        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);
    }

    public function getPDFDataURI(): string {
        $pdfpath = $this->toPDFFilePath();
        $pdfString = file_get_contents($pdfpath);
        unlink($pdfpath);
        $pdfBase64 = base64_encode($pdfString);
        return 'data:application/pdf;base64,' . $pdfBase64;
    }

}
