<?php

namespace Velis\Dto\Validators;

use Attribute;

#[Attribute]
class NipValidator extends BaseValidator
{
    public string $message = 'Invalid NIP';

    public function validate($value): bool
    {
        if (!is_string($value) || preg_match('/[^0-9-]/', $value)) {
            return false;
        }

        $value = preg_replace('/[^0-9]/', '', $value);

        if (strlen($value) !== 10) {
            return false;
        }

        $weights = [6, 5, 7, 2, 3, 4, 5, 6, 7];
        $sum = 0;

        for ($i = 0; $i < 9; $i++) {
            $sum += $weights[$i] * $value[$i];
        }

        return $sum !== 10 && $sum % 11 === (int)$value[9];
    }
}
