<?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/.
 */

require_once __DIR__ . "/../required.php";

redirectIfNotLoggedIn();
$user = new User($_SESSION['uid']);
if (!$user->hasPermission("MACHINEMANAGER_VIEW")) {
    die("No permission.");
}

if (!empty($_GET["id"])) {
    $machineid = $_GET["id"];
} else if (!empty($_GET["arg"])) {
    $machineid = $_GET["arg"];
}
if (!Machine::exists($machineid)) {
    exit("No such machine.");
}

$labeltype = array_keys($SETTINGS["labels"]["templates"])[0];

if (array_key_exists($VARS["labeltype"], $SETTINGS["labels"]["templates"])) {
    $labeltype = $VARS["labeltype"];
}

$machine = new Machine($machineid);

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

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

/**
 * https://stackoverflow.com/a/14167216
 */
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;
}

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

$csvfile = tempnam("/tmp", "MCHMGR_CSV");

$fp = fopen($csvfile, 'w');
fputcsv($fp, array_keys($mergedata));
fputcsv($fp, array_values($mergedata));
fclose($fp);

$pdffile = tempnam("/tmp", "MCHMGR_PDF");

shell_exec("glabels-3-batch --input=$csvfile --output=$pdffile " . __DIR__ . "/templates/$labeltype.glabels");

header('Content-type: application/pdf');
header("Content-Disposition: inline; filename=\"$labeltype (ID $mergedata[id])\"");
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

echo file_get_contents($pdffile);

unlink($csvfile);
unlink($pdffile);
