<?php

declare(strict_types=1);

namespace Plugin\tnt_international_phone\src\Service;

use JTL\DB\DbInterface;
use stdClass;
use Throwable;

/**
 * Persists auto-normalized phone submissions (original input -> E.164 result) to the
 * plugin's own log table (see Migrations), so the admin audit report can show what was
 * silently changed on save.
 */
final class ModifiedPhoneLogger implements ModifiedPhoneLoggerInterface
{
    public const TABLE = 'tnt_ip_modified_phone';

    public function __construct(private readonly DbInterface $db)
    {
    }

    public function log(string $form, string $field, string $before, string $after, ?string $countryHint): void
    {
        $row               = new stdClass();
        $row->form         = mb_substr($form, 0, 64);
        $row->field        = mb_substr($field, 0, 32);
        $row->before_value = mb_substr($before, 0, 255);
        $row->after_value  = mb_substr($after, 0, 255);
        $row->country_hint = $countryHint !== null ? mb_substr($countryHint, 0, 8) : null;
        $row->created_at   = date('Y-m-d H:i:s');
        try {
            $this->db->insertRow(self::TABLE, $row);
        } catch (Throwable) {
            // fail open: logging must never break a storefront form submit
        }
    }
}
