<?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 Exception;
use Shopware\Models\Shop\Shop;
use Shopware\Plugins\ViisonCommon\Classes\Installation\SQLHelper;
use Shopware\Plugins\ViisonCommon\Classes\PluginConfigImport\PluginConfigReader;
use Shopware\Plugins\ViisonShippingCommon\Classes\PluginInfo;

class ShippingPluginConfigReaderService extends PluginConfigReader
{
    /**
     * @var SQLHelper
     */
    private $sqlHelper;

    /**
     * ShippingPluginConfigImporter constructor.
     *
     * @param \Zend_Db_Adapter_Abstract $db
     */
    public function __construct(\Zend_Db_Adapter_Abstract $db)
    {
        $this->sqlHelper = new SQLHelper($db);
    }

    /**
     * Function to save the config values to the database
     *
     * @param string $configPath
     * @param Shop $shop
     * @param PluginInfo $pluginInfo
     * @throws Exception
     */
    public function importShippingConfigFormFile($configPath, Shop $shop, PluginInfo $pluginInfo)
    {
        $configuration = $this->getConfigFileData($configPath)['configuration'];
        if (!$configuration) {
            return;
        }

        try {
            $this->sqlHelper->insertOrUpdateUniqueRow(
                $pluginInfo->getConfigTableName(),
                [
                    'shopId' => $shop->getId(),
                ],
                $configuration
            );
        } catch (Exception $exception) {
            throw new Exception(
                sprintf(
                    'The configuration file (%s) could not be set as %s\'s configuration. (Could not be read into the database.)',
                    $configPath,
                    $pluginInfo->getPluginName()
                ),
                0,
                $exception
            );
        }
    }
}
