<?php

namespace idoit\Module\QCW;

use idoit\Component\Upload\UploadType;
use isys_module_quick_configuration_wizard;
use Symfony\Component\Filesystem\Filesystem;
use Throwable;

/**
 * i-doit QCW profile upload type.
 *
 * @package     Modules
 * @subpackage  QCW
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class ProfileUploadType extends UploadType
{
    /**
     *
     */
    public function __construct()
    {
        $this
            ->setUploadDirectory('/temp/')
            ->setValidExtensions(['xml'])
            ->setSizeLimit(1048576) // 1 MB
            ->setCallbackAfterUpload([self::class, 'uploadXml']);
    }

    /**
     * @param string $filePath
     * @return array
     */
    public static function uploadXml(string $filePath): array
    {
        $uploadDir = isys_module_quick_configuration_wizard::getProfilePath();

        try {
            $fileName = basename($filePath);

            // Move from 'temp' to the profile directory.
            (new Filesystem())->rename(
                $filePath,
                $uploadDir . $fileName,
                true,
            );

            return [
                'success' => true,
                'data'    => $fileName,
                'message' => '',
            ];
        } catch (Throwable $e) {
            return [
                'success' => false,
                'data'    => $fileName,
                'message' => $e->getMessage(),
            ];
        }
    }
}
