<?php

namespace App\Imports\QuickBooks\Concerns;

trait InteractsWithQuickBooksRows
{
    protected function normalizeRow($row): array
    {
        return collect($row)->mapWithKeys(function ($value, $key) {
            $normalized = strtolower(trim(preg_replace('/[\s_]+/', ' ', (string) $key)));

            return [$normalized => $value];
        })->all();
    }

    protected function value(array $row, array $keys): mixed
    {
        foreach ($keys as $key) {
            $normalized = strtolower(trim(preg_replace('/\s+/', ' ', $key)));

            if (array_key_exists($normalized, $row)) {
                return $row[$normalized];
            }
        }

        return null;
    }

    protected function clean(mixed $value): string
    {
        return trim((string) $value);
    }

    protected function isBlank(mixed $value): bool
    {
        return $this->clean($value) === '';
    }

    protected function activeValue(mixed $value): bool
    {
        $value = strtolower($this->clean($value));

        if ($value === '') {
            return true;
        }

        return !in_array($value, ['0', 'no', 'false', 'inactive'], true);
    }

    protected function personName(array $row): ?string
    {
        $first = $this->clean($this->value($row, ['first name']));
        $middle = $this->clean($this->value($row, ['m.i.', 'm i', 'mi', 'middle initial']));
        $last = $this->clean($this->value($row, ['last name']));

        $name = trim(implode(' ', array_filter([$first, $middle, $last])));

        return $name !== '' ? $name : null;
    }
}
