<?php

declare(strict_types=1);

namespace Plugin\tnt_international_phone\src\Service;

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

/**
 * Persists invalid phone submissions to the plugin's own log table (see Migrations).
 */
final class InvalidPhoneLogger implements InvalidPhoneLoggerInterface
{
    public const TABLE = 'tnt_ip_invalid_phone';

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

    public function log(string $form, string $field, string $raw, ?string $countryHint, string $reason): void
    {
        $row               = new stdClass();
        $row->form         = mb_substr($form, 0, 64);
        $row->field        = mb_substr($field, 0, 32);
        $row->raw_value    = mb_substr($raw, 0, 255);
        $row->country_hint = $countryHint !== null ? mb_substr($countryHint, 0, 8) : null;
        $row->reason       = mb_substr($reason, 0, 64);
        $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
        }
    }
}
