<?php

namespace App\Concerns;

trait CurrencyStripping
{
    protected function stripCurrencyDot(array $data, string ...$fields): array
    {
        foreach ($fields as $field) {
            $data = $this->stripField($data, $field);
        }

        return $data;
    }

    private function stripField(array $data, string $field): array
    {
        if (str_contains($field, '*')) {
            return $this->stripNestedField($data, $field);
        }

        if (isset($data[$field]) && is_string($data[$field])) {
            $data[$field] = (int) str_replace('.', '', $data[$field]);
        }

        return $data;
    }

    private function stripNestedField(array $data, string $pattern): array
    {
        $parts = explode('.', $pattern);
        $this->stripNestedRecursive($data, $parts);

        return $data;
    }

    private function stripNestedRecursive(array &$data, array $parts): void
    {
        $current = array_shift($parts);

        if ($current === '*') {
            if (is_array($data)) {
                foreach ($data as &$item) {
                    $this->stripNestedRecursive($item, $parts);
                }
            }
        } elseif (empty($parts)) {
            if (isset($data[$current]) && is_string($data[$current])) {
                $data[$current] = (int) str_replace('.', '', $data[$current]);
            }
        } else {
            if (isset($data[$current]) && is_array($data[$current])) {
                $this->stripNestedRecursive($data[$current], $parts);
            }
        }
    }
}
