<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model\Config\Backend;

use Magento\Config\Model\Config\Backend\Encrypted;
use Simplyin\Payment\Block\Adminhtml\System\Config\Field\ApiKeyMasked;

/**
 * Encrypted API-key backend model that recognises the masked display placeholder.
 *
 * {@see ApiKeyMasked} renders the saved key as a mask (e.g. ••••••••h8). If that placeholder is
 * submitted unchanged it must NOT be re-encrypted as the new key — the stored (encrypted) value is
 * kept instead. Any real value (no mask character) is encrypted by the parent as usual.
 */
class ApiKeyEncrypted extends Encrypted
{
    /**
     * Keep the stored key when the masked placeholder is submitted unchanged; encrypt any real value.
     *
     * @return $this
     */
    public function beforeSave()
    {
        $value = (string)$this->getValue();
        if ($value !== '' && str_contains($value, ApiKeyMasked::MASK_CHAR)) {
            $this->setValue((string)$this->getOldValue());

            return $this;
        }

        parent::beforeSave();

        return $this;
    }
}
