<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonShippingCommon\Components;

use Enlight_Components_Db_Adapter_Pdo_Mysql;
use Shopware\Plugins\ViisonCommon\Components\FileStorage\FileStorage;
use Shopware\Plugins\ViisonShippingCommon\Classes\Types\LabelFile;

class LabelPersister
{
    /**
     * @var FileStorage
     */
    private $fileStorageService;

    /**
     * @var Enlight_Components_Db_Adapter_Pdo_Mysql
     */
    private $db;

    /**
     * @var string
     */
    private $orderTableName;

    public function __construct(
        FileStorage $fileStorageService,
        Enlight_Components_Db_Adapter_Pdo_Mysql $db,
        $orderTableName
    ) {
        $this->fileStorageService = $fileStorageService;
        $this->db = $db;
        $this->orderTableName = $orderTableName;
    }

    /**
     * Persist a label with a given filename.
     *
     * If the label file already exists, the existing label is copied to $targetPath-[ORDERID].pdf first. With the given
     * tracking code the [ORDERID] is retrieved.
     *
     * @param LabelFile $labelFile
     */
    public function persistLabelAndArchiveOldLabel(LabelFile $labelFile)
    {
        if ($this->fileStorageService->doesFileExist($labelFile->getFileName())) {
            $documentId = $this->db->fetchOne(
                sprintf(
                    'SELECT MAX(id)
                    FROM %s
                    WHERE trackingCode = ?',
                    $this->orderTableName
                ),
                [
                    $labelFile->getTrackingCode(),
                ]
            );

            $existingPdf = $this->fileStorageService->readFileContents($labelFile->getFileName());
            $pathInfo = pathinfo($labelFile->getFileName());
            $identifier = $documentId ?: ('orphaned-' . time());
            $newPdfFileName = $pathInfo['filename'] . '-' . $identifier . '.' . $pathInfo['extension'];
            $this->fileStorageService->writeFileContents($newPdfFileName, $existingPdf);
            $this->fileStorageService->deleteFile($labelFile->getFileName());
        }

        $this->fileStorageService->writeFileContents($labelFile->getFileName(), $labelFile->getPdf());
    }
}
