<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Repository;

use Paysera\PrestashopPayments\Dto\PayseraPaymentMethod;
use Paysera\PrestashopPayments\Installer\DatabaseInstaller;
use Psr\Clock\ClockInterface;
use Psr\Log\LoggerInterface;

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

class PayseraPaymentMethodRepository
{
    public function __construct(
        private LoggerInterface $logger,
        private ClockInterface $clock
    ) {
    }

    public function findByKey(string $key): ?PayseraPaymentMethod
    {
        if ($key === '') {
            return null;
        }

        $sql = sprintf(
            'SELECT * FROM `%s` WHERE `key` = \'%s\'',
            $this->tableName(),
            pSQL($key)
        );

        $row = \Db::getInstance()->getRow($sql);

        if (!is_array($row) || $row === []) {
            return null;
        }

        return new PayseraPaymentMethod(
            (string) ($row['key'] ?? ''),
            (string) ($row['title'] ?? '')
        );
    }

    public function save(PayseraPaymentMethod $method): void
    {
        $key = $method->getKey();

        if ($key === '') {
            return;
        }

        $now = $this->clock->now()->format('Y-m-d H:i:s');

        $sql = sprintf(
            'INSERT INTO `%s` (`key`, `title`, `date_add`, `date_upd`) '
            . 'VALUES (\'%s\', \'%s\', \'%s\', \'%s\') '
            . 'ON DUPLICATE KEY UPDATE `title` = VALUES(`title`), `date_upd` = VALUES(`date_upd`)',
            $this->tableName(),
            pSQL($key),
            pSQL($method->getTitle()),
            pSQL($now),
            pSQL($now)
        );

        \Db::getInstance()->execute($sql);

        $this->logger->debug('Paysera payment method row saved', [
            'key' => $key,
        ]);
    }

    private function tableName(): string
    {
        return _DB_PREFIX_ . DatabaseInstaller::TABLE_PAYMENT_METHOD;
    }
}
