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

    private $labeltype = "";
    private $mergedata = [];
    private $machine = null;

    public function __construct(string $labeltype, Machine $machine) {
        $this->labeltype = $labeltype;

        if (!file_exists($this->getLabelPath())) {
            throw new InvalidArgumentException("Label " . $this->getLabelPath() . " does not exist.");
        }

        $this->machine = $machine;
    }

    public static function getLabelTemplates(): array {
        global $SETTINGS;
        return $SETTINGS["labels"]["templates"];
    }

    public function getLabelPath(): string {
        return __DIR__ . "/../print/templates/$this->labeltype.glabels";
    }

    public function servePDF() {
        $this->buildMergeData();
        $label = new Label($this->getLabelPath(), "$this->labeltype (ID " . $this->mergedata['id'] . ")");

        $label->setFields($this->mergedata);
        $label->servePDF();
    }

    /**
     * https://stackoverflow.com/a/14167216
     */
    public static function formatPhoneNumber($phoneNumber) {
        $phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);

        if (strlen($phoneNumber) > 10) {
            $countryCode = substr($phoneNumber, 0, strlen($phoneNumber) - 10);
            $areaCode = substr($phoneNumber, -10, 3);
            $nextThree = substr($phoneNumber, -7, 3);
            $lastFour = substr($phoneNumber, -4, 4);

            $phoneNumber = '+' . $countryCode . ' (' . $areaCode . ') ' . $nextThree . '-' . $lastFour;
        } else if (strlen($phoneNumber) == 10) {
            $areaCode = substr($phoneNumber, 0, 3);
            $nextThree = substr($phoneNumber, 3, 3);
            $lastFour = substr($phoneNumber, 6, 4);

            $phoneNumber = '(' . $areaCode . ') ' . $nextThree . '-' . $lastFour;
        } else if (strlen($phoneNumber) == 7) {
            $nextThree = substr($phoneNumber, 0, 3);
            $lastFour = substr($phoneNumber, 3, 4);

            $phoneNumber = $nextThree . '-' . $lastFour;
        }

        return $phoneNumber;
    }

    private function buildMergeData() {
        global $SETTINGS;

        $this->mergedata = [
            "id" => $this->machine->getID(),
            "price" => number_format($this->machine->getPrice(), 2),
            "devicetype" => $this->machine->getTypeLabel(),
            "devicetype_lowercase" => strtolower($this->machine->getTypeLabel()),
            "serial" => $this->machine->getSerial(),
            "model" => $this->machine->getModel(),
            "os" => $this->machine->getOS(),
            "manufacturer" => $this->machine->getManufacturer(),
            "publicnotes" => $this->machine->getPublicNotes(),
            "privatenotes" => $this->machine->getPrivateNotes(),
            "date" => date($SETTINGS["date_format"]),
            "date_time" => date($SETTINGS["datetime_format"]),
            "clientid" => "",
            "clientname" => "",
            "clientphone" => "",
            "clientphoneformatted" => "",
            "clientemail" => "",
            "clientbillingaddress" => "",
            "clientshippingaddress" => "",
            "clientpublicnotes" => "",
            "clientprivatenotes" => ""
        ];

        foreach ($SETTINGS["labels"]["fields"] as $id => $val) {
            $this->mergedata[$id] = str_replace("{{id}}", $this->machine->getID(), $val);
        }

        if (!empty($this->machine->getClientID())) {
            $client = Clients::getClient($this->machine->getClientID());
            $this->mergedata["clientid"] = $client->getID();
            $this->mergedata["clientname"] = $client->getName();
            $this->mergedata["clientphone"] = $client->getPhone();
            $this->mergedata["clientphoneformatted"] = $this->formatPhoneNumber($client->getPhone());
            $this->mergedata["clientemail"] = $client->getEmail();
            $this->mergedata["clientbillingaddress"] = $client->getBillingAddress();
            $this->mergedata["clientshippingaddress"] = $client->getMailingAddress();
            $this->mergedata["clientpublicnotes"] = $client->getPublicNotes();
            $this->mergedata["clientprivatenotes"] = $client->getPrivateNotes();
        }
    }

}
