<?php
/**
 * NOTICE OF LICENSE.
 *
 * Copyright 2022 Kosmonaft.dev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 *  @author    Alexandre DEBUSSCHÈRE <alexandre@kosmonaft.dev>
 *  @copyright 2022 - 2023 Kosmonaft.dev
 *  @license   MIT
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

use setasign\Fpdi\Fpdi;
use setasign\Fpdi\PdfParser\StreamReader;

/**
 * Class MRMaxPrintLabelsModuleFrontController
 */
class MRMaxPrintLabelsModuleFrontController extends ModuleFrontController
{

    /** @var bool */
    public $auth = false;

    /** @var bool */
    public $ajax;

    /** @var bool */
    protected $debug;

    /** @var Fpdi */
    protected $fpdi;

    /**
     * @return void
     * @throws SoapFault
     */
    public function display()
    {
        $this->ajax = 1;
        if (Tools::getValue('token') !== Configuration::getGlobalValue('MRMAX_TOKEN')) {
            header('HTTP/1.1 401 Unauthorized', true, 401);
            exit;
        }

        if (!Tools::strlen(Tools::getValue('ids'))) {
            header('HTTP/1.1 400 Bad Request', true, 400);
            exit;
        }

        $order_ids = array_map('trim', explode(',', Tools::getValue('ids')));
        $files = [];
        $base_path = _PS_MODULE_DIR_.'mrmax/download/';

        // Get PDF files
        foreach ($order_ids as $order_id) {
            $order = new Order($order_id);
            if (!Validate::isLoadedObject($order)) {
                continue;
            }

            $shipping_number = array_reduce($order->getShipping(), function ($number, $shipping) {
                if (!MRMaxTools::strlen($number) && MRMaxTools::strlen($shipping['tracking_number'])) {
                    $number = $shipping['tracking_number'];
                }

                return $number;
            }, '');

            $label_path = sprintf('%s%s.pdf', $base_path, $shipping_number);
            if (!file_exists($label_path)) {
                continue;
            }

            $files[] = StreamReader::createByFile($label_path);
        }

        // Generate new PDF
        $this->fpdi = new Fpdi('P', 'mm', 'A4');
        foreach ($files as $file) {
            try {
                $page_count = $this->fpdi->setSourceFile($file);

                for ($page_number = 1; $page_number <= $page_count; $page_number += 1) {
                    $template_id = $this->fpdi->importPage($page_number);
                    $size = $this->fpdi->getTemplateSize($template_id);

                    $this->fpdi->AddPage($size['orientation'], $size);
                    $this->fpdi->useTemplate($template_id);
                }
            } catch (Exception $exception) {
                throw new PrestaShopException($exception->getMessage(), $exception->getCode(), $exception);
            }
        }

        // Display labels PDF
        $this->fpdi->Output('I', 'Etiquettes_MondialRelay_'.date('Y-m-d_H:i:s').'.pdf');
        exit;
    }
}
