<?php

namespace App\Services\Schema;

class SchemaDefaults
{
    public function applyDefaults(array $schema, array $data): array
    {
        foreach (($schema['fields'] ?? []) as $f) {
            $key = $f['key'] ?? null;
            if (!$key) continue;

            if (!array_key_exists($key, $data) && array_key_exists('default', $f)) {
                $data[$key] = $f['default'];
            }

            if (($f['type'] ?? '') === 'repeater' && isset($data[$key]) && is_array($data[$key])) {
                // apply defaults in repeater items
                $subFields = $f['fields'] ?? [];
                foreach ($data[$key] as $idx => $item) {
                    if (!is_array($item)) continue;

                    foreach ($subFields as $sf) {
                        $sk = $sf['key'] ?? null;
                        if (!$sk) continue;

                        if (!array_key_exists($sk, $item) && array_key_exists('default', $sf)) {
                            $data[$key][$idx][$sk] = $sf['default'];
                        }
                    }
                }
            }
        }

        return $data;
    }
}
